text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { Buffer } from 'buffer';
import { U2F } from '../../src';
import { mergeMap } from 'rxjs';
describe('- Integration u2f.test.ts file', () => {
/**
* Test if U2F.decodeAuthKey() function returns the same value than initial value in base32
*/
test('- `U2F.decodeAuthKey()` must return the same value than initial value in base32', (done) => {
U2F.encodeAuthKey(Buffer.from('secret key'))
.pipe(
mergeMap(_ => U2F.decodeAuthKey(_))
).subscribe(_ => {
expect(_.toString('hex')).toBe(Buffer.from('secret key').toString('hex'));
done();
});
});
/**
* Test if U2F._cleanBase32Key() function returns good value
*/
test('- `U2F._cleanBase32Key()` must return good value - 1', (done) => {
U2F[ '_cleanBase32Key' ]('RHCQ 3M3Y P5KY U4VS 7KGT 2IUH R7M4 TEC5').subscribe(_ => {
expect(_).toBe('RHCQ3M3YP5KYU4VS7KGT2IUHR7M4TEC5');
done();
});
});
test('- `U2F._cleanBase32Key()` must return good value - 2', (done) => {
U2F[ '_cleanBase32Key' ]('RHCQ 3M3Y P5KY U4V_ 7KG- 2IU. R7M4 TEC5').subscribe(_ => {
expect(_).toBe('RHCQ3M3YP5KYU4V7KG2IUR7M4TEC5');
done();
});
});
/**
* Test if U2F.generateTOTPUri() function returns good value with good parameters
*/
test('- `U2F.generateTOTPUri()` - secret => \'RHCQ 3M3Y P5KY U4VS 7KGT 2IUH R7M4 TEC5\',' +
'account_name => \'akanass\', issuer => \'rx-otp\' and options => {time:30, code_digits:6, algorithm:\'SHA512\'}', (done) => {
U2F.generateTOTPUri('RHCQ 3M3Y P5KY U4VS 7KGT 2IUH R7M4 TEC5', 'akanass', 'rx-otp')
.subscribe(_ => {
expect(_).toBe('otpauth://totp/rx-otp:akanass?secret=RHCQ3M3YP5KYU4VS7KGT2IUHR7M4TEC5' +
'&issuer=rx-otp&algorithm=SHA512&digits=6&period=30');
done();
});
});
test('- `U2F.generateTOTPUri()` - secret => \'RHCQ 3M3Y P5KY U4VS 7KGT 2IUH R7M4 TEC5\',' +
'account_name => \'akanass\', issuer => \'rx-otp\' and options => {time:10, code_digits:8, algorithm:\'SHA1\'}', (done) => {
U2F.generateTOTPUri('RHCQ 3M3Y P5KY U4VS 7KGT 2IUH R7M4 TEC5', 'akanass', 'rx-otp', {
time: 10,
code_digits: 8,
algorithm: 'SHA1'
})
.subscribe(_ => {
expect(_).toBe('otpauth://totp/rx-otp:akanass?secret=RHCQ3M3YP5KYU4VS7KGT2IUHR7M4TEC5' +
'&issuer=rx-otp&algorithm=SHA1&digits=8&period=10');
done();
});
});
/**
* Test if U2F.generateAuthToken() function returns good value with good parameters
*/
test('- `U2F.generateAuthToken()` - secret => \'RHCQ 3M3Y P5KY U4VS 7KGT 2IUH R7M4 TEC5\' and options => ' +
'{time:30, timestamp:59000, code_digits:6, add_checksum:false, truncation_offset: -1, algorithm:\'SHA512\'}', (done) => {
U2F.generateAuthToken('RHCQ 3M3Y P5KY U4VS 7KGT 2IUH R7M4 TEC5', { timestamp: 59000 })
.subscribe(_ => {
expect(_).toBe('766122');
done();
});
});
/**
* Test if U2F.verifyAuthToken() function returns good value with good parameters
*/
test('- `U2F.verifyAuthToken()` - token: \'766122\', secret => \'RHCQ 3M3Y P5KY U4VS 7KGT 2IUH R7M4 TEC5\' and options => ' +
'{time:30, timestamp:59000, code_digits:6, add_checksum:false, truncation_offset: -1, algorithm:\'SHA512\'}', (done) => {
U2F.verifyAuthToken('766122', 'RHCQ 3M3Y P5KY U4VS 7KGT 2IUH R7M4 TEC5', { timestamp: 59000 })
.subscribe(_ => {
expect(_).toEqual({
delta: 0,
delta_format: 'int'
});
done();
});
});
/**
* Test if U2F.qrCode() function returns good value with good parameters
*/
test('- `U2F.qrCode()` must return a svg', (done) => {
U2F.generateTOTPUri('RHCQ 3M3Y P5KY U4VS 7KGT 2IUH R7M4 TEC5', 'akanass', 'rx-otp')
.pipe(
mergeMap(_ => U2F.qrCode(_))
)
.subscribe(_ => {
expect(_).toEqual('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 47 47">' +
'<path d="M1 1h7v7h-7zM12 1h1v1h-1zM14 1h7v2h-1v-1h-3v1h-1v-1h-1v1h1v1h1v2h1v2h1v-2h1v2h1v-2h-1v-1h-1v1h-' +
'1v-2h-1v-1h3v1h1v-1h1v1h1v1h3v-2h-1v1h-1v-1h-1v-1h-1v-1h2v1h2v-1h1v1h1v1h-1v3h1v2h-1v-1h-1v1h1v1h-1v1h-' +
'1v1h-2v-1h-3v2h-1v-1h-3v-1h1v-1h-1v1h-1v-1h-1v-1h1v-1h1v1h1v-1h-1v-1h-2v-1h1v-1h-1v1h-1v-3h1zM29 ' +
'1h1v3h-1zM31 1h1v1h-1zM37 1h1v1h-1zM39 1h7v7h-7zM2 2v5h5v-5zM34 2h1v2h-2v1h-1v1h1v1h-1v1h1v-1h1v2h-1v5h1v1h' +
'-3v-1h1v-1h-1v-1h1v-1h-1v-1h1v-1h-1v-2h-1v-3h2v-1h2zM36 2h1v2h1v2h-3v-1h1zM40 2v5h5v-5zM3 3h3v3h-3zM9 3h3v1h' +
'-2v1h1v1h-1v3h-1zM41 3h3v3h-3zM28 4h1v1h-1zM12 6h1v1h-1zM22 6v3h3v-3zM34 6h1v1h-1zM11 7h1v1h1v1h1v3h1v1h-1v1h1v' +
'-1h1v-1h1v2h-1v3h2v-3h1v1h1v1h1v1h-1v3h1v1h-1v1h-2v-1h1v-1h-1v-1h1v-1h-1v1h-2v-1h-3v-2h-1v1h-1v1h-2v-1h1v-1h1v' +
'-1h1v-1h1v-2h-2v1h1v1h-1v1h-1v1h-1v-1h-1v-1h2v-1h-2v-1h-1v-1h2v1h1v-1h1zM13 7h1v1h-1zM23 7h1v1h-1zM29 7h1v2h-1zM35' +
' 7h1v1h1v-1h1v2h-2v1h-1zM1 9h1v1h1v1h2v-1h-2v-1h5v1h-2v2h-1v1h-1v1h-2v-1h1v-1h-1v-1h-1zM18 9v1h1v-1zM39 9h5v1h2v1h' +
'-1v1h1v3h-3v1h2v1h1v2h-2v-1h-1v-1h-1v-3h2v-1h-3v-1h1v-2h-3zM9 10h1v1h-1zM26 10h1v1h1v1h-1v1h-1v1h-2v1h-1v-1h-1v2h' +
'-1v-1h-1v-1h1v-1h-1v-1h2v1h3v-2h1zM29 10h1v1h1v1h-1v1h-2v-1h1zM34 10h1v1h1v1h-1v1h-1zM36 10h3v1h1v1h-1v1h-1v2h3v2h' +
'-1v-1h-1v3h-2v-1h1v-2h-1v-1h-1v-1h1v-1h-1v-1h2v-1h-2zM15 11h1v1h-1zM22 11h1v1h-1zM1 12h1v1h-1zM18 12h1v1h-1zM5' +
' 13h3v1h-1v1h1v1h-5v-1h1v-1h1v1h1v-1h-1zM19 13h1v1h-1zM30 13h1v1h-1zM35 13h1v1h-1zM40 13h1v1h-1zM26 14h1v3h' +
'-1v1h1v1h1v1h-3v1h1v1h1v1h-1v4h-4v1h-1v-1h-2v-1h1v-1h1v-2h-1v-1h1v-1h3v-2h1v-2h-1v-2h2zM28 14h1v2h1v-1h1v3h1v1h' +
'-1v1h-2v-1h1v-2h-2zM1 15h1v1h1v1h-2zM8 16h1v1h-1zM22 16h1v1h-1zM32 16h4v1h-3v1h-1zM3 17h3v1h-1v1h-4v-1h2zM7' +
' 17h1v1h-1zM21 17h1v1h-1zM23 17h1v1h-1zM8 18h1v1h1v1h2v2h-2v1h1v1h-1v2h-4v1h3v1h-3v1h-1v1h1v1h-1v2h3v1h' +
'-1v1h-1v-1h-2v-2h-2v1h-1v-5h2v3h1v-3h1v-4h-1v1h-2v-1h1v-1h1v-2h1v-2h1v2h2v-1h-1v-1h1zM11 18h2v1h-2zM22' +
' 18h1v1h-1zM40 18h1v1h-1zM42 18h1v1h1v4h1v1h1v1h-3v1h-4v1h-1v1h2v1h-1v1h-1v-1h-2v-1h1v-1h-1v-1h1v-3h-1v' +
'-1h1v-1h1v-1h1v1h2v-1h1zM14 19h1v1h-1zM32 19h1v1h1v1h-1v2h-2v-3h1zM35 19h1v1h-1zM2 20h1v1h-1zM13' +
' 20h1v3h-1zM17 20h1v1h-1zM45 20h1v1h-1zM27 21h1v1h-1zM34 21h1v1h-1zM1 22h1v1h-1zM6 22v3h3v-3zM17' +
' 22h1v1h-1zM22 22v3h3v-3zM38 22v3h3v-3zM45 22h1v1h-1zM7 23h1v1h-1zM12 23h1v1h-1zM15' +
' 23h2v2h2v1h-1v2h-1v1h-2v-1h1v-1h-1v1h-2v-1h1v-1h-1v-1h1v-1h1zM18 23h1v1h-1zM23 23h1v1h-1zM27' +
' 23h4v2h2v3h2v1h-3v-2h-1v2h1v1h1v1h1v1h1v1h-2v1h1v2h1v-1h1v1h2v-1h-2v-1h1v-1h2v-1h2v2h-2v3h1v-' +
'2h1v1h1v-1h1v1h1v2h1v-1h1v2h-1v1h1v3h-1v1h-1v-1h-1v-1h1v-1h-2v1h-5v1h-1v-2h1v-4h-4v-1h-1v-1h-' +
'1v1h1v1h1v1h1v1h-1v1h1v1h-1v1h1v1h-3v1h1v1h-3v1h-4v-1h3v-1h-1v-1h1v-1h-1v-3h2v-1h1v-2h-2v1h-1v-' +
'2h1v-3h2v1h-1v2h1v-1h2v-1h-1v-1h1v-1h-1v-1h-1v-1h-1v-2h1v-2h-2v-1h-1zM33 23h3v3h-1v-2h-1v1h-1zM39' +
' 23h1v1h-1zM42 23v1h1v-1zM11 24h1v2h-1zM15 25v1h1v-1zM3 26h1v1h-1zM10 26h1v1h-1zM43 26h1v1h-1zM45' +
' 26h1v1h-1zM26 27h2v1h-1v1h-1v1h1v2h-1v-1h-1v-1h-1v-1h-1v-1h3zM35 27h1v1h-1zM42 27h1v1h1v-1h1v1h1v1h' +
'-1v1h-1v-1h-1v2h2v1h-1v1h-1v-1h-1v-2h-1v-1h1zM9 28h2v1h1v1h-2v-1h-1zM12 28h1v1h-1zM19 28h1v1h-1zM7' +
' 29h2v1h1v1h-2v-1h-1zM13 29h2v1h-2zM17 29h2v2h-1v-1h-1zM27 29h1v1h-1zM12 30h1v1h-1zM15' +
' 30h2v1h1v1h1v1h-2v1h-1v-1h-1v1h1v1h1v2h2v-2h1v1h1v-1h-1v-1h1v-1h1v1h2v-1h-1v-1h3v1h-1v2h-2v1h' +
'-1v1h1v-1h3v1h1v2h-1v3h-3v1h-1v-1h-1v-2h-1v-1h-1v-1h-2v1h1v3h-2v-1h1v-1h-1v1h-1v-1h-1v-3h-1v1h' +
'-1v1h-3v-1h-2v-1h2v-1h-2v-1h2v-1h1v1h1v-1h2v1h-1v1h-1v1h1v-1h1v-1h1v1h1v1h1v-1h-1v-1h-1v-1h-1v' +
'-1h-2v1h-1v-1h-2v-1h3v-1h1v1h1v-1h1v1h2v-1h-1zM28 30h2v1h-2zM34 30h1v1h-1zM45 30h1v1h-1zM6' +
' 31h2v1h-2zM30 31h1v1h-1zM35 31h1v1h-1zM37 31h2v1h-2zM19 33h1v1h-1zM35 33h1v1h-1zM42 33h1v1h-1zM45 33h1v1h-1zM17' +
' 34h2v1h-2zM43 34h2v2h-1v-1h-1zM5 35h1v3h-2v-1h-2v-1h3zM1 37h1v1h-1zM42 37v3h1v-3zM22 38v3h3v-3zM38 38v3h3v-3zM1' +
' 39h7v7h-7zM12 39h1v1h1v1h-3v-1h1zM23 39h1v1h-1zM30 39v2h-1v2h1v-1h2v-1h-1v-2zM34 39h2v1h-2zM39 39h1v1h-1zM2' +
' 40v5h5v-5zM9 40h1v1h1v1h5v2h-1v-1h-1v1h-1v-1h-1v1h-3zM3 41h3v3h-3zM34 41h1v1h-1zM18 42h1v1h-1zM26 42h1v1h-1zM17' +
' 43h1v1h-1zM19 43h2v1h-1v1h-1zM23 43h3v1h-1v1h-1v1h-2v-1h1zM34 43h2v1h-1v1h-1zM37 43h3v1h-2v1h2v1h-3v-1h-1v-1h1zM12' +
' 44h1v1h-1zM14 44h1v1h1v1h-2zM21 44h1v1h-1zM40 44h1v1h-1zM42 44h2v1h-2zM9 45h3v1h-3zM20 45h1v1h-1zM32' +
' 45h1v1h-1zM35 45h1v1h-1zM44 45h1v1h-1z"/></svg>');
done();
});
});
test('- `U2F.qrCode()` must return a png in Buffer format', (done) => {
U2F.qrCode('text', { type: 'png' }).subscribe(_ => {
expect(Buffer.isBuffer(_)).toBeTruthy();
done();
});
});
test('- `U2F.qrCode()` must return a png in Buffer format with specific size', (done) => {
U2F.qrCode('text', { type: 'png', size: 3 }).subscribe(_ => {
expect(Buffer.isBuffer(_)).toBeTruthy();
done();
});
});
}); | the_stack |
import { Trans } from "@lingui/macro";
import { i18nMark, withI18n } from "@lingui/react";
import classNames from "classnames";
import isEqual from "lodash.isequal";
import { MountService } from "foundation-ui";
import { Hooks } from "PluginSDK";
import PropTypes from "prop-types";
import * as React from "react";
import { deepCopy, findNestedPropertyInObject } from "#SRC/js/utils/Util";
import AdvancedSection from "#SRC/js/components/form/AdvancedSection";
import AdvancedSectionContent from "#SRC/js/components/form/AdvancedSectionContent";
import AdvancedSectionLabel from "#SRC/js/components/form/AdvancedSectionLabel";
import Batch from "#SRC/js/structs/Batch";
import DataValidatorUtil from "#SRC/js/utils/DataValidatorUtil";
import ErrorMessageUtil from "#SRC/js/utils/ErrorMessageUtil";
import ErrorsAlert from "#SRC/js/components/ErrorsAlert";
import FluidGeminiScrollbar from "#SRC/js/components/FluidGeminiScrollbar";
import PageHeaderNavigationDropdown from "#SRC/js/components/PageHeaderNavigationDropdown";
import SplitPanel, {
PrimaryPanel,
SidePanel,
} from "#SRC/js/components/SplitPanel";
import TabButton from "#SRC/js/components/TabButton";
import TabButtonList from "#SRC/js/components/TabButtonList";
import Tabs from "#SRC/js/components/Tabs";
import TabView from "#SRC/js/components/TabView";
import TabViewList from "#SRC/js/components/TabViewList";
import Transaction from "#SRC/js/structs/Transaction";
import * as TransactionTypes from "#SRC/js/constants/TransactionTypes";
import FormErrorUtil, { FormError } from "#SRC/js/utils/FormErrorUtil";
import { getContainerNameWithIcon } from "../../utils/ServiceConfigDisplayUtil";
import ArtifactsSection from "../forms/ArtifactsSection";
import ContainerServiceFormSection from "../forms/ContainerServiceFormSection";
import CreateServiceModalFormUtil from "../../utils/CreateServiceModalFormUtil";
import EnvironmentFormSection from "../forms/EnvironmentFormSection";
import GeneralServiceFormSection from "../forms/GeneralServiceFormSection";
import HealthChecksFormSection from "../forms/HealthChecksFormSection";
import MultiContainerHealthChecksFormSection from "../forms/MultiContainerHealthChecksFormSection";
import MultiContainerNetworkingFormSection from "../forms/MultiContainerNetworkingFormSection";
import MultiContainerVolumesFormSection from "../forms/MultiContainerVolumesFormSection";
import MultiContainerFormAdvancedSection from "../forms/MultiContainerFormAdvancedSection";
import PlacementSection from "../forms/PlacementSection";
import NetworkingFormSection from "../forms/NetworkingFormSection";
import PodSpec from "../../structs/PodSpec";
import ServiceErrorMessages from "../../constants/ServiceErrorMessages";
import ServiceErrorPathMapping from "../../constants/ServiceErrorPathMapping";
import ServiceErrorTabPathRegexes from "../../constants/ServiceErrorTabPathRegexes";
import ServiceUtil from "../../utils/ServiceUtil";
import VolumesFormSection from "../forms/VolumesFormSection";
import ApplicationSpec from "../../structs/ApplicationSpec";
import ServiceSpec from "../../structs/ServiceSpec";
/**
* Since the form input fields operate on a different path than the one in the
* data, it's not always possible to figure out which error paths to unmute when
* the field is edited. Therefore, form fields that do not map 1:1 with the data
* are opted out from the error muting feature.
*
* TODO: This should be removed when DCOS-13524 is completed
*/
const CONSTANTLY_UNMUTED_ERRORS = [
/^constraints\.[0-9]+\./,
/^portDefinitions\.[0-9]+\./,
/^container.docker.portMappings\.[0-9]+\./,
/^volumes\.[0-9]+\./,
];
function cleanConfig(config) {
const { labels = {}, env = {}, environment = {}, ...serviceConfig } = config;
let newServiceConfig = CreateServiceModalFormUtil.stripEmptyProperties(
serviceConfig
);
if (Object.keys(labels).length !== 0) {
newServiceConfig = { labels, ...newServiceConfig };
}
if (Object.keys(env).length !== 0) {
newServiceConfig = { env, ...newServiceConfig };
}
if (Object.keys(environment).length !== 0) {
newServiceConfig = { environment, ...newServiceConfig };
}
return newServiceConfig;
}
const JSONEditor = React.lazy(
() =>
import(/* webpackChunkName: "jsoneditor" */ "#SRC/js/components/JSONEditor")
);
class CreateServiceModalForm extends React.Component<
{
activeTab?: string;
errors: FormError[];
expandAdvancedSettings: boolean;
handleTabChange: (a: string) => void;
inputConfigReducers: unknown;
isEdit: boolean;
isJSONModeActive: boolean;
onChange: (s: ServiceSpec) => void;
onConvertToPod: (spec: unknown) => void;
onErrorsChange: (e: FormError[]) => void;
resetExpandAdvancedSettings: () => void;
service: ApplicationSpec;
showAllErrors: boolean;
},
{
appConfig: {} | null;
baseConfig: unknown;
batch: Batch;
editedFieldPaths: string[];
editingFieldPath: null | string;
editorWidth?: number;
isPod: boolean;
}
> {
static defaultProps = {
errors: [],
expandAdvancedSettings: false,
handleTabChange() {},
isJSONModeActive: false,
onChange() {},
onErrorStateChange() {},
showAllErrors: false,
};
static propTypes = {
activeTab: PropTypes.string,
errors: PropTypes.array,
expandAdvancedSettings: PropTypes.bool,
handleTabChange: PropTypes.func,
isJSONModeActive: PropTypes.bool,
onChange: PropTypes.func,
onErrorStateChange: PropTypes.func,
service: PropTypes.object,
showAllErrors: PropTypes.bool,
resetExpandAdvancedSettings: PropTypes.func,
};
constructor(props) {
super(props);
// Hint: When you add something to the state, make sure to update the
// shouldComponentUpdate function, since we are trying to reduce
// the number of updates as much as possible.
// In the Next line we are destructing the config to keep labels as it is and even keep labels with an empty value
const newServiceConfig = cleanConfig(
ServiceUtil.getServiceJSON(props.service)
);
this.state = {
appConfig: null,
batch: new Batch(),
editedFieldPaths: [],
editingFieldPath: null,
...this.getNewStateForJSON(
newServiceConfig,
props.service instanceof PodSpec
),
};
}
UNSAFE_componentWillReceiveProps(nextProps) {
const prevJSON = ServiceUtil.getServiceJSON(this.props.service);
const nextJSON = ServiceUtil.getServiceJSON(nextProps.service);
const isPod = nextProps.service instanceof PodSpec;
// Note: We ignore changes that might derive from the `onChange` event
// handler. In that case the contents of nextJSON would be the same
// as the contents of the last rendered appConfig in the state.
if (
this.state.isPod !== isPod ||
(!isEqual(prevJSON, nextJSON) &&
!isEqual(this.state.appConfig, nextJSON) &&
!isEqual(this.props.errors, nextProps.errors))
) {
this.setState(this.getNewStateForJSON(nextJSON, isPod));
}
}
componentDidUpdate(_, prevState) {
const { editingFieldPath, appConfig } = this.state;
const { onChange, service } = this.props;
if (this.props.expandAdvancedSettings) {
this.props.resetExpandAdvancedSettings();
}
const shouldUpdate =
editingFieldPath === null &&
(prevState.editingFieldPath !== null ||
!isEqual(appConfig, prevState.appConfig));
if (shouldUpdate) {
onChange(service.constructor(appConfig));
}
}
shouldComponentUpdate(nextProps, nextState) {
// Update if json state changed
if (this.props.isJSONModeActive !== nextProps.isJSONModeActive) {
return true;
}
// Update if showAllErrors changed
if (this.props.showAllErrors !== nextProps.showAllErrors) {
return true;
}
// Update if pod type changed
if (this.state.isPod !== nextProps.service instanceof PodSpec) {
return true;
}
// Update if service property has changed
//
// Note: We ignore changes that might derrive from the `onChange` event
// handler. In that case the contents of nextJSON would be the same
// as the contents of the last rendered appConfig in the state.
//
const prevJSON = ServiceUtil.getServiceJSON(this.props.service);
const nextJSON = ServiceUtil.getServiceJSON(nextProps.service);
if (
!isEqual(prevJSON, nextJSON) &&
!isEqual(this.state.appConfig, nextJSON)
) {
return true;
}
if (
nextProps.expandAdvancedSettings !== this.props.expandAdvancedSettings
) {
return true;
}
const didBaseConfigChange = this.state.baseConfig !== nextState.baseConfig;
const didBatchChange = this.state.batch !== nextState.batch;
const didEditingFieldPathChange =
this.state.editingFieldPath !== nextState.editingFieldPath;
const didActiveTabChange = this.props.activeTab !== nextProps.activeTab;
// Otherwise update if the state has changed
return (
didBaseConfigChange ||
didBatchChange ||
didEditingFieldPathChange ||
didActiveTabChange ||
!isEqual(this.props.errors, nextProps.errors)
);
}
getNewStateForJSON = (baseConfig = {}, isPod = this.state.isPod) => {
const newState = { baseConfig, isPod };
// Regenerate batch
newState.batch = this.props
.jsonParserReducers(deepCopy(baseConfig))
.reduce((batch, item) => batch.add(item), new Batch());
// Update appConfig
newState.appConfig = this.getAppConfig(newState.batch, baseConfig);
return newState;
};
handleConvertToPod = () => {
this.props.onConvertToPod(this.getAppConfig());
};
handleDropdownNavigationSelection = (item) => {
this.props.handleTabChange(item.id);
};
handleJSONChange = (jsonObject) => {
this.setState(this.getNewStateForJSON(jsonObject));
};
handleJSONPropertyChange = (path) => {
const { editedFieldPaths } = this.state;
const pathStr = path.join(".");
if (path.length === 0) {
return;
}
if (!editedFieldPaths.includes(pathStr)) {
this.setState({
editedFieldPaths: editedFieldPaths.concat([pathStr]),
});
}
};
handleJSONErrorStateChange = (errorMessage) => {
if (errorMessage !== null) {
this.props.onErrorsChange([{ message: errorMessage, path: [] }]);
} else {
this.props.onErrorsChange([]);
}
};
handleFormBlur = (event) => {
const { editedFieldPaths } = this.state;
const fieldName = event.target.name;
if (!fieldName) {
return;
}
const newState = { editingFieldPath: null };
// Keep track of which fields have changed
if (!editedFieldPaths.includes(fieldName)) {
newState.editedFieldPaths = editedFieldPaths.concat([fieldName]);
}
this.setState(newState);
};
handleFormFocus = (event) => {
const fieldName = event.target.getAttribute("name");
const newState = {
editingFieldPath: fieldName,
};
if (!fieldName) {
return;
}
this.setState(newState);
};
addTransaction = (t) => {
const batch = this.state.batch.add(t);
this.setState({ appConfig: this.getAppConfig(batch), batch });
};
handleFormChange = ({ target }) => {
if (!target.name) {
return;
}
const path = target.name.split(".");
const value = target.type === "checkbox" ? target.checked : target.value;
this.addTransaction(new Transaction(path, value));
};
handleAddItem = ({ path, value }) => {
this.addTransaction(
new Transaction(path.split("."), value, TransactionTypes.ADD_ITEM)
);
};
handleRemoveItem = ({ path, value }) => {
this.addTransaction(
new Transaction(path.split("."), value, TransactionTypes.REMOVE_ITEM)
);
};
handleClickItem = (item) => {
this.props.handleTabChange(item);
};
getAppConfig(batch = this.state.batch, baseConfig = this.state.baseConfig) {
// Do a deepCopy once before it goes to reducers
// so they don't need to perform Object.assign()
const baseConfigCopy = deepCopy(baseConfig);
const newConfig = batch.reduce(
this.props.jsonConfigReducers,
baseConfigCopy
);
// In the Next line we are destructing the config to keep labels as it is and even keep labels with an empty value
return cleanConfig(newConfig);
}
getErrors() {
return ErrorMessageUtil.translateErrorMessages(
this.props.errors,
ServiceErrorMessages,
this.props.i18n
);
}
getContainerList(data) {
if (Array.isArray(data.containers) && data.containers.length !== 0) {
return data.containers.map((item, index) => {
const fakeContainer = { name: item.name || `container-${index + 1}` };
return {
className: "text-overflow",
id: `container${index}`,
label: getContainerNameWithIcon(fakeContainer),
isContainer: true,
};
});
}
return null;
}
getContainerContent(data, errors) {
const { service, showAllErrors } = this.props;
const { containers } = data;
if (containers == null) {
return [];
}
return containers.map((_, index) => {
const artifactsPath = `containers.${index}.artifacts`;
const artifacts = findNestedPropertyInObject(data, artifactsPath) || [];
const artifactErrors =
findNestedPropertyInObject(errors, artifactsPath) || [];
return (
<TabView key={index} id={`container${index}`}>
<ErrorsAlert
errors={this.getErrors()}
pathMapping={ServiceErrorPathMapping}
hideTopLevelErrors={!showAllErrors}
/>
<Trans render="h1" className="flush-top short-bottom">
Container
</Trans>
<Trans render="p">
Configure your container below. Enter a container image or command
you want to run.
</Trans>
<ContainerServiceFormSection
data={data}
errors={errors}
onAddItem={this.handleAddItem}
onRemoveItem={this.handleRemoveItem}
path={`containers.${index}`}
service={service}
/>
<AdvancedSection>
<AdvancedSectionLabel>
<Trans render="span">More Settings</Trans>
</AdvancedSectionLabel>
<AdvancedSectionContent>
<MultiContainerFormAdvancedSection
data={data}
path={`containers.${index}`}
/>
<ArtifactsSection
data={artifacts}
path={artifactsPath}
errors={artifactErrors}
onRemoveItem={this.handleRemoveItem}
onAddItem={this.handleAddItem}
/>
</AdvancedSectionContent>
</AdvancedSection>
</TabView>
);
});
}
getFormDropdownList(navigationItems, activeTab, { isNested = false } = {}) {
return navigationItems.reduce((accumulator, item, index) => {
accumulator.push({
className: classNames({ "page-header-menu-item-nested": isNested }),
id: item.id,
isActive: activeTab === item.id || (activeTab == null && index === 0),
label: item.label,
});
if (item.children) {
accumulator = accumulator.concat(
this.getFormDropdownList(item.children, activeTab, { isNested: true })
);
}
return accumulator;
}, []);
}
getFormNavigationItems(appConfig, data) {
// L10NTODO: Pluralize
const serviceLabel =
(findNestedPropertyInObject(appConfig, "containers.length") || 1) === 1
? "Service"
: "Services";
type Tab = {
id: string;
label: string;
key?: string;
children?: unknown;
};
let tabList: Tab[] = [
{
id: "services",
label: serviceLabel,
children: this.getContainerList(data),
},
];
if (this.state.isPod) {
tabList.push(
{ id: "placement", key: "placement", label: i18nMark("Placement") },
{
id: "networking",
key: "multinetworking",
label: i18nMark("Networking"),
},
{ id: "volumes", key: "multivolumes", label: i18nMark("Volumes") },
{
id: "healthChecks",
key: "multihealthChecks",
label: i18nMark("Health Checks"),
},
{
id: "environment",
key: "multienvironment",
label: i18nMark("Environment"),
}
);
tabList = Hooks.applyFilter(
"createServiceMultiContainerTabList",
tabList
);
} else {
tabList.push(
{ id: "placement", key: "placement", label: i18nMark("Placement") },
{ id: "networking", key: "networking", label: i18nMark("Networking") },
{ id: "volumes", key: "volumes", label: i18nMark("Volumes") },
{
id: "healthChecks",
key: "healthChecks",
label: i18nMark("Health Checks"),
},
{
id: "environment",
key: "environment",
label: i18nMark("Environment"),
}
);
tabList = Hooks.applyFilter(
"createServiceMultiContainerTabList",
tabList
);
}
return tabList;
}
getFormTabList(navigationItems) {
if (navigationItems == null) {
return null;
}
const errorsByTab = FormErrorUtil.getTopLevelTabErrors(
this.props.errors,
ServiceErrorTabPathRegexes,
ServiceErrorPathMapping,
this.props.i18n
);
return navigationItems.map((item) => {
const finalErrorCount = item.isContainer
? findNestedPropertyInObject(
FormErrorUtil.getContainerTabErrors(errorsByTab),
`${item.id}.length`
)
: findNestedPropertyInObject(errorsByTab, `${item.id}.length`);
return (
<TabButton
className={item.className}
id={item.id}
label={
typeof item.label === "string" ? (
<Trans render="span" id={item.label} />
) : (
item.label
)
}
key={item.key || item.id}
count={finalErrorCount}
showErrorBadge={Boolean(finalErrorCount) && this.props.showAllErrors}
description={
// TODO: pluralize
<Trans render="span">
{finalErrorCount} issues need addressing
</Trans>
}
>
{this.getFormTabList(item.children)}
</TabButton>
);
});
}
getSectionContent(data, errorMap) {
const { showAllErrors } = this.props;
const errors = this.getErrors();
const pluginTabProps = {
data,
errors,
errorMap,
hideTopLevelErrors: !showAllErrors,
onAddItem: this.handleAddItem,
onRemoveItem: this.handleRemoveItem,
onTabChange: this.props.handleTabChange,
pathMapping: ServiceErrorPathMapping,
};
if (this.state.isPod) {
const tabs = [
<TabView id="placement" key="placement">
<ErrorsAlert
errors={errors}
pathMapping={ServiceErrorPathMapping}
hideTopLevelErrors={!showAllErrors}
/>
<MountService.Mount
type="CreateService:MultiContainerPlacementSection"
data={data}
errors={errorMap}
onRemoveItem={this.handleRemoveItem}
onAddItem={this.handleAddItem}
>
<PlacementSection
data={data}
errors={errorMap}
onRemoveItem={this.handleRemoveItem}
onAddItem={this.handleAddItem}
/>
</MountService.Mount>
</TabView>,
<TabView id="networking" key="multinetworking">
<ErrorsAlert
errors={errors}
pathMapping={ServiceErrorPathMapping}
hideTopLevelErrors={!showAllErrors}
/>
<MultiContainerNetworkingFormSection
data={data}
errors={errorMap}
handleTabChange={this.props.handleTabChange}
onRemoveItem={this.handleRemoveItem}
onAddItem={this.handleAddItem}
/>
</TabView>,
<TabView id="volumes" key="multivolumes">
<ErrorsAlert
errors={errors}
pathMapping={ServiceErrorPathMapping}
hideTopLevelErrors={!showAllErrors}
/>
<MultiContainerVolumesFormSection
data={data}
errors={errorMap}
handleTabChange={this.props.handleTabChange}
onRemoveItem={this.handleRemoveItem}
onAddItem={this.handleAddItem}
/>
</TabView>,
<TabView id="healthChecks" key="multihealthChecks">
<ErrorsAlert
errors={errors}
pathMapping={ServiceErrorPathMapping}
hideTopLevelErrors={!showAllErrors}
/>
<MultiContainerHealthChecksFormSection
data={data}
errors={errorMap}
handleTabChange={this.props.handleTabChange}
onRemoveItem={this.handleRemoveItem}
onAddItem={this.handleAddItem}
/>
</TabView>,
<TabView id="environment" key="multienvironment">
<ErrorsAlert
errors={errors}
pathMapping={ServiceErrorPathMapping}
hideTopLevelErrors={!showAllErrors}
/>
<EnvironmentFormSection
data={data}
onChange={this.handleFormChange}
/>
</TabView>,
];
return Hooks.applyFilter(
"createServiceMultiContainerTabViews",
tabs,
pluginTabProps
);
}
const tabs = [
<TabView id="placement" key="placement">
<ErrorsAlert
errors={errors}
pathMapping={ServiceErrorPathMapping}
hideTopLevelErrors={!showAllErrors}
/>
<MountService.Mount
type="CreateService:PlacementSection"
data={data}
errors={errorMap}
onRemoveItem={this.handleRemoveItem}
onAddItem={this.handleAddItem}
>
<PlacementSection
data={data}
errors={errorMap}
onRemoveItem={this.handleRemoveItem}
onAddItem={this.handleAddItem}
/>
</MountService.Mount>
</TabView>,
<TabView id="networking" key="networking">
<ErrorsAlert
errors={errors}
pathMapping={ServiceErrorPathMapping}
hideTopLevelErrors={!showAllErrors}
/>
<NetworkingFormSection
data={data}
errors={errorMap}
onRemoveItem={this.handleRemoveItem}
onAddItem={this.handleAddItem}
/>
</TabView>,
<TabView id="volumes" key="volumes">
<ErrorsAlert
errors={errors}
pathMapping={ServiceErrorPathMapping}
hideTopLevelErrors={!showAllErrors}
/>
<VolumesFormSection
data={data}
errors={errorMap}
onRemoveItem={this.handleRemoveItem}
onAddItem={this.handleAddItem}
onChange={this.handleFormChange}
/>
</TabView>,
<TabView id="healthChecks" key="healthChecks">
<ErrorsAlert
errors={errors}
pathMapping={ServiceErrorPathMapping}
hideTopLevelErrors={!showAllErrors}
/>
<HealthChecksFormSection
data={data}
errors={errorMap}
onRemoveItem={this.handleRemoveItem}
onAddItem={this.handleAddItem}
/>
</TabView>,
<TabView id="environment" key="environment">
<ErrorsAlert
errors={errors}
pathMapping={ServiceErrorPathMapping}
hideTopLevelErrors={!showAllErrors}
/>
<EnvironmentFormSection data={data} onChange={this.handleFormChange} />
</TabView>,
];
return Hooks.applyFilter("createServiceTabViews", tabs, pluginTabProps);
}
/**
* This function filters the error list in order to keep only the
* errors that should be displayed to the UI.
*
* @returns {Array} - Returns an array of errors that passed the filter
*/
getUnmutedErrors() {
const { showAllErrors } = this.props;
const { editedFieldPaths, editingFieldPath } = this.state;
const errors: FormError[] = [...this.getErrors()];
return errors.filter((error) => {
const errorPath = error.path.join(".");
// Always mute the error on the field we are editing
if (editingFieldPath != null && errorPath === editingFieldPath) {
return false;
}
// Never mute fields in the CONSTANTLY_UNMUTED_ERRORS fields
const isUnmuted = CONSTANTLY_UNMUTED_ERRORS.some((rule) =>
rule.test(errorPath)
);
return isUnmuted || showAllErrors || editedFieldPaths.includes(errorPath);
});
}
onEditorResize = (newSize) => {
this.setState({ editorWidth: newSize });
};
render() {
const { appConfig, batch } = this.state;
const {
activeTab,
expandAdvancedSettings,
handleTabChange,
isEdit,
isJSONModeActive,
onConvertToPod,
service,
showAllErrors,
} = this.props;
const data = batch.reduce(this.props.inputConfigReducers, {});
const unmutedErrors = this.getUnmutedErrors();
const errors = this.getErrors();
const errorMap = DataValidatorUtil.errorArrayToMap(unmutedErrors);
const navigationItems = this.getFormNavigationItems(appConfig, data);
const tabButtonListItems = this.getFormTabList(navigationItems);
const navigationDropdownItems = this.getFormDropdownList(
navigationItems,
activeTab
);
return (
<SplitPanel onResize={this.onEditorResize}>
<PrimaryPanel className="create-service-modal-form__scrollbar-container modal-body-offset gm-scrollbar-container-flex">
<PageHeaderNavigationDropdown
handleNavigationItemSelection={
this.handleDropdownNavigationSelection
}
items={navigationDropdownItems}
/>
<FluidGeminiScrollbar>
<div className="modal-body-padding-surrogate create-service-modal-form-container">
<form
className="create-service-modal-form container"
onChange={this.handleFormChange}
onBlur={this.handleFormBlur}
onFocus={this.handleFormFocus}
>
<Tabs
activeTab={activeTab}
handleTabChange={handleTabChange}
vertical={true}
>
<TabButtonList>{tabButtonListItems}</TabButtonList>
<TabViewList>
<TabView id="services">
<ErrorsAlert
errors={errors}
pathMapping={ServiceErrorPathMapping}
hideTopLevelErrors={!showAllErrors}
/>
<GeneralServiceFormSection
errors={errorMap}
expandAdvancedSettings={expandAdvancedSettings}
data={data}
isEdit={isEdit}
onConvertToPod={onConvertToPod}
service={service}
onRemoveItem={(options, event) => {
event.stopPropagation();
this.handleRemoveItem(options);
}}
onClickItem={this.handleClickItem}
onAddItem={this.handleAddItem}
/>
</TabView>
{this.getContainerContent(data, errorMap)}
{this.getSectionContent(data, errorMap)}
</TabViewList>
</Tabs>
</form>
</div>
</FluidGeminiScrollbar>
</PrimaryPanel>
<SidePanel isActive={isJSONModeActive} className="jsonEditorWrapper">
<React.Suspense fallback={<div>Loading...</div>}>
<JSONEditor
errors={errors}
onChange={this.handleJSONChange}
onPropertyChange={this.handleJSONPropertyChange}
onErrorStateChange={this.handleJSONErrorStateChange}
showGutter={true}
showPrintMargin={false}
theme="monokai"
height="100%"
value={appConfig}
width={
this.state.editorWidth ? `${this.state.editorWidth}px` : "100%"
}
/>
</React.Suspense>
</SidePanel>
</SplitPanel>
);
}
}
export default withI18n()(CreateServiceModalForm); | the_stack |
import { observable, SetterObserver, IObservable, ValueConverter, IObserverLocator } from '@aurelia/runtime-html';
import { assert, createFixture } from '@aurelia/testing';
import { noop } from '@aurelia/kernel';
import type { IObserver } from '@aurelia/runtime';
describe('3-runtime-html/decorator-observable.spec.ts', function () {
const oldValue = 'old';
const newValue = 'new';
// [UNIT] tests needed: change handler, symbol key, symbol change handler
// todo: define the spec how it should behave for:
// [INTEGRATION] tests needed: <select 2 way /> <radio 2 way />
it('initializes with TS', function () {
let callCount = 0;
class Test {
@observable
public value = oldValue;
public valueChanged() {
callCount++;
}
}
const instance = new Test();
// with TS, initialization of class field are in constructor
assert.strictEqual(callCount, 1);
assert.strictEqual(instance.value, oldValue);
assert.notInstanceOf((instance as unknown as IObservable).$observers['value'], SetterObserver);
instance.value = newValue;
assert.strictEqual(callCount, 2);
assert.strictEqual(instance.value, newValue);
});
it('should not call valueChanged when property is assigned the same value', function () {
let callCount = 0;
class Test {
@observable
public value = oldValue;
public valueChanged() {
callCount++;
}
}
const instance = new Test();
assert.strictEqual(callCount, 1);
instance.value = oldValue;
assert.strictEqual(callCount, 1);
});
it('initialize with Babel property decorator', function () {
let callCount = 0;
class Test {
public value: any;
public valueChanged() {
callCount++;
}
}
Object.defineProperty(Test.prototype, 'value', observable(Test.prototype, 'value', {
configurable: true,
writable: true,
initializer: () => oldValue
}) as unknown as PropertyDescriptor);
const instance = new Test();
assert.strictEqual(callCount, 0);
assert.strictEqual(instance.value, oldValue);
instance.value = oldValue;
assert.strictEqual(callCount, 0);
instance.value = newValue;
assert.strictEqual(callCount, 1);
});
it('should call customHandler when changing the property', function () {
let callCount = 0;
class Test {
@observable({ callback: 'customHandler' })
public value = oldValue;
public customHandler() {
callCount++;
}
}
const instance = new Test();
assert.strictEqual(callCount, 1);
instance.value = newValue;
assert.strictEqual(callCount, 2);
instance.customHandler = noop;
instance.value = oldValue;
// change handler is resolved once
assert.strictEqual(callCount, 3);
});
describe('with normal app', function () {
it('works in basic scenario', async function () {
const noValue = {};
let $div = noValue;
class App {
@observable
public div: any;
public divChanged(div) {
$div = div;
}
}
const { component, platform, testHost, tearDown, startPromise } = createFixture(`<div ref="div"></div>\${div.tagName}`, App);
await startPromise;
assert.strictEqual(testHost.textContent, 'DIV');
component.div = { tagName: 'hello' };
platform.domWriteQueue.flush();
assert.strictEqual(testHost.textContent, 'hello');
await tearDown();
});
it('works for 2 way binding', async function () {
let changeCount = 0;
class App {
@observable
public v: any;
public vChanged(input) {
changeCount++;
}
}
const { ctx, component, platform, testHost, tearDown, startPromise }
= createFixture('<input value.bind="v">', App);
await startPromise;
const input = testHost.querySelector('input')!;
assert.strictEqual(input.value, '');
component.v = 'v';
assert.strictEqual(changeCount, 1);
assert.strictEqual(input.value, '');
platform.domWriteQueue.flush();
assert.strictEqual(changeCount, 1);
assert.strictEqual(input.value, 'v');
input.value = 'vv';
input.dispatchEvent(new ctx.CustomEvent('input'));
assert.strictEqual(component.v, 'vv');
assert.strictEqual(changeCount, 2);
input.dispatchEvent(new ctx.CustomEvent('input'));
assert.strictEqual(component.v, 'vv');
assert.strictEqual(changeCount, 2);
await tearDown();
});
it('works with 2 way binding and converter', async function () {
let changeCount = 0;
class App {
@observable({
set: v => Number(v) || 0
})
public v: any;
public vChanged(input) {
changeCount++;
}
}
const { ctx, component, platform, testHost, tearDown, startPromise }
= createFixture('<input value.bind="v">', App);
await startPromise;
const input = testHost.querySelector('input')!;
assert.strictEqual(input.value, '');
component.v = 'v';
assert.strictEqual(component.v, 0);
assert.strictEqual(changeCount, 1);
assert.strictEqual(input.value, '');
platform.domWriteQueue.flush();
assert.strictEqual(changeCount, 1);
assert.strictEqual(input.value, '0');
input.value = 'vv';
input.dispatchEvent(new ctx.CustomEvent('input'));
assert.strictEqual(component.v, 0);
assert.strictEqual(changeCount, 1);
assert.strictEqual(input.value, 'vv');
platform.domWriteQueue.flush();
// for this assignment, the component.v still 0
// so there was no change, and it's not propagated back to the input
assert.strictEqual(input.value, 'vv');
assert.strictEqual(component.v, 0);
input.dispatchEvent(new ctx.CustomEvent('input'));
assert.strictEqual(component.v, 0);
assert.strictEqual(changeCount, 1);
assert.strictEqual(input.value, 'vv');
platform.domWriteQueue.flush();
assert.strictEqual(input.value, 'vv');
assert.strictEqual(component.v, 0);
// real valid input assertion
input.value = '1';
input.dispatchEvent(new ctx.CustomEvent('input'));
assert.strictEqual(component.v, 1);
assert.strictEqual(changeCount, 2);
platform.domWriteQueue.flush();
assert.strictEqual(input.value, '1');
await tearDown();
});
it('works with 2 way binding and value converter', async function () {
let changeCount = 0;
class App {
@observable({
set: v => Number(v) || 0
})
public v: any;
public vChanged(input) {
changeCount++;
}
}
const {
ctx,
component,
platform,
testHost,
tearDown,
startPromise
} = createFixture(
'<input value.bind="v | two">',
App,
[ValueConverter.define('two', class {
public fromView(v: any) {
// converting back and forth with number
// so prefixing with '0' to avoid infinite loop
return `0${v}`;
}
public toView(v: any) {
return v;
}
})]
);
await startPromise;
const input = testHost.querySelector('input')!;
assert.strictEqual(input.value, '');
component.v = 'v';
assert.strictEqual(component.v, 0);
assert.strictEqual(changeCount, 1);
assert.strictEqual(input.value, '');
platform.domWriteQueue.flush();
assert.strictEqual(changeCount, 1);
assert.strictEqual(input.value, '0');
input.value = 'vv';
input.dispatchEvent(new ctx.CustomEvent('input'));
assert.strictEqual(component.v, 0);
assert.strictEqual(changeCount, 1);
assert.strictEqual(input.value, 'vv');
platform.domWriteQueue.flush();
// for this assignment, the component.v still 0
// so there was no change, and it's not propagated back to the input
assert.strictEqual(input.value, 'vv');
assert.strictEqual(component.v, 0);
input.dispatchEvent(new ctx.CustomEvent('input'));
assert.strictEqual(component.v, 0);
assert.strictEqual(changeCount, 1);
assert.strictEqual(input.value, 'vv');
platform.domWriteQueue.flush();
assert.strictEqual(input.value, 'vv');
assert.strictEqual(component.v, 0);
// real valid input assertion
input.value = '1';
input.dispatchEvent(new ctx.CustomEvent('input'));
assert.strictEqual(component.v, 1);
assert.strictEqual(changeCount, 2);
platform.domWriteQueue.flush();
assert.strictEqual(input.value, '1');
await tearDown();
});
});
it('handle recursive changes', async function () {
const { component, appHost, startPromise, tearDown } = createFixture(`
<button click.trigger="incr()">Incr()</button>
<button click.trigger="decr()">Decr()</button>
<div id="logs"><div repeat.for="log of logs">\${log}</div></div>
`, MyApp);
await startPromise;
// from TS code compilation, field initializer is compiled to assignment in ctor
assert.deepStrictEqual(component.logs, [['P.1. countChanged()', 0]]);
component.logs.splice(0);
const [incrButton, decrButton] = Array.from(appHost.querySelectorAll('button'));
incrButton.click();
assert.deepStrictEqual(
component.logs,
(Array
.from({ length: 9 })
.reduce((acc: unknown[], _: unknown, idx: number) => {
acc.push(['P.1. countChanged()', idx + 1], ['S.1. handleChange()', idx + 1]);
return acc;
}, []) as unknown[])
.concat([
['P.1. countChanged()', 10],
['After incr()', 10]
])
);
decrButton.click();
const logs = (Array
.from({ length: 9 })
.reduce((acc: unknown[], _: unknown, idx: number) => {
acc.push(['P.1. countChanged()', idx + 1], ['S.1. handleChange()', idx + 1]);
return acc;
}, []) as unknown[])
.concat([
['P.1. countChanged()', 10],
['After incr()', 10]
]);
assert.deepStrictEqual(
component.logs,
logs
.concat(
Array
.from({ length: 9 })
.reduce((acc: unknown[], _: unknown, idx: number) => {
// start at 10 when click, but the first value log will be after the substraction of 1, which is 10 - 1
acc.push(['P.1. countChanged()', 9 - idx], ['S.1. handleChange()', 9 - idx]);
return acc;
}, []) as unknown[]
)
.concat([
['P.1. countChanged()', 0],
['After decr()', 0]
])
);
await tearDown();
});
class MyApp {
public message = 'Hello Aurelia 2!';
public logs = [];
@observable
public count: number = 0;
public countObs: IObserver;
public obsLoc: IObserverLocator;
public created() {
this.countObs = this['$controller'].container.get(IObserverLocator).getObserver(this, 'count');
this.countObs.subscribe({
handleChange: (value, oldValue) => {
if (value > 0 && value < 10) {
this.log('S.1. handleChange()', value);
if (value > oldValue) {
this.count++;
} else {
this.count--;
}
}
}
});
}
public countChanged(value: number) {
this.log('P.1. countChanged()', value);
}
public incr() {
if (this.count < 10) {
this.count++;
this.log('After incr()', this.count);
// console.assert(this.count, 9);
}
}
public decr() {
if (this.count > 0) {
this.count--;
this.log('After decr()', this.count);
// console.assert(this.count, 1);
}
}
public log(...msgs: unknown[]) {
this.logs.push(msgs);
}
}
}); | the_stack |
import { Options } from 'vue-class-component';
import { isUndefined } from '@syncfusion/ej2-base';
import { ComponentBase, EJComponentDecorator, getProps, allVue, gh } from '@syncfusion/ej2-vue-base';
import { isNullOrUndefined, getValue } from '@syncfusion/ej2-base';
import { StockChart } from '@syncfusion/ej2-charts';
import { StockChartTrendlinesDirective, StockChartTrendlineDirective, StockChartTrendlinesPlugin, StockChartTrendlinePlugin } from './trendlines.directive'
import { StockChartSeriesCollectionDirective, StockChartSeriesDirective, StockChartSeriesCollectionPlugin, StockChartSeriesPlugin } from './series.directive'
import { StockChartAxesDirective, StockChartAxisDirective, StockChartAxesPlugin, StockChartAxisPlugin } from './axes.directive'
import { StockChartRowsDirective, StockChartRowDirective, StockChartRowsPlugin, StockChartRowPlugin } from './rows.directive'
import { StockChartAnnotationsDirective, StockChartAnnotationDirective, StockChartAnnotationsPlugin, StockChartAnnotationPlugin } from './annotations.directive'
import { StockChartSelectedDataIndexesDirective, StockChartSelectedDataIndexDirective, StockChartSelectedDataIndexesPlugin, StockChartSelectedDataIndexPlugin } from './selecteddataindexes.directive'
import { StockChartPeriodsDirective, StockChartPeriodDirective, StockChartPeriodsPlugin, StockChartPeriodPlugin } from './periods.directive'
import { StockEventsDirective, StockEventDirective, StockEventsPlugin, StockEventPlugin } from './stockevents.directive'
import { StockChartIndicatorsDirective, StockChartIndicatorDirective, StockChartIndicatorsPlugin, StockChartIndicatorPlugin } from './indicators.directive'
// {{VueImport}}
export const properties: string[] = ['islazyUpdate', 'annotations', 'axes', 'background', 'border', 'chartArea', 'crosshair', 'dataSource', 'enableCustomRange', 'enablePeriodSelector', 'enablePersistence', 'enableRtl', 'enableSelector', 'exportType', 'height', 'indicatorType', 'indicators', 'isMultiSelect', 'isSelect', 'isTransposed', 'legendSettings', 'locale', 'margin', 'periods', 'primaryXAxis', 'primaryYAxis', 'rows', 'selectedDataIndexes', 'selectionMode', 'series', 'seriesType', 'stockEvents', 'theme', 'title', 'titleStyle', 'tooltip', 'trendlineType', 'width', 'zoomSettings', 'axisLabelRender', 'legendClick', 'legendRender', 'load', 'loaded', 'onZooming', 'pointClick', 'pointMove', 'rangeChange', 'selectorRender', 'seriesRender', 'stockChartMouseClick', 'stockChartMouseDown', 'stockChartMouseLeave', 'stockChartMouseMove', 'stockChartMouseUp', 'stockEventRender', 'tooltipRender'];
export const modelProps: string[] = ['dataSource'];
export const testProp: any = getProps({props: properties});
export const props = testProp[0];
export const watch = testProp[1];
export const emitProbs: any = Object.keys(watch);
emitProbs.push('modelchanged');
for (let props of modelProps) {
emitProbs.push(
'update:'+props
);
}
export const isExecute: any = gh ? false : true;
/**
* Represents Vuejs chart Component
* ```vue
* <ejs-stockchart></ejs-stockchart>
* ```
*/
@EJComponentDecorator({
props: properties,
model: {
event: 'modelchanged'
}
},isExecute)
/* Start Options({
props: props,
watch: watch,
emits: emitProbs
}) End */
export class StockChartComponent extends ComponentBase {
public ej2Instances: any;
public propKeys: string[] = properties;
public models: string[] = modelProps;
public hasChildDirective: boolean = true;
protected hasInjectedModules: boolean = true;
public tagMapper: { [key: string]: Object } = {"e-stockchart-series-collection":{"e-stockchart-series":{"e-trendlines":"e-trendline"}},"e-stockchart-axes":"e-stockchart-axis","e-stockchart-rows":"e-stockchart-row","e-stockchart-annotations":"e-stockchart-annotation","e-stockchart-selectedDataIndexes":"e-stockchart-selectedDataIndex","e-stockchart-periods":"e-stockchart-period","e-stockchart-stockevents":"e-stockchart-stockevent","e-stockchart-indicators":"e-stockchart-indicator"};
public tagNameMapper: Object = {"e-stockchart-series-collection":"e-series","e-stockchart-axes":"e-axes","e-stockchart-rows":"e-rows","e-stockchart-annotations":"e-annotations","e-stockchart-selectedDataIndexes":"e-selectedDataIndexes","e-stockchart-periods":"e-periods","e-stockchart-stockevents":"e-stockEvents","e-stockchart-indicators":"e-indicators"};
public isVue3: boolean;
public templateCollection: any;
constructor() {
super(arguments);
this.isVue3 = !isExecute;
this.ej2Instances = new StockChart({}); this.ej2Instances._trigger = this.ej2Instances.trigger;
this.ej2Instances.trigger = this.trigger;
this.bindProperties();
this.ej2Instances._setProperties = this.ej2Instances.setProperties;
this.ej2Instances.setProperties = this.setProperties;
this.ej2Instances.clearTemplate = this.clearTemplate;
}
public clearTemplate(templateNames?: string[]): any {
if (!templateNames){
templateNames = Object.keys(this.templateCollection || {});
}
if (templateNames.length && this.templateCollection) {
for (let tempName of templateNames){
let elementCollection: any = this.templateCollection[tempName];
if(elementCollection && elementCollection.length) {
for(let ele of elementCollection) {
let destroy: any = getValue('__vue__.$destroy', ele);
if (destroy) {
ele.__vue__.$destroy();
}
if (ele.innerHTML){
ele.innerHTML = '';
}
}
delete this.templateCollection[tempName];
}
}
}
}
public setProperties(prop: any, muteOnChange: boolean): void {
if(this.isVue3) {
this.models = !this.models ? this.ej2Instances.referModels : this.models;
}
if (this.ej2Instances && this.ej2Instances._setProperties) {
this.ej2Instances._setProperties(prop, muteOnChange);
}
if (prop && this.models && this.models.length) {
Object.keys(prop).map((key: string): void => {
this.models.map((model: string): void => {
if ((key === model) && !(/datasource/i.test(key))) {
if (this.isVue3) {
this.ej2Instances.vueInstance.$emit('update:' + key, prop[key]);
} else {
(this as any).$emit('update:' + key, prop[key]);
(this as any).$emit('modelchanged', prop[key]);
}
}
});
});
}
}
public trigger(eventName: string, eventProp: {[key:string]:Object}, successHandler?: Function): void {
if(!isExecute) {
this.models = !this.models ? this.ej2Instances.referModels : this.models;
}
if ((eventName === 'change' || eventName === 'input') && this.models && (this.models.length !== 0)) {
let key: string[] = this.models.toString().match(/checked|value/) || [];
let propKey: string = key[0];
if (eventProp && key && !isUndefined(eventProp[propKey])) {
if (!isExecute) {
this.ej2Instances.vueInstance.$emit('update:' + propKey, eventProp[propKey]);
this.ej2Instances.vueInstance.$emit('modelchanged', eventProp[propKey]);
} else {
if (eventName === 'change' || ((this as any).$props && !(this as any).$props.islazyUpdate)) {
(this as any).$emit('update:'+ propKey, eventProp[propKey]);
(this as any).$emit('modelchanged', eventProp[propKey]);
}
}
}
} else if ((eventName === 'actionBegin' && eventProp.requestType === 'dateNavigate') && this.models && (this.models.length !== 0)) {
let key: string[] = this.models.toString().match(/currentView|selectedDate/) || [];
let propKey: string = key[0];
if (eventProp && key && !isUndefined(eventProp[propKey])) {
if (!isExecute) {
this.ej2Instances.vueInstance.$emit('update:' + propKey, eventProp[propKey]);
this.ej2Instances.vueInstance.$emit('modelchanged', eventProp[propKey]);
} else {
(this as any).$emit('update:'+ propKey, eventProp[propKey]);
(this as any).$emit('modelchanged', eventProp[propKey]);
}
}
}
if ((this.ej2Instances && this.ej2Instances._trigger)) {
this.ej2Instances._trigger(eventName, eventProp, successHandler);
}
}
public render(createElement: any) {
let h: any = gh || createElement;
let slots: any = null;
if(!isNullOrUndefined((this as any).$slots.default)) {
slots = gh ? (this as any).$slots.default() : (this as any).$slots.default;
}
return h('div', slots);
}
public chartModuleInjection(): void {
return this.ej2Instances.chartModuleInjection();
}
public findCurrentData(totalData: Object, xName: string): Object {
return this.ej2Instances.findCurrentData(totalData, xName);
}
public rangeChanged(updatedStart: number, updatedEnd: number): void {
return this.ej2Instances.rangeChanged(updatedStart, updatedEnd);
}
public renderPeriodSelector(): void {
return this.ej2Instances.renderPeriodSelector();
}
public stockChartDataManagerSuccess(): void {
return this.ej2Instances.stockChartDataManagerSuccess();
}
}
export const StockChartPlugin = {
name: 'ejs-stockchart',
install(Vue: any) {
Vue.component(StockChartPlugin.name, StockChartComponent);
Vue.component(StockChartSeriesPlugin.name, StockChartSeriesDirective);
Vue.component(StockChartSeriesCollectionPlugin.name, StockChartSeriesCollectionDirective);
Vue.component(StockChartTrendlinePlugin.name, StockChartTrendlineDirective);
Vue.component(StockChartTrendlinesPlugin.name, StockChartTrendlinesDirective);
Vue.component(StockChartAxisPlugin.name, StockChartAxisDirective);
Vue.component(StockChartAxesPlugin.name, StockChartAxesDirective);
Vue.component(StockChartRowPlugin.name, StockChartRowDirective);
Vue.component(StockChartRowsPlugin.name, StockChartRowsDirective);
Vue.component(StockChartAnnotationPlugin.name, StockChartAnnotationDirective);
Vue.component(StockChartAnnotationsPlugin.name, StockChartAnnotationsDirective);
Vue.component(StockChartSelectedDataIndexPlugin.name, StockChartSelectedDataIndexDirective);
Vue.component(StockChartSelectedDataIndexesPlugin.name, StockChartSelectedDataIndexesDirective);
Vue.component(StockChartPeriodPlugin.name, StockChartPeriodDirective);
Vue.component(StockChartPeriodsPlugin.name, StockChartPeriodsDirective);
Vue.component(StockEventPlugin.name, StockEventDirective);
Vue.component(StockEventsPlugin.name, StockEventsDirective);
Vue.component(StockChartIndicatorPlugin.name, StockChartIndicatorDirective);
Vue.component(StockChartIndicatorsPlugin.name, StockChartIndicatorsDirective);
}
} | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement, Operator } from "../shared";
/**
* Statement provider for service [elasticloadbalancing](https://docs.aws.amazon.com/service-authorization/latest/reference/list_elasticloadbalancing.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Elasticloadbalancing extends PolicyStatement {
public servicePrefix = 'elasticloadbalancing';
/**
* Statement provider for service [elasticloadbalancing](https://docs.aws.amazon.com/service-authorization/latest/reference/list_elasticloadbalancing.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);
}
/**
* Adds the specified tags to the specified load balancer. Each load balancer can have a maximum of 10 tags
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_AddTags.html
*/
public toAddTags() {
return this.to('AddTags');
}
/**
* Associates one or more security groups with your load balancer in a virtual private cloud (VPC)
*
* Access Level: Write
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_ApplySecurityGroupsToLoadBalancer.html
*/
public toApplySecurityGroupsToLoadBalancer() {
return this.to('ApplySecurityGroupsToLoadBalancer');
}
/**
* Adds one or more subnets to the set of configured subnets for the specified load balancer
*
* Access Level: Write
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_AttachLoadBalancerToSubnets.html
*/
public toAttachLoadBalancerToSubnets() {
return this.to('AttachLoadBalancerToSubnets');
}
/**
* Specifies the health check settings to use when evaluating the health state of your back-end instances
*
* Access Level: Write
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_ConfigureHealthCheck.html
*/
public toConfigureHealthCheck() {
return this.to('ConfigureHealthCheck');
}
/**
* Generates a stickiness policy with sticky session lifetimes that follow that of an application-generated cookie
*
* Access Level: Write
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_CreateAppCookieStickinessPolicy.html
*/
public toCreateAppCookieStickinessPolicy() {
return this.to('CreateAppCookieStickinessPolicy');
}
/**
* Generates a stickiness policy with sticky session lifetimes controlled by the lifetime of the browser (user-agent) or a specified expiration period
*
* Access Level: Write
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_CreateLBCookieStickinessPolicy.html
*/
public toCreateLBCookieStickinessPolicy() {
return this.to('CreateLBCookieStickinessPolicy');
}
/**
* Creates a load balancer
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_CreateLoadBalancer.html
*/
public toCreateLoadBalancer() {
return this.to('CreateLoadBalancer');
}
/**
* Creates one or more listeners for the specified load balancer
*
* Access Level: Write
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_CreateLoadBalancerListeners.html
*/
public toCreateLoadBalancerListeners() {
return this.to('CreateLoadBalancerListeners');
}
/**
* Creates a policy with the specified attributes for the specified load balancer
*
* Access Level: Write
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_CreateLoadBalancerPolicy.html
*/
public toCreateLoadBalancerPolicy() {
return this.to('CreateLoadBalancerPolicy');
}
/**
* Deletes the specified load balancer
*
* Access Level: Write
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_DeleteLoadBalancer.html
*/
public toDeleteLoadBalancer() {
return this.to('DeleteLoadBalancer');
}
/**
* Deletes the specified listeners from the specified load balancer
*
* Access Level: Write
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_DeleteLoadBalancerListeners.html
*/
public toDeleteLoadBalancerListeners() {
return this.to('DeleteLoadBalancerListeners');
}
/**
* Deletes the specified policy from the specified load balancer. This policy must not be enabled for any listeners
*
* Access Level: Write
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_DeleteLoadBalancerPolicy.html
*/
public toDeleteLoadBalancerPolicy() {
return this.to('DeleteLoadBalancerPolicy');
}
/**
* Deregisters the specified instances from the specified load balancer
*
* Access Level: Write
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_DeregisterInstancesFromLoadBalancer.html
*/
public toDeregisterInstancesFromLoadBalancer() {
return this.to('DeregisterInstancesFromLoadBalancer');
}
/**
* Describes the state of the specified instances with respect to the specified load balancer
*
* Access Level: Read
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_DescribeInstanceHealth.html
*/
public toDescribeInstanceHealth() {
return this.to('DescribeInstanceHealth');
}
/**
* Describes the attributes for the specified load balancer
*
* Access Level: Read
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_DescribeLoadBalancerAttributes.html
*/
public toDescribeLoadBalancerAttributes() {
return this.to('DescribeLoadBalancerAttributes');
}
/**
* Describes the specified policies
*
* Access Level: Read
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_DescribeLoadBalancerPolicies.html
*/
public toDescribeLoadBalancerPolicies() {
return this.to('DescribeLoadBalancerPolicies');
}
/**
* Describes the specified load balancer policy types
*
* Access Level: Read
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_DescribeLoadBalancerPolicyTypes.html
*/
public toDescribeLoadBalancerPolicyTypes() {
return this.to('DescribeLoadBalancerPolicyTypes');
}
/**
* Describes the specified the load balancers. If no load balancers are specified, the call describes all of your load balancers
*
* Access Level: List
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_DescribeLoadBalancers.html
*/
public toDescribeLoadBalancers() {
return this.to('DescribeLoadBalancers');
}
/**
* Describes the tags associated with the specified load balancers
*
* Access Level: Read
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_DescribeTags.html
*/
public toDescribeTags() {
return this.to('DescribeTags');
}
/**
* Removes the specified subnets from the set of configured subnets for the load balancer
*
* Access Level: Write
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_DetachLoadBalancerFromSubnets.html
*/
public toDetachLoadBalancerFromSubnets() {
return this.to('DetachLoadBalancerFromSubnets');
}
/**
* Removes the specified Availability Zones from the set of Availability Zones for the specified load balancer
*
* Access Level: Write
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_DisableAvailabilityZonesForLoadBalancer.html
*/
public toDisableAvailabilityZonesForLoadBalancer() {
return this.to('DisableAvailabilityZonesForLoadBalancer');
}
/**
* Adds the specified Availability Zones to the set of Availability Zones for the specified load balancer
*
* Access Level: Write
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_EnableAvailabilityZonesForLoadBalancer.html
*/
public toEnableAvailabilityZonesForLoadBalancer() {
return this.to('EnableAvailabilityZonesForLoadBalancer');
}
/**
* Modifies the attributes of the specified load balancer
*
* Access Level: Write
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_ModifyLoadBalancerAttributes.html
*/
public toModifyLoadBalancerAttributes() {
return this.to('ModifyLoadBalancerAttributes');
}
/**
* Adds the specified instances to the specified load balancer
*
* Access Level: Write
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_RegisterInstancesWithLoadBalancer.html
*/
public toRegisterInstancesWithLoadBalancer() {
return this.to('RegisterInstancesWithLoadBalancer');
}
/**
* Removes one or more tags from the specified load balancer
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_RemoveTags.html
*/
public toRemoveTags() {
return this.to('RemoveTags');
}
/**
* Sets the certificate that terminates the specified listener's SSL connections
*
* Access Level: Write
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_SetLoadBalancerListenerSSLCertificate.html
*/
public toSetLoadBalancerListenerSSLCertificate() {
return this.to('SetLoadBalancerListenerSSLCertificate');
}
/**
* Replaces the set of policies associated with the specified port on which the back-end server is listening with a new set of policies
*
* Access Level: Write
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_SetLoadBalancerPoliciesForBackendServer.html
*/
public toSetLoadBalancerPoliciesForBackendServer() {
return this.to('SetLoadBalancerPoliciesForBackendServer');
}
/**
* Replaces the current set of policies for the specified load balancer port with the specified set of policies
*
* Access Level: Write
*
* https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_SetLoadBalancerPoliciesOfListener.html
*/
public toSetLoadBalancerPoliciesOfListener() {
return this.to('SetLoadBalancerPoliciesOfListener');
}
protected accessLevelList: AccessLevelList = {
"Tagging": [
"AddTags",
"RemoveTags"
],
"Write": [
"ApplySecurityGroupsToLoadBalancer",
"AttachLoadBalancerToSubnets",
"ConfigureHealthCheck",
"CreateAppCookieStickinessPolicy",
"CreateLBCookieStickinessPolicy",
"CreateLoadBalancer",
"CreateLoadBalancerListeners",
"CreateLoadBalancerPolicy",
"DeleteLoadBalancer",
"DeleteLoadBalancerListeners",
"DeleteLoadBalancerPolicy",
"DeregisterInstancesFromLoadBalancer",
"DetachLoadBalancerFromSubnets",
"DisableAvailabilityZonesForLoadBalancer",
"EnableAvailabilityZonesForLoadBalancer",
"ModifyLoadBalancerAttributes",
"RegisterInstancesWithLoadBalancer",
"SetLoadBalancerListenerSSLCertificate",
"SetLoadBalancerPoliciesForBackendServer",
"SetLoadBalancerPoliciesOfListener"
],
"Read": [
"DescribeInstanceHealth",
"DescribeLoadBalancerAttributes",
"DescribeLoadBalancerPolicies",
"DescribeLoadBalancerPolicyTypes",
"DescribeTags"
],
"List": [
"DescribeLoadBalancers"
]
};
/**
* Adds a resource of type loadbalancer to the statement
*
* https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/what-is-load-balancing.html
*
* @param loadBalancerName - Identifier for the loadBalancerName.
* @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()
* - .ifResourceTag()
*/
public onLoadbalancer(loadBalancerName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:elasticloadbalancing:${Region}:${Account}:loadbalancer/${LoadBalancerName}';
arn = arn.replace('${LoadBalancerName}', loadBalancerName);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* The preface string for a tag key and value pair attached to a resource
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifResourceTagExists(value: string | string[], operator?: Operator | string) {
return this.if(`ResourceTag/`, value, operator || 'StringLike');
}
/**
* A tag key and value pair
*
* Applies to resource types:
* - loadbalancer
*
* @param tagKey The tag key to check
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifResourceTag(tagKey: string, value: string | string[], operator?: Operator | string) {
return this.if(`ResourceTag/${ tagKey }`, value, operator || 'StringLike');
}
} | the_stack |
import * as React from "react";
import { ReactNode, RefObject, PureComponent } from "react";
import SceneRenderer, { sceneDefaultProps } from "./SceneRenderer";
import Sidepanel from "./Sidepanel";
import View, { CommonViewClass } from "./View";
import { ViewProps } from "./ViewRenderer";
import Mayer, { PreparedProps as MayerProps } from "./Mayer";
import update from "immutability-helper";
import { SidepanelConfig } from "./Airr";
import ViewsAPIHelper from "./Scene/ViewsAPIHelper";
import SidepanelAPIHelper from "./Scene/SidepanelAPIHelper";
import MayersAPIHelper from "./Scene/MayersAPIHelper";
import { CoreSceneProps } from "./SceneRenderer";
import { getViewProps } from "./CommonViewHelpers";
export interface SceneProps extends CoreSceneProps {
/**
* This propety changes behaviour of views animation when overlay animation is set
*/
stackMode?: boolean;
}
export type SceneState = SceneProps;
export type CommonViewProps = ViewProps | SceneProps;
export interface ViewConfig<T> {
/**
* Refference to class or function that will render View. Use View class refference or class that extends View.
*/
type: React.ComponentClass<T & CommonViewProps, any>;
/**
* Special properties of AirrView class. Go to class declaration for further properties documenation.
*/
props: T & CommonViewProps;
}
export interface ViewsConfigItem<T> extends ViewConfig<T> {
/**
* Props to modify this Scene
*/
sceneProps?: Pick<SceneProps, Exclude<keyof SceneProps, "name">>;
/**
*
* Common view configutaion can have nameGenerator function used to create another view name propperty.
* Gets current state views list as argument.
* Example:
* nameGenerator: views => { return "common-view-*".replace("*", views.length + 1);}
*/
nameGenerator?(views: SceneProps["views"]): string;
}
/**
* View configuraion which can be found by key which is also it's name.
*/
export type ViewsConfig<T = {}> = { [K in keyof T]: ViewsConfigItem<T[K]> };
export interface RefsCOMPViews {
[viewname: string]: RefObject<View<ViewProps>>;
}
export default class Scene<P extends SceneProps = SceneProps, S extends SceneState = SceneState>
extends PureComponent<P, S>
implements CommonViewClass {
static defaultProps = {
...sceneDefaultProps,
stackMode: false
};
/**
* Class member that keep information about views configuraion objects.
* Every key in this object describes another view.
* That configuration later will be used to create new view and add it to state views array.
* Used by ::getFreshViewConfig to deliver new view config.
* This variable is mainly used in crucial components's ::changeView method.
*/
viewsConfig: ViewsConfig;
/**
* Refferency to view's DOM element.
*/
refDOM = React.createRef<HTMLDivElement>();
/**
* Special method for delivering props to View component's.
* Used in render method.
*/
getViewProps = getViewProps.bind(this);
/**
* Instantiated views Component's refferences
*/
refsCOMPViews: RefsCOMPViews = {};
/**
* Instantiated mayers Components refferences
*/
refsCOMPMayers: { [configName: string]: RefObject<Mayer> } = {};
/**
* Instantiated sidepanel Component refference
*/
refCOMPSidepanel = React.createRef<Sidepanel>();
/**
* Refference to DOM element of container's div (first child of most outer element)
*/
refDOMContainer = React.createRef<HTMLDivElement>();
/**
* Refference to DOM element of navbar's div
*/
refDOMNavbar = React.createRef<HTMLDivElement>();
/**
* Helper variable for storing views names that will be filtered
*/
viewsNamesToStayList: string[] = [];
/**
* Describes if views animation is taking place
*/
viewChangeInProgress = false;
/**
* Common view life-cycle method to be overwriten in classes that extends this class
*/
viewAfterActivation(): void {}
viewAfterDeactivation(): void {}
viewBeforeActivation(): void {}
viewBeforeDeactivation(): void {}
state: S = {
...this.state,
name: this.props.name,
active: this.props.active,
className: this.props.className,
title: this.props.title,
navbar: this.props.navbar,
navbarHeight: this.props.navbarHeight,
navbarMenu: this.props.navbarMenu,
navbarClass: this.props.navbarClass,
backButton: this.props.backButton,
backButtonOnFirstView: this.props.backButtonOnFirstView,
activeViewName: this.props.activeViewName,
animation: this.props.animation,
views: this.props.views,
sidepanel: this.props.sidepanel,
sidepanelVisibilityCallback: this.props.sidepanelVisibilityCallback,
GUIDisabled: this.props.GUIDisabled,
GUIDisableCover: this.props.GUIDisableCover,
mayers: this.props.mayers,
children: this.props.children,
animationTime: this.props.animationTime,
handleBackBehaviourOnFirstView: this.props.handleBackBehaviourOnFirstView,
handleBackButton: this.props.handleBackButton,
stackMode: this.props.stackMode
};
componentDidMount(): Promise<void> {
return new Promise(
(resolve): void => {
SidepanelAPIHelper.initWindowResizeListener(this);
/**
* Call first active view life cycle method - viewAfterActivation
*/
ViewsAPIHelper.invokeActivationEffectOnActiveView(this);
if (this.state.sidepanel) {
SidepanelAPIHelper.updateSidepanelSizeProps(this).then(resolve);
} else {
resolve();
}
}
);
}
render(): ReactNode {
const { views, sidepanel, className, ...stateRest } = this.state;
return (
<SceneRenderer
{...{
...stateRest,
views: views,
sidepanel: sidepanel,
refDOMContainer: this.refDOMContainer,
refDOMNavbar: this.refDOMNavbar,
refsCOMPViews: this.refsCOMPViews,
refCOMPSidepanel: this.refCOMPSidepanel,
sidepanelVisibilityCallback: this.__sidepanelVisibilityCallback
}}
{...this.getViewProps()}
{...{ className }}
/>
);
}
/**
* Special lifecycle method to be overwritten in descendant classes.
* Called, as name sugest, when views animation finish.
*/
viewsAnimationEnd(oldViewName: string, newViewName: string): void {}
/**
* Creates new view config base on configuration in `viewsConfig` variable.
* When `viewNameGenerator` in present base configuration it will use to create new view name property.
* This feature is handy when you want to easly create next views based upon generic view configuration.
*
* @param {string|ViewConfig} view Name of the configuraion key in `this.viewsConfig` object or raw ViewConfig object
* @param {object} props Additional prop to be merged with base config
*/
getFreshViewConfig<T>(
view: string | ViewsConfigItem<T>,
props: CommonViewProps | {} = {}
): ViewsConfigItem<T> {
if (typeof view === "string" && view in this.viewsConfig) {
const config = Object.assign({}, this.viewsConfig[view]);
const viewGenerator = this.viewsConfig[view].nameGenerator;
return update(this.viewsConfig[view], {
props: {
$set: {
...Object.assign({}, config.props),
...Object.assign({}, props),
name:
viewGenerator && typeof viewGenerator === "function"
? viewGenerator(this.state.views)
: view
}
}
});
} else if (typeof view === "object" && this.isValidViewConfig<T>(view)) {
return Object.assign({}, view, {
props: { ...view.props, ...props }
});
} else {
throw new Error(
`Passed view is not present in viewsConfig or is invalid raw ViewConfig object.`
);
}
}
/**
* Removes views that are not contained by name in array
* @param {array} viewsNameList List of views names that will stay in state
* @returns {Promise} Will be resolved on succesful state update
*/
filterViews(viewsNameList: string[] = []): Promise<void> {
return new Promise(
(resolve): void => {
this.setState(
{
views: this.state.views.filter(
(view): boolean => viewsNameList.indexOf(view.props.name) !== -1
)
},
resolve
);
}
);
}
/**
* Pops out with animation currently active view from view's array
* @param {object} viewProps props to modify the view just before popping
* @param {object} sceneProps props to modify the scene while popping
* @returns {Promise} Will be resolved on succesful state update or rejected when no view to pop
*/
popView = async (
viewProps: ViewProps | {} = {},
sceneProps: SceneProps | {} = {}
): Promise<string | void> => {
if (this.state.views.length > 1) {
const viewName = this.state.views[this.state.views.length - 2].props.name;
await this.changeView(viewName, viewProps, sceneProps);
const newviewdefinition = update(this.state.views, {
$splice: [[this.state.views.length - 1, 1]]
});
delete this.refsCOMPViews[this.state.views[this.state.views.length - 1].props.name];
return new Promise(
(resolve): void =>
this.setState({ views: newviewdefinition }, (): void => resolve(viewName))
);
} else {
console.warn("[] No view to pop.");
return Promise.resolve();
}
};
/**
* Crucial method of the scene component for manipalutaing views and scene properties and performing animations.
* Can change active view with animation or just update view and scene properties.
*
* Change view by:
* - string name kept in state views array which will lead to view change (with animation) or just update if currently active
* - string name kept in `this.viewsConfig` which will lead to view push (with animation)
* - new view config wich will lead to view change
*
* @param {string|object} view View name to change or view config to be added
* @param {object} viewProps Extra props to be added to changing view
* @param {object} sceneProps Extra props to manipulate this scene while changing view
* @returns {Promise} Resolved on state succesful change and animation end. Or reject on failure.
*/
async changeView(
view: string | ViewConfig<CommonViewProps>,
viewProps: CommonViewProps | {} = {},
sceneProps: SceneProps | {} = {}
): Promise<string | void> {
const viewName = await ViewsAPIHelper.changeView(this, view, viewProps, sceneProps);
return ViewsAPIHelper.performViewsAnimation(this, viewName);
}
/**
* Removes view from views array
* @param {string} name
*/
destroyView(name: string): Promise<void> {
return new Promise(
(resolve, reject): void => {
const index = this.state.views.findIndex(
(view): boolean => view.props.name === name
);
if (index !== -1) {
this.setState(
{
views: update(this.state.views, {
$splice: [[index, 1]]
})
},
resolve
);
} else {
reject(`View with name: ${name} was not found in this scene.`);
}
}
);
}
/**
* Utility function to handle back button clicks.
* Can be overwritten by class extending this scene.
* By default it pops currently active view.
* To use it, assign it's value to state like this:
* this.state.handleBackButton = this.handleBackButton
*
* @returns {Promise} Resolved on state succesful change or reject on failure.
*/
handleBackButton = (
viewProps: ViewProps | {} = {},
sceneProps: SceneProps | {} = {}
): Promise<string | void> => {
if (this.state.views.length > 1) {
return this.popView(viewProps, sceneProps);
}
return Promise.resolve();
};
/**
* Special function for enabling sidepanel config after mounting of scene.
* Will ensure proper sidepanel size (width,height) after incjeting it into DOM.
* @returns {Promise} Resolved on state succesful change.
*/
setSidepanelConfig = (config: SidepanelConfig): Promise<void> => {
return new Promise(
(resolve): void =>
this.setState(
{
sidepanel: config
},
(): void => {
SidepanelAPIHelper.updateSidepanelSizeProps(this).then(resolve);
}
)
);
};
/**
* Disables scene's sidepanel by setting it prop enabled = false.
* @returns {Promise} Resolved on state succesful change or reject on failure.
*/
disableSidepanel = (): Promise<void> => {
return SidepanelAPIHelper.toggleSidepanel(this, false);
};
/**
* Enables scene's sidepanel by setting it prop enabled = true.
* @returns {Promise} Resolved on state succesful change or reject on failure.
*/
enableSidepanel = (): Promise<void> => {
return SidepanelAPIHelper.toggleSidepanel(this, true);
};
/**
* Shows sidepanel
* @returns {Promise}
*/
openSidepanel = (): Promise<boolean | void> => {
if (this.state.sidepanel && this.refCOMPSidepanel.current) {
this.setState({
sidepanel: update(this.state.sidepanel, {
props: { enabled: { $set: true } }
})
});
return this.refCOMPSidepanel.current.show();
}
return Promise.resolve();
};
/**
* Hides sidepanel
* @returns {Promise}
*/
hideSidepanel = (): Promise<boolean | void> => {
if (this.state.sidepanel && this.refCOMPSidepanel.current) {
return this.refCOMPSidepanel.current.hide();
}
return Promise.resolve();
};
/**
* Add new mayer to this.state.mayers configurations array.
* This will immediatelly open new mayer due to `componentDidMount` lifecycle implementation.
*
* @param {object} config Mayer config object.
* @returns {Promise}
*/
openMayer(config: MayerProps): Promise<void> {
if (this.state.mayers.findIndex((item): boolean => item.name === config.name) !== -1) {
console.warn("[] Scene allready has Mayer with this name: " + config.name);
return Promise.reject();
}
//add special functionality,props
const preparedConfig = MayersAPIHelper.prepareMayerConfig(this, config);
return MayersAPIHelper.addMayer(this, preparedConfig);
}
/**
* Close mayer by name
*
* @param {string} name Unique mayer name
* @returns {Promise}
*/
closeMayer(name: string): Promise<void> {
//TODO hasMountedMayer might be deprecated in favour to simple check in this.state.mayers
if (MayersAPIHelper.hasMountedMayer(this, name)) {
return new Promise(
(resolve): void => {
this.refsCOMPMayers[name].current.animateOut(
(): void => {
//renew check because after animation things might have changed
if (MayersAPIHelper.hasMountedMayer(this, name)) {
MayersAPIHelper.removeMayer(this, name).then(resolve);
}
}
);
}
);
}
return Promise.resolve();
}
/**
* Action dispatcher method. Will return a function ready to fire view change.
* @param {string} name
* @param {array} viewsNamesToStayList
* @returns {function} Function that will resolve view change on invoke.
*/
goToView = (name: string, viewsNamesToStayList: string[] = []): Function => {
return (
params: ViewProps | {} = {},
sceneProps: SceneProps | {} = {}
): Promise<string | void> => {
this.viewsNamesToStayList = viewsNamesToStayList;
return this.changeView(name, params, sceneProps);
};
};
/**
* Check wheter object is valid view config and can be added to view's array
* @param {object} object
* @returns {boolean}
*/
isValidViewConfig<T>(object: ViewsConfigItem<T>): boolean {
return (
typeof object === "object" &&
"type" in object &&
typeof object.props === "object" &&
"name" in object.props
);
}
/**
* Check if view's name is described by some config in `this.viewsConfig` object
* @param {string} name
* @returns {boolean}
*/
hasViewInConfig = (name: string): boolean => name in this.viewsConfig;
/**
* Check if view recognized by name argument is present in state
* @param {string} name
* @returns {boolean}
*/
hasViewInState = (name: string): boolean =>
this.state.views.findIndex((view): boolean => view.props.name === name) !== -1
? true
: false;
/**
* Get view index in views array
* @param {string} viewName
* @returns {number}
*/
getViewIndex = (viewName: string): number =>
this.state.views.findIndex((view): boolean => view.props.name === viewName);
/**
* Utility function for updating sidepanel isShown prop
*/
__sidepanelVisibilityCallback = (isShown: boolean): void => {
return SidepanelAPIHelper.sidepanelVisibilityCallback(this, isShown);
};
} | the_stack |
import * as React from "react";
import { IShowAdaptiveCardProps } from "./IShowAdaptiveCardProps";
import * as adaptiveCards from "adaptivecards";
import { Stack } from "@fluentui/react/lib/Stack";
import * as markdownit from "markdown-it";
import { FontType, Spacing, TextSize, TextWeight } from "adaptivecards";
import { IUser } from "../../models/IUser";
import { EGlobalStateTypes, GlobalStateContext } from "../../globalState";
import { DefaultButton, PrimaryButton } from "@fluentui/react/lib/Button";
import { useTeams } from "./../../hooks";
import { ITermLabel } from "../../models/ITermLabel";
import {
MessageBar,
MessageBarType,
Spinner,
SpinnerSize,
Text,
} from "@fluentui/react";
import { IMessageInfo } from "../../models/IMessageInfo";
import strings from "SendToTeamsCommandSetStrings";
export const ShowAdaptiveCard: React.FunctionComponent<IShowAdaptiveCardProps> = (
props: React.PropsWithChildren<IShowAdaptiveCardProps>
) => {
const containerRef = React.useRef<HTMLDivElement>(undefined);
const cardRef = React.useRef<any>();
const { state, dispatch } = React.useContext(GlobalStateContext);
const { sendAdativeCardToTeams } = useTeams(state.serviceScope);
const { appContext } = state;
const {
title,
subtitle,
text,
itemImage,
fields,
onSendCard,
onCancelPanel,
} = props;
const { messageInfo } = state;
React.useEffect(() => {
while (containerRef.current.firstChild) {
containerRef.current.removeChild(containerRef.current.lastChild);
}
if (!title && !subtitle && !text && !itemImage && !fields && !fields.length)
return;
const adaptiveCard = new adaptiveCards.AdaptiveCard();
adaptiveCard.version = new adaptiveCards.Version(1, 2);
// Handle parsing markdown from HTML
adaptiveCards.AdaptiveCard.onProcessMarkdown = _onProcessMarkdownHandler;
const cardTitle: adaptiveCards.TextBlock = _addTitle(title);
const cardSubtitle: adaptiveCards.TextBlock = _addSubTitle(subtitle);
const image: adaptiveCards.Image = _addImage(itemImage);
const cardText: adaptiveCards.TextBlock = _addTextMessage(text);
adaptiveCard.addItem(cardTitle);
adaptiveCard.addItem(cardSubtitle);
adaptiveCard.addItem(image);
adaptiveCard.addItem(cardText);
let _cardListFieldLabel: any[] = [];
let _cardListField: any[] = [];
if (fields && fields.length) {
for (let index = 0; index < fields.length; index++) {
const column = fields[index];
let fieldValue = column.fieldValue;
const fieldType = column.fieldType;
if (
fieldType === "URL" &&
(fieldValue as string).match(/\.(jpg|jpeg|png|gif)$/)
)
continue;
_cardListFieldLabel[index] = _addFieldLabel(column);
_cardListField[index] = _addListField(
fieldValue,
fieldType,
appContext.pageContext.site.absoluteUrl
);
adaptiveCard.addItem(_cardListFieldLabel[index]);
adaptiveCard.addItem(_cardListField[index]);
}
}
// Create JSON Adaptive Card
const _card = adaptiveCard.toJSON();
// Parse the card payload
adaptiveCard.parse(_card);
// Render the card to an HTML element:
cardRef.current = _card;
const renderedCard = adaptiveCard.render();
// Empty the div so we can replace it
containerRef.current.appendChild(renderedCard);
}, [props]);
const onSendMessage = React.useCallback(
async () => {
const { selectedTeam, selectedTeamChannel } = state;
let sendMessageInfo: IMessageInfo = {
isShow: false,
messageProps:{messageBarType: MessageBarType.error},
message: "",
};
try {
dispatch({
type: EGlobalStateTypes.SET_IS_SENDING_MESSAGE,
payload: true,
});
await sendAdativeCardToTeams(cardRef.current,selectedTeam[0].key as string,selectedTeamChannel[0].key as string);
onSendCard();
} catch (error) {
console.log(error);
dispatch({
type: EGlobalStateTypes.SET_IS_SENDING_MESSAGE,
payload: false,
});
sendMessageInfo = {
isShow: true,
messageProps:{messageBarType: MessageBarType.error},
message: strings.ErrorMessageOnSendingMessage,
};
dispatch({
type: EGlobalStateTypes.SET_MESSAGE,
payload: sendMessageInfo,
});
}
},
[
state.selectedTeam,
state.selectedTeamChannel,
cardRef.current,
sendAdativeCardToTeams,
]
);
const onRenderFooterContent = React.useCallback(() => {
let enableSend: boolean = false;
const {
selectedTeam,
selectedTeamChannel,
selectedTitle,
isSendingMessage,
} = state;
if (
selectedTeam &&
selectedTeamChannel &&
selectedTitle &&
!isSendingMessage
) {
enableSend = true;
}
return (
<>
<Stack
tokens={{ childrenGap: 10 }}
horizontal
horizontalAlign="end"
verticalAlign="center"
>
<PrimaryButton disabled={!enableSend} onClick={onSendMessage}>
{isSendingMessage ? (
<Stack horizontal horizontalAlign="center">
<Spinner size={SpinnerSize.small} />
</Stack>
) : (
strings.SendButtonLabel
)}
</PrimaryButton>
<DefaultButton
onClick={() => {
onCancelPanel();
}}
>
{strings.CancelButtonLabel}
</DefaultButton>
</Stack>
</>
);
}, [
state.selectedTeam,
state.selectedTeamChannel,
state.selectedTitle,
state.isSendingMessage,
onSendMessage,
onCancelPanel,
]);
return (
<>
<Stack
verticalAlign="center"
tokens={{ childrenGap: 30 }}
styles={{ root: { width: "100%" } }}
>
<div ref={containerRef} style={{ width: "100%" }} />
{onRenderFooterContent()}
{messageInfo.isShow && (
<MessageBar
{...messageInfo.messageProps}
messageBarType={MessageBarType.error}>
<Text>{state.messageInfo.message}</Text>
</MessageBar>
)}
</Stack>
</>
);
};
// Functions
const _addListField = (
fieldValue: any,
fieldType: string,
siteUrl: string
): adaptiveCards.TextBlock | adaptiveCards.ColumnSet => {
let _fieldValue: adaptiveCards.TextBlock = new adaptiveCards.TextBlock();
_fieldValue.spacing = Spacing.None;
_fieldValue.maxLines = 20;
_fieldValue.wrap = true;
_fieldValue.fontType = FontType.Default;
_fieldValue.size = TextSize.Default;
switch (fieldType) {
case "DateTime":
_fieldValue.text = fieldValue;
return _fieldValue;
case "URL":
if (!(fieldValue as string).match(/\.(jpg|jpeg|png|gif)$/)) {
_fieldValue.text = `[${fieldValue}](${fieldValue})`;
return _fieldValue;
}
break;
case "TaxonomyFieldType":
_fieldValue.text = fieldValue.Label;
return _fieldValue;
case "TaxonomyFieldTypeMulti":
const _fieldValueMetadataMulti: ITermLabel[] = fieldValue as ITermLabel[];
const terms: string[] = [];
for (const term of _fieldValueMetadataMulti) {
terms.push(term.Label);
}
_fieldValue.text = terms.join(",");
return _fieldValue;
case "MultiChoice":
const _fieldValueMultiChoice: string[] = fieldValue as any;
fieldValue = _fieldValueMultiChoice.join(",");
_fieldValue.text = fieldValue;
return _fieldValue;
case "User":
case "UserMulti":
return _addUserField(fieldValue, siteUrl);
default:
_fieldValue.text = fieldValue;
break;
}
return _fieldValue;
};
const _addUserField = (
fieldValue: IUser[],
siteUrl: string
): adaptiveCards.ColumnSet => {
const _userField: IUser[] = fieldValue;
let columnset = new adaptiveCards.ColumnSet();
columnset.spacing = Spacing.None;
let firstColumn = new adaptiveCards.Column();
(firstColumn.width as any) = "45px";
let secondColumn = new adaptiveCards.Column();
for (const user of _userField) {
let proFileImage = new adaptiveCards.Image();
let columnTextName = new adaptiveCards.TextBlock();
let columnTextEmail = new adaptiveCards.TextBlock();
proFileImage.size = adaptiveCards.Size.Small;
proFileImage.pixelWidth = 40;
proFileImage.spacing = Spacing.Small;
proFileImage.style = adaptiveCards.ImageStyle.Person;
proFileImage.url = `${siteUrl}/_layouts/15/userphoto.aspx?size=S&accountname=${user.email}`;
// user.picture !== "" ? user.picture : DEFAULT_PERSONA_IMAGE;
columnTextName.text = user.value;
columnTextName.maxLines = 2;
columnTextName.wrap = true;
columnTextName.size = TextSize.Default;
columnTextName.spacing = Spacing.Small;
//
columnTextEmail.text = `[${user.email}](mailto:${user.email})`;
columnTextEmail.maxLines = 2;
columnTextEmail.wrap = true;
columnTextEmail.size = TextSize.Default;
columnTextEmail.spacing = Spacing.None;
firstColumn.addItem(proFileImage);
secondColumn.addItem(columnTextName);
secondColumn.addItem(columnTextEmail);
}
columnset.addColumn(firstColumn);
columnset.addColumn(secondColumn);
return columnset;
};
const _addFieldLabel = (field: any): adaptiveCards.TextBlock => {
let _fieldLabel = new adaptiveCards.TextBlock();
_fieldLabel.maxLines = 1;
_fieldLabel.wrap = false;
_fieldLabel.text = field.fieldDIsplayName;
_fieldLabel.fontType = FontType.Default;
_fieldLabel.size = TextSize.Default;
_fieldLabel.weight = TextWeight.Bolder;
return _fieldLabel;
};
const _addImage = (itemImage: string): adaptiveCards.Image => {
let image = new adaptiveCards.Image();
image.url = itemImage;
return image;
};
const _addTitle = (title: string): adaptiveCards.TextBlock => {
let cardTitle = new adaptiveCards.TextBlock();
cardTitle.text = title;
cardTitle.maxLines = 2;
cardTitle.wrap = true;
cardTitle.size = TextSize.Large;
return cardTitle;
};
const _addSubTitle = (subTitle: string): adaptiveCards.TextBlock => {
let cardSubtitle = new adaptiveCards.TextBlock();
cardSubtitle.maxLines = 2;
cardSubtitle.wrap = true;
cardSubtitle.isSubtle = true;
cardSubtitle.spacing = Spacing.None;
cardSubtitle.text = subTitle;
return cardSubtitle;
};
const _onProcessMarkdownHandler = (md: string, result: any) => {
// Don't stop parsing if there is invalid Markdown -- there's a lot of that in sample Adaptive Cards templates
try {
result.outputHtml = new markdownit().render(md);
result.didProcess = true;
} catch (error) {
console.error("Error parsing Markdown", error);
result.didProcess = false;
}
};
const _addTextMessage = (text: string): adaptiveCards.TextBlock => {
let cardTextMessage = new adaptiveCards.TextBlock();
// Message
cardTextMessage.text = text;
cardTextMessage.maxLines = 10;
cardTextMessage.wrap = true;
return cardTextMessage;
}; | the_stack |
import BigNumber from 'bignumber.js';
import _ from 'lodash';
import { fastForward, mineAvgBlock } from './helpers/EVM';
import initializePerpetual from './helpers/initializePerpetual';
import { expectBalances, mintAndDeposit } from './helpers/balances';
import { ITestContext, perpetualDescribe } from './helpers/perpetualDescribe';
import { buy, sell } from './helpers/trade';
import { expect, expectBN, expectBaseValueEqual, expectThrow, expectAddressesEqual } from './helpers/Expect';
import { address } from '../src';
import { FEES, INTEGERS, PRICES } from '../src/lib/Constants';
import {
BaseValue,
BigNumberable,
Order,
Price,
SigningMethod,
TxResult,
} from '../src/lib/types';
const initialPrice = new Price(100);
const longBorderlinePrice = new Price(50);
const longUnderwaterPrice = new Price('49.999999');
const shortBorderlinePrice = new Price(150);
const shortUnderwaterPrice = new Price('150.000001');
const positionSize = new BigNumber(10);
let admin: address;
let long: address;
let short: address;
let rando: address;
let deleveragingOperator: address;
let deleveragingTimelockSeconds: number;
async function init(ctx: ITestContext): Promise<void> {
await initializePerpetual(ctx);
admin = ctx.accounts[0];
long = ctx.accounts[1];
short = ctx.accounts[2];
rando = ctx.accounts[3];
deleveragingOperator = ctx.accounts[4];
deleveragingTimelockSeconds = await ctx.perpetual.deleveraging.getDeleveragingTimelockSeconds();
// Set up initial balances:
// +---------+--------+----------+-------------------+
// | account | margin | position | collateralization |
// |---------+--------+----------+-------------------|
// | long | -500 | 10 | 200% |
// | short | 1500 | -10 | 150% |
// +---------+--------+----------+-------------------+
await Promise.all([
ctx.perpetual.testing.oracle.setPrice(initialPrice),
ctx.perpetual.deleveraging.setDeleveragingOperator(deleveragingOperator, { from: admin }),
mintAndDeposit(ctx, long, new BigNumber(500)),
mintAndDeposit(ctx, short, new BigNumber(500)),
]);
await buy(ctx, long, short, positionSize, new BigNumber(1000));
}
perpetualDescribe('P1Deleveraging', init, (ctx: ITestContext) => {
describe('setDeleveragingOperator()', () => {
it('sets the privileged deleveraging operator', async () => {
// Make the long account deleverageable.
await ctx.perpetual.testing.oracle.setPrice(longUnderwaterPrice);
// Check that the operator-to-be can't deleverage without marking.
await expectThrow(
deleverage(long, short, positionSize, { sender: rando }),
'Cannot deleverage since account is not marked',
);
// Set the operator.
const txResult = await ctx.perpetual.deleveraging.setDeleveragingOperator(
rando,
{ from: admin },
);
// Check logs.
const logs = ctx.perpetual.logs.parseLogs(txResult);
expect(logs.length).to.equal(1);
const log = logs[0];
expect(log.name).to.equal('LogDeleveragingOperatorSet');
expectAddressesEqual(log.args.deleveragingOperator, rando);
// Check getter.
const operatorAfter = await ctx.perpetual.deleveraging.getDeleveragingOperator();
expectAddressesEqual(operatorAfter, rando);
// Check that the old operator can't deleverage without marking.
await expectThrow(
deleverage(long, short, positionSize, { sender: deleveragingOperator }),
'Cannot deleverage since account is not marked',
);
// Check that the new operator can deleverage without marking.
await deleverage(long, short, positionSize, { sender: rando });
});
it('fails if the caller is not the admin', async () => {
// Call from a random address.
await expectThrow(
ctx.perpetual.deleveraging.setDeleveragingOperator(deleveragingOperator, { from: rando }),
'Ownable: caller is not the owner',
);
// Call from the operator address.
await expectThrow(
ctx.perpetual.deleveraging.setDeleveragingOperator(
deleveragingOperator,
{ from: deleveragingOperator },
),
'Ownable: caller is not the owner',
);
});
});
describe('trade()', () => {
it('Fails if the caller is not the perpetual contract', async () => {
await expectThrow(
ctx.perpetual.deleveraging.trade(
short,
long,
shortUnderwaterPrice,
positionSize,
false,
),
'msg.sender must be PerpetualV1',
);
});
});
describe('trade(), via PerpetualV1, as the deleveraging admin', () => {
it('Succeeds partially deleveraging a long position', async () => {
await ctx.perpetual.testing.oracle.setPrice(longUnderwaterPrice);
const deleverageAmount = positionSize.div(2);
const txResult = await deleverage(long, short, deleverageAmount);
await expectBalances(
ctx,
txResult,
[long, short],
[new BigNumber(-250), new BigNumber(1250)],
[new BigNumber(5), new BigNumber(-5)],
);
// Check logs.
const logs = ctx.perpetual.logs.parseLogs(txResult);
const filteredLogs = _.filter(logs, { name: 'LogDeleveraged' });
expect(filteredLogs.length).to.equal(1);
const deleveragedLog = filteredLogs[0];
expect(deleveragedLog.args.maker).to.equal(long);
expect(deleveragedLog.args.taker).to.equal(short);
expectBN(deleveragedLog.args.amount).to.equal(deleverageAmount);
expect(deleveragedLog.args.isBuy).to.equal(true);
expectBaseValueEqual(deleveragedLog.args.oraclePrice, longUnderwaterPrice);
});
it('Succeeds partially deleveraging a short position', async () => {
await ctx.perpetual.testing.oracle.setPrice(shortUnderwaterPrice);
const deleverageAmount = positionSize.div(2);
const txResult = await deleverage(short, long, deleverageAmount);
await expectBalances(
ctx,
txResult,
[long, short],
[new BigNumber(250), new BigNumber(750)],
[new BigNumber(5), new BigNumber(-5)],
);
// Check logs.
const logs = ctx.perpetual.logs.parseLogs(txResult);
const filteredLogs = _.filter(logs, { name: 'LogDeleveraged' });
expect(filteredLogs.length).to.equal(1);
const deleveragedLog = filteredLogs[0];
expect(deleveragedLog.args.maker).to.equal(short);
expect(deleveragedLog.args.taker).to.equal(long);
expectBN(deleveragedLog.args.amount).to.equal(deleverageAmount);
expect(deleveragedLog.args.isBuy).to.equal(false);
expectBaseValueEqual(deleveragedLog.args.oraclePrice, shortUnderwaterPrice);
});
it('Succeeds fully deleveraging a long position', async () => {
await ctx.perpetual.testing.oracle.setPrice(longUnderwaterPrice);
const txResult = await deleverage(long, short, positionSize);
await expectBalances(
ctx,
txResult,
[long, short],
[new BigNumber(0), new BigNumber(1000)],
[new BigNumber(0), new BigNumber(0)],
);
});
it('Succeeds fully deleveraging a short position', async () => {
await ctx.perpetual.testing.oracle.setPrice(shortUnderwaterPrice);
const txResult = await deleverage(short, long, positionSize);
await expectBalances(
ctx,
txResult,
[long, short],
[new BigNumber(1000), new BigNumber(0)],
[new BigNumber(0), new BigNumber(0)],
);
});
it('Succeeds with all-or-nothing', async () => {
await ctx.perpetual.testing.oracle.setPrice(longUnderwaterPrice);
const txResult = await deleverage(long, short, positionSize, { allOrNothing: true });
await expectBalances(
ctx,
txResult,
[long, short],
[new BigNumber(0), new BigNumber(1000)],
[new BigNumber(0), new BigNumber(0)],
);
});
it('Succeeds when the amount is zero and the maker is long', async () => {
await ctx.perpetual.testing.oracle.setPrice(longUnderwaterPrice);
const txResult = await deleverage(long, short, 0);
await expectBalances(
ctx,
txResult,
[long, short],
[new BigNumber(-500), new BigNumber(1500)],
[new BigNumber(10), new BigNumber(-10)],
);
});
it('Succeeds when the amount is zero and the maker is short', async () => {
await ctx.perpetual.testing.oracle.setPrice(shortUnderwaterPrice);
const txResult = await deleverage(short, long, 0);
await expectBalances(
ctx,
txResult,
[long, short],
[new BigNumber(-500), new BigNumber(1500)],
[new BigNumber(10), new BigNumber(-10)],
);
});
it('Succeeds even if amount is greater than the maker position', async() => {
// Cover some of the short position.
await mintAndDeposit(ctx, rando, new BigNumber(10000));
await buy(ctx, short, rando, new BigNumber(1), new BigNumber(150));
// New balances:
// | account | margin | position |
// |---------+--------+----------|
// | long | -500 | 10 |
// | short | 1350 | -9 |
// Deleverage the short position.
await ctx.perpetual.testing.oracle.setPrice(new Price(150.2));
const txResult = await deleverage(short, long, positionSize);
// The actual amount executed should be bounded by the maker position.
await expectBalances(
ctx,
txResult,
[long, short, rando],
[new BigNumber(850), new BigNumber(0), new BigNumber(10150)],
[new BigNumber(1), new BigNumber(0), new BigNumber(-1)],
);
});
it('Succeeds even if amount is greater than the taker position', async() => {
// Sell off some of the long position.
await mintAndDeposit(ctx, rando, new BigNumber(10000));
await sell(ctx, long, rando, new BigNumber(1), new BigNumber(150));
// New balances:
// | account | margin | position |
// |---------+--------+----------|
// | long | -350 | 9 |
// | short | 1500 | -10 |
// Deleverage the short position.
await ctx.perpetual.testing.oracle.setPrice(shortUnderwaterPrice);
const txResult = await deleverage(short, long, positionSize);
// The actual amount executed should be bounded by the taker position.
await expectBalances(
ctx,
txResult,
[long, short, rando],
[new BigNumber(1000), new BigNumber(150), new BigNumber(9850)],
[new BigNumber(0), new BigNumber(-1), new BigNumber(1)],
);
});
it('Cannot deleverage a long position that is not underwater', async () => {
await ctx.perpetual.testing.oracle.setPrice(longBorderlinePrice);
await expectThrow(
deleverage(long, short, positionSize),
'Cannot deleverage since maker is not underwater',
);
});
it('Cannot deleverage a short position that is not underwater', async () => {
await ctx.perpetual.testing.oracle.setPrice(shortBorderlinePrice);
await expectThrow(
deleverage(short, long, positionSize),
'Cannot deleverage since maker is not underwater',
);
});
it('Cannot deleverage a long position if isBuy is false', async () => {
await ctx.perpetual.testing.oracle.setPrice(longUnderwaterPrice);
await expectThrow(
deleverage(long, short, positionSize, { isBuy: false }),
'deleveraging must not increase maker\'s position size',
);
});
it('Cannot deleverage a short position if isBuy is true', async () => {
await ctx.perpetual.testing.oracle.setPrice(shortUnderwaterPrice);
await expectThrow(
deleverage(short, long, positionSize, { isBuy: true }),
'deleveraging must not increase maker\'s position size',
);
});
it('With all-or-nothing, fails if amount is greater than the maker position', async () => {
// Attempt to deleverage the short position.
await ctx.perpetual.testing.oracle.setPrice(shortUnderwaterPrice);
await expectThrow(
deleverage(short, long, positionSize.plus(1), { allOrNothing: true }),
'allOrNothing is set and maker position is less than amount',
);
});
it('With all-or-nothing, fails if amount is greater than the taker position', async () => {
// Sell off some of the long position.
await mintAndDeposit(ctx, rando, new BigNumber(10000));
await sell(ctx, long, rando, new BigNumber(1), new BigNumber(100));
// Attempt to deleverage the short position.
await ctx.perpetual.testing.oracle.setPrice(shortUnderwaterPrice);
await expectThrow(
deleverage(short, long, positionSize, { allOrNothing: true }),
'allOrNothing is set and taker position is less than amount',
);
});
it('Cannot deleverage a long against a long', async () => {
// Turn the short into a long.
await mintAndDeposit(ctx, rando, new BigNumber(10000));
await buy(ctx, short, rando, new BigNumber(20), new BigNumber(500));
await ctx.perpetual.testing.oracle.setPrice(longUnderwaterPrice);
await expectThrow(
deleverage(long, short, positionSize),
'Taker position has wrong sign to deleverage this maker',
);
});
it('Cannot deleverage a short against a short', async () => {
// Turn the long into a short.
await mintAndDeposit(ctx, rando, new BigNumber(10000));
await sell(ctx, long, rando, new BigNumber(20), new BigNumber(2500));
await ctx.perpetual.testing.oracle.setPrice(shortUnderwaterPrice);
await expectThrow(
deleverage(short, long, positionSize),
'Taker position has wrong sign to deleverage this maker',
);
});
it('Cannot deleverage after an order has executed in the same tx', async () => {
await ctx.perpetual.testing.oracle.setPrice(longUnderwaterPrice);
const defaultOrder: Order = {
isBuy: true,
isDecreaseOnly: false,
amount: new BigNumber(1),
limitPrice: initialPrice,
triggerPrice: PRICES.NONE,
limitFee: FEES.ZERO,
maker: long,
taker: short,
expiration: INTEGERS.ZERO,
salt: new BigNumber(444),
};
const defaultSignedOrder = await ctx.perpetual.orders.getSignedOrder(
defaultOrder,
SigningMethod.Hash,
);
await expectThrow(
ctx.perpetual.trade.initiate()
.fillSignedOrder(
defaultSignedOrder,
defaultSignedOrder.amount,
defaultSignedOrder.limitPrice,
defaultSignedOrder.limitFee,
)
.deleverage(long, short, positionSize, true, false)
.commit({ from: short }),
'cannot deleverage after other trade operations, in the same tx',
);
});
it('Cannot deleverage twice in the same tx', async () => {
await ctx.perpetual.testing.oracle.setPrice(longUnderwaterPrice);
await expectThrow(
ctx.perpetual.trade.initiate()
.deleverage(long, short, 1, true, false)
.deleverage(long, short, positionSize.minus(1), true, false)
.commit({ from: deleveragingOperator }),
'cannot deleverage after other trade operations, in the same tx',
);
});
describe('when an account has no positive value', async () => {
beforeEach(async () => {
// Short begins with -10 position, 1500 margin.
// Set a negative funding rate and accumulate 2000 margin worth of interest.
await ctx.perpetual.testing.funder.setFunding(new BaseValue(-2));
await mineAvgBlock();
await ctx.perpetual.margin.deposit(short, 0);
const balance = await ctx.perpetual.getters.getAccountBalance(short);
expectBN(balance.position).to.equal(-10);
expectBN(balance.margin).to.equal(-500);
});
it('Cannot directly deleverage the account', async () => {
await expectThrow(
deleverage(short, long, positionSize),
'Cannot liquidate when maker position and margin are both negative',
);
});
it('Succeeds deleveraging after bringing margin up to zero', async () => {
// Avoid additional funding.
await ctx.perpetual.testing.funder.setFunding(new BaseValue(0));
// Deposit margin into the target account to bring it to zero margin.
await ctx.perpetual.margin.withdraw(long, long, 500, { from: long });
await ctx.perpetual.margin.deposit(short, 500, { from: long });
// Deleverage the underwater account.
const txResult = await deleverage(short, long, positionSize);
// Check balances.
await expectBalances(
ctx,
txResult,
[long, short],
[new BigNumber(1000), new BigNumber(0)],
[new BigNumber(0), new BigNumber(0)],
);
});
});
});
describe('trade(), via PerpetualV1, as a non-admin', () => {
beforeEach(async () => {
await ctx.perpetual.testing.oracle.setPrice(longUnderwaterPrice);
ctx.perpetual.contracts.resetGasUsed();
});
it('Can mark an account and deleverage it after waiting the timelock period', async () => {
await ctx.perpetual.deleveraging.mark(long, { from: rando });
await fastForward(deleveragingTimelockSeconds);
const txResult = await deleverage(long, short, positionSize, { sender: rando });
await expectBalances(
ctx,
txResult,
[long, short],
[new BigNumber(0), new BigNumber(1000)],
[new BigNumber(0), new BigNumber(0)],
);
});
it('Cannot deleverage an unmarked account', async () => {
await expectThrow(
deleverage(long, short, positionSize, { sender: rando }),
'Cannot deleverage since account is not marked',
);
});
it('Cannot deleverage an account that was not marked for the timelock period', async () => {
await ctx.perpetual.deleveraging.mark(long, { from: rando });
await fastForward(deleveragingTimelockSeconds - 5);
await expectThrow(
deleverage(long, short, positionSize, { sender: rando }),
'Cannot deleverage since account has not been marked for the timelock period',
);
});
it('Can deleverage partially, and then fully, after waiting one timelock period', async () => {
await ctx.perpetual.deleveraging.mark(long, { from: rando });
await fastForward(deleveragingTimelockSeconds);
await deleverage(long, short, positionSize.div(2), { sender: rando });
await deleverage(long, short, positionSize.div(2), { sender: rando });
});
it('Cannot deleverage fully, and then deleverage again, after waiting only once', async () => {
await ctx.perpetual.deleveraging.mark(long, { from: rando });
await fastForward(deleveragingTimelockSeconds);
const txResult = await deleverage(long, short, positionSize, { sender: rando });
// Check logs.
const logs = ctx.perpetual.logs.parseLogs(txResult);
const filteredLogs = _.filter(logs, { name: 'LogUnmarkedForDeleveraging' });
expect(filteredLogs.length).to.equal(1);
expect(filteredLogs[0].args.account).to.equal(long);
// Set up a new underwater position.
await ctx.perpetual.testing.oracle.setPrice(initialPrice);
await mintAndDeposit(ctx, long, new BigNumber(500));
await mintAndDeposit(ctx, rando, new BigNumber(10000));
await buy(ctx, long, rando, positionSize, new BigNumber(1000));
await ctx.perpetual.testing.oracle.setPrice(longUnderwaterPrice);
// Try to deleverage the same account again.
await expectThrow(
deleverage(long, short, positionSize, { sender: rando }),
'Cannot deleverage since account is not marked',
);
});
});
describe('mark()', () => {
it('Can mark an account which is underwater', async () => {
await ctx.perpetual.testing.oracle.setPrice(longUnderwaterPrice);
const txResult = await ctx.perpetual.deleveraging.mark(long);
// Check logs.
const logs = ctx.perpetual.logs.parseLogs(txResult);
expect(logs.length).to.equal(1);
expect(logs[0].name).to.equal('LogMarkedForDeleveraging');
expect(logs[0].args.account).to.equal(long);
});
it('Cannot mark an account which is not underwater', async () => {
await expectThrow(
ctx.perpetual.deleveraging.mark(long),
'Cannot mark since account is not underwater',
);
});
});
describe('unmark()', () => {
beforeEach(async () => {
await ctx.perpetual.testing.oracle.setPrice(longUnderwaterPrice);
await ctx.perpetual.deleveraging.mark(long);
ctx.perpetual.contracts.resetGasUsed();
});
it('Can unmark an account which is not underwater', async () => {
await ctx.perpetual.testing.oracle.setPrice(longBorderlinePrice);
const txResult = await ctx.perpetual.deleveraging.unmark(long);
// Check logs.
const logs = ctx.perpetual.logs.parseLogs(txResult);
expect(logs.length).to.equal(1);
expect(logs[0].name).to.equal('LogUnmarkedForDeleveraging');
expect(logs[0].args.account).to.equal(long);
});
it('Cannot unmark an account which is underwater', async () => {
await expectThrow(
ctx.perpetual.deleveraging.unmark(long),
'Cannot unmark since account is underwater',
);
});
});
async function deleverage(
maker: address,
taker: address,
amount: BigNumberable,
args: {
allOrNothing?: boolean,
isBuy?: boolean,
sender?: address,
} = {},
): Promise<TxResult> {
let { isBuy } = args;
if (typeof isBuy !== 'boolean') {
// By default, infer isBuy from the sign of the maker position.
isBuy = (await ctx.perpetual.getters.getAccountBalance(maker)).position.isPositive();
}
return ctx.perpetual.trade
.initiate()
.deleverage(maker, taker, amount, isBuy, !!args.allOrNothing)
.commit({ from: args.sender || deleveragingOperator });
}
}); | the_stack |
import * as ts from "typescript";
import * as tsserver from "typescript/lib/tsserverlibrary";
import { ApiMethod, ApiMethodKind, isApiMethodKind } from "./api";
import { AppsyncResolver } from "./appsync";
import { EventBus, Rule } from "./event-bridge";
import { EventTransform } from "./event-bridge/transform";
import { Function } from "./function";
import { ExpressStepFunction, StepFunction } from "./step-function";
import { Table } from "./table";
/**
* Various types that could be in a call argument position of a function parameter.
*/
export type TsFunctionParameter =
| ts.FunctionExpression
| ts.ArrowFunction
| ts.Identifier
| ts.PropertyAccessExpression
| ts.ElementAccessExpression
| ts.CallExpression;
export type RuleInterface = ts.NewExpression & {
arguments: [any, any, any, TsFunctionParameter];
};
export type EventTransformInterface = ts.NewExpression & {
arguments: [TsFunctionParameter, any];
};
export type EventBusWhenInterface = ts.CallExpression & {
arguments: [any, any, TsFunctionParameter];
};
export type EventBusMapInterface = ts.CallExpression & {
arguments: [TsFunctionParameter];
};
export type FunctionInterface = ts.NewExpression & {
arguments:
| [
// scope
ts.Expression,
// id
ts.Expression,
// props
ts.Expression,
// closure
TsFunctionParameter
]
| [
// scope
ts.Expression,
// id
ts.Expression,
// closure
TsFunctionParameter
];
};
export type ApiIntegrationsStaticMethodInterface = ts.CallExpression & {
arguments: [ts.ObjectLiteralExpression];
};
export type NewStepFunctionInterface = ts.NewExpression & {
arguments:
| [ts.Expression, ts.Expression, TsFunctionParameter]
| [ts.Expression, ts.Expression, ts.Expression, TsFunctionParameter];
};
export type FunctionlessChecker = ReturnType<typeof makeFunctionlessChecker>;
export function makeFunctionlessChecker(
checker: ts.TypeChecker | tsserver.TypeChecker
) {
return {
...checker,
getApiMethodKind,
getFunctionlessTypeKind,
isApiIntegration,
isAppsyncResolver,
isCDKConstruct,
isConstant,
isEventBus,
isEventBusWhenFunction,
isFunctionlessFunction,
isFunctionlessType,
isIntegrationNode,
isNewEventTransform,
isNewFunctionlessFunction,
isNewRule,
isNewStepFunction,
isReflectFunction,
isRuleMapFunction,
isStepFunction,
isTable,
};
/**
* Matches the patterns:
* * new Rule()
*/
function isNewRule(node: ts.Node): node is RuleInterface {
return ts.isNewExpression(node) && isRule(node.expression);
}
/**
* Matches the patterns:
* * new EventTransform()
*/
function isNewEventTransform(node: ts.Node): node is EventTransformInterface {
return ts.isNewExpression(node) && isEventTransform(node.expression);
}
/**
* Matches the patterns:
* * IEventBus.when
* * IRule.when
*/
function isEventBusWhenFunction(
node: ts.Node
): node is EventBusWhenInterface {
return (
ts.isCallExpression(node) &&
ts.isPropertyAccessExpression(node.expression) &&
node.expression.name.text === "when" &&
(isEventBus(node.expression.expression) ||
isRule(node.expression.expression))
);
}
/**
* Matches the patterns:
* * IRule.map()
*/
function isRuleMapFunction(node: ts.Node): node is EventBusMapInterface {
return (
ts.isCallExpression(node) &&
ts.isPropertyAccessExpression(node.expression) &&
node.expression.name.text === "map" &&
isRule(node.expression.expression)
);
}
/**
* Checks to see if a node is of type EventBus.
* The node could be any kind of node that returns an event bus rule.
*
* Matches the patterns:
* * IEventBus
*/
function isEventBus(node: ts.Node) {
return isFunctionlessClassOfKind(node, EventBus.FunctionlessType);
}
/**
* Checks to see if a node is of type {@link Rule}.
* The node could be any kind of node that returns an event bus rule.
*
* Matches the patterns:
* * IRule
*/
function isRule(node: ts.Node) {
return isFunctionlessClassOfKind(node, Rule.FunctionlessType);
}
/**
* Checks to see if a node is of type {@link EventTransform}.
* The node could be any kind of node that returns an event bus rule.
*
* Matches the patterns:
* * IEventTransform
*/
function isEventTransform(node: ts.Node) {
return isFunctionlessClassOfKind(node, EventTransform.FunctionlessType);
}
function isAppsyncResolver(node: ts.Node): node is ts.NewExpression & {
arguments: [TsFunctionParameter, ...ts.Expression[]];
} {
if (ts.isNewExpression(node)) {
return isFunctionlessClassOfKind(
node.expression,
AppsyncResolver.FunctionlessType
);
}
return false;
}
function isReflectFunction(node: ts.Node): node is ts.CallExpression & {
arguments: [TsFunctionParameter, ...ts.Expression[]];
} {
if (ts.isCallExpression(node)) {
const exprType = checker.getTypeAtLocation(node.expression);
const exprDecl = exprType.symbol?.declarations?.[0];
if (exprDecl && ts.isFunctionDeclaration(exprDecl)) {
if (exprDecl.name?.text === "reflect") {
return true;
}
}
}
return false;
}
function isTable(node: ts.Node) {
return isFunctionlessClassOfKind(node, Table.FunctionlessType);
}
function isStepFunction(node: ts.Node) {
return (
isFunctionlessClassOfKind(node, StepFunction.FunctionlessType) ||
isFunctionlessClassOfKind(node, ExpressStepFunction.FunctionlessType)
);
}
function isNewStepFunction(node: ts.Node): node is NewStepFunctionInterface {
if (ts.isNewExpression(node)) {
return isStepFunction(node.expression);
}
return false;
}
function isFunctionlessFunction(node: ts.Node) {
return isFunctionlessClassOfKind(node, Function.FunctionlessType);
}
function isNewFunctionlessFunction(node: ts.Node): node is FunctionInterface {
return (
ts.isNewExpression(node) &&
isFunctionlessFunction(node.expression) &&
// only take the form with the arrow function at the end.
(node.arguments?.length === 3
? ts.isArrowFunction(node.arguments[2])
: node.arguments?.length === 4
? ts.isArrowFunction(node.arguments[3])
: false)
);
}
function isApiIntegration(node: ts.Node): node is ts.NewExpression {
return (
ts.isNewExpression(node) &&
isFunctionlessClassOfKind(node.expression, ApiMethod.FunctionlessType)
);
}
function getApiMethodKind(node: ts.NewExpression): ApiMethodKind | undefined {
if (isApiIntegration(node)) {
const type = checker.getTypeAtLocation(node);
const kind = type.getProperty("kind");
if (kind) {
const kindType = checker.getTypeOfSymbolAtLocation(kind, node);
if (kindType.isStringLiteral()) {
if (isApiMethodKind(kindType.value)) {
return kindType.value;
}
}
}
}
return undefined;
}
/**
* Heuristically evaluate the fqn of a symbol to be in a module and of a type name.
*
* /somePath/node_modules/{module}/somePath.{typeName}
*
* isInstanceOf(typeSymbol, "constructs", "Construct")
* ex: /home/sussmans/functionless/node_modules/constructs/lib/index.js
*/
function isInstanceOf(symbol: ts.Symbol, module: string, typeName: string) {
const find = /.*\/node_modules\/([^\/]*)\/.*\.(.*)$/g.exec(
checker.getFullyQualifiedName(symbol)
);
const [_, mod, type] = find ?? [];
return mod === module && type === typeName;
}
function isCDKConstruct(type: ts.Type): boolean {
const typeSymbol = type.getSymbol();
return (
((typeSymbol && isInstanceOf(typeSymbol, "constructs", "Construct")) ||
type.getBaseTypes()?.some((t) => isCDKConstruct(t))) ??
false
);
}
/**
* Checks if the type contains one of
* a static property FunctionlessType with the value of {@param kind}
* a property signature functionlessKind with literal type with the value of {@param kind}
* a readonly property functionlessKind with literal type with the value of {@param kind}
*/
function isFunctionlessType(
type: ts.Type | undefined,
kind: string
): boolean {
return !!type && getFunctionlessTypeKind(type) === kind;
}
function isFunctionlessClassOfKind(node: ts.Node, kind: string) {
const type = checker.getTypeAtLocation(node);
return isFunctionlessType(type, kind);
}
function getFunctionlessTypeKind(
type: ts.Type
): ts.Type | string | undefined {
const functionlessType = type.getProperty("FunctionlessType");
const functionlessKind = type.getProperty("functionlessKind");
const prop = functionlessType ?? functionlessKind;
if (prop && prop.valueDeclaration) {
if (
ts.isPropertyDeclaration(prop.valueDeclaration) &&
prop.valueDeclaration.initializer &&
ts.isStringLiteral(prop.valueDeclaration.initializer)
) {
return prop.valueDeclaration.initializer.text;
} else if (ts.isPropertySignature(prop.valueDeclaration)) {
const type = checker.getTypeAtLocation(prop.valueDeclaration);
if (type.isStringLiteral()) {
return type.value;
} else {
return type;
}
}
}
return undefined;
}
/**
* Check if a TS node is a constant value that can be evaluated at compile time.
*/
function isConstant(node: ts.Node): boolean {
if (
ts.isStringLiteral(node) ||
ts.isNumericLiteral(node) ||
node.kind === ts.SyntaxKind.TrueKeyword ||
node.kind === ts.SyntaxKind.FalseKeyword ||
node.kind === ts.SyntaxKind.NullKeyword ||
node.kind === ts.SyntaxKind.UndefinedKeyword
) {
return true;
} else if (ts.isIdentifier(node)) {
const sym = checker
.getSymbolsInScope(
node,
// eslint-disable-next-line no-bitwise
ts.SymbolFlags.BlockScopedVariable |
ts.SymbolFlags.FunctionScopedVariable
)
.find((sym) => sym.name === node.text);
if (sym?.valueDeclaration) {
return isConstant(sym.valueDeclaration);
}
} else if (ts.isVariableDeclaration(node) && node.initializer) {
return isConstant(node.initializer);
} else if (ts.isPropertyAccessExpression(node)) {
return isConstant(node.expression);
} else if (ts.isElementAccessExpression(node)) {
return isConstant(node.argumentExpression) && isConstant(node.expression);
} else if (ts.isArrayLiteralExpression(node)) {
return (
node.elements.length === 0 ||
node.elements.find((e) => !isConstant(e)) === undefined
);
} else if (ts.isSpreadElement(node)) {
return isConstant(node.expression);
} else if (ts.isObjectLiteralExpression(node)) {
return (
node.properties.length === 0 ||
node.properties.find((e) => !isConstant(e)) === undefined
);
} else if (ts.isPropertyAssignment(node)) {
return isConstant(node.initializer);
} else if (ts.isSpreadAssignment(node)) {
return isConstant(node.expression);
} else if (
ts.isBinaryExpression(node) &&
isArithmeticToken(node.operatorToken.kind)
) {
return isConstant(node.left) && isConstant(node.right);
} else if (
ts.isPrefixUnaryExpression(node) &&
node.operator === ts.SyntaxKind.MinusToken
) {
return isConstant(node.operand);
}
return false;
}
function isIntegrationNode(node: ts.Node): boolean {
const exprType = checker.getTypeAtLocation(node);
const exprKind = exprType.getProperty("kind");
if (exprKind) {
const exprKindType = checker.getTypeOfSymbolAtLocation(exprKind, node);
return exprKindType.isStringLiteral();
}
return false;
}
}
const ArithmeticOperators = [
ts.SyntaxKind.PlusToken,
ts.SyntaxKind.MinusToken,
ts.SyntaxKind.AsteriskEqualsToken,
ts.SyntaxKind.SlashToken,
] as const;
export type ArithmeticToken = typeof ArithmeticOperators[number];
/**
* Check if a {@link token} is an {@link ArithmeticToken}: `+`, `-`, `*` or `/`.
*/
export function isArithmeticToken(
token: ts.SyntaxKind
): token is ArithmeticToken {
return ArithmeticOperators.includes(token as ArithmeticToken);
} | the_stack |
import {
Options,
Series,
ChartOptionsUsingYAxis,
Axes,
ViewAxisLabel,
RotationLabelData,
InitAxisData,
Layout,
Categories,
DefaultRadialAxisData,
RadiusInfo,
ScaleData,
} from '@t/store/store';
import { LineTypeXAxisOptions, BulletChartOptions, AxisTitle, Rect } from '@t/options';
import { Theme } from '@t/theme';
import { AxisType } from '@src/component/axis';
import {
divisors,
makeTickPixelPositions,
getTextHeight,
getTextWidth,
} from '@src/helpers/calculator';
import {
range,
isString,
isUndefined,
isNumber,
calculateSizeWithPercentString,
includes,
} from '@src/helpers/utils';
import {
ANGLE_CANDIDATES,
calculateRotatedWidth,
calculateRotatedHeight,
} from '@src/helpers/geometric';
import { getDateFormat, formatDate } from '@src/helpers/formatDate';
import {
calculateDegreeToRadian,
DEGREE_360,
DEGREE_0,
initSectorOptions,
getDefaultRadius,
} from '@src/helpers/sector';
import { DEFAULT_LABEL_TEXT } from '@src/brushes/label';
import { AxisDataParams } from '@src/store/axes';
import { getSemiCircleCenterY, getTotalAngle, isSemiCircle } from './pieSeries';
import { RadialAxisType } from '@src/store/radialAxes';
interface IntervalInfo {
blockCount: number;
remainBlockCount: number;
interval: number;
}
function makeAdjustingIntervalInfo(blockCount: number, axisWidth: number, blockSize: number) {
let remainBlockCount;
let newBlockCount = Math.floor(axisWidth / blockSize);
let intervalInfo: IntervalInfo | null = null;
const interval = newBlockCount ? Math.floor(blockCount / newBlockCount) : blockCount;
if (interval > 1) {
// remainBlockCount : remaining block count after filling new blocks
// | | | | | | | | | | | | - previous block interval
// | | | | - new block interval
// |*|*| - remaining block
remainBlockCount = blockCount - interval * newBlockCount;
if (remainBlockCount >= interval) {
newBlockCount += Math.floor(remainBlockCount / interval);
remainBlockCount = remainBlockCount % interval;
}
intervalInfo = {
blockCount: newBlockCount,
remainBlockCount,
interval,
};
}
return intervalInfo;
}
export function getAutoAdjustingInterval(count: number, axisWidth: number, categories?: string[]) {
const autoInterval = {
MIN_WIDTH: 90,
MAX_WIDTH: 121,
STEP_SIZE: 5,
};
const LABEL_MARGIN = 5;
if (categories?.[0]) {
const categoryMinWidth = getTextWidth(categories[0]);
if (categoryMinWidth < axisWidth / count - LABEL_MARGIN) {
return 1;
}
}
let candidates: IntervalInfo[] = [];
divisors(count).forEach((interval) => {
const intervalWidth = (interval / count) * axisWidth;
if (intervalWidth >= autoInterval.MIN_WIDTH && intervalWidth <= autoInterval.MAX_WIDTH) {
candidates.push({ interval, blockCount: Math.floor(count / interval), remainBlockCount: 0 });
}
});
if (!candidates.length) {
const blockSizeRange = range(
autoInterval.MIN_WIDTH,
autoInterval.MAX_WIDTH,
autoInterval.STEP_SIZE
);
candidates = blockSizeRange.reduce<IntervalInfo[]>((acc, blockSize) => {
const candidate = makeAdjustingIntervalInfo(count, axisWidth, blockSize);
return candidate ? [...acc, candidate] : acc;
}, []);
}
let tickInterval = 1;
if (candidates.length) {
const candidate = candidates.reduce(
(acc, cur) => (cur.blockCount > acc.blockCount ? cur : acc),
{ blockCount: 0, interval: 1 }
);
tickInterval = candidate.interval;
}
return tickInterval;
}
export function isLabelAxisOnYAxis({
series,
options,
categories,
}: {
series: Series;
options?: Options;
categories?: Categories;
}) {
return (
!!series.bar ||
!!series.radialBar ||
(!!series.gauge && Array.isArray(categories) && !categories.length) ||
(!!series.bullet && !(options as BulletChartOptions)?.series?.vertical)
);
}
export function hasBoxTypeSeries(series: Series) {
return !!series.column || !!series.bar || !!series.boxPlot || !!series.bullet;
}
export function isPointOnColumn(series: Series, options: Options) {
if (hasBoxTypeSeries(series)) {
return true;
}
if (series.line || series.area) {
return Boolean((options.xAxis as LineTypeXAxisOptions)?.pointOnColumn);
}
return false;
}
export function isSeriesUsingRadialAxes(series: Series): boolean {
return !!series.radar || !!series.radialBar || !!series.gauge;
}
function getAxisNameUsingRadialAxes(labelAxisOnYAxis: boolean) {
return {
valueAxisName: labelAxisOnYAxis ? 'circularAxis' : 'verticalAxis',
labelAxisName: labelAxisOnYAxis ? 'verticalAxis' : 'circularAxis',
};
}
export function getAxisName(labelAxisOnYAxis: boolean, series: Series) {
return isSeriesUsingRadialAxes(series)
? getAxisNameUsingRadialAxes(labelAxisOnYAxis)
: {
valueAxisName: labelAxisOnYAxis ? 'xAxis' : 'yAxis',
labelAxisName: labelAxisOnYAxis ? 'yAxis' : 'xAxis',
};
}
export function getSizeKey(labelAxisOnYAxis: boolean) {
return {
valueSizeKey: labelAxisOnYAxis ? 'width' : 'height',
labelSizeKey: labelAxisOnYAxis ? 'height' : 'width',
};
}
export function getLimitOnAxis(labels: string[]) {
const values = labels.map((label) => Number(label));
return {
min: Math.min(...values),
max: Math.max(...values),
};
}
export function hasSecondaryYAxis(options: ChartOptionsUsingYAxis) {
return Array.isArray(options?.yAxis) && options.yAxis.length === 2;
}
export function getYAxisOption(options: ChartOptionsUsingYAxis) {
const secondaryYAxis = hasSecondaryYAxis(options);
return {
yAxis: secondaryYAxis ? options.yAxis![0] : options?.yAxis,
secondaryYAxis: secondaryYAxis ? options.yAxis![1] : null,
};
}
export function getValueAxisName(
options: ChartOptionsUsingYAxis,
seriesName: string,
valueAxisName: string
) {
const { secondaryYAxis } = getYAxisOption(options);
return secondaryYAxis?.chartType === seriesName ? 'secondaryYAxis' : valueAxisName;
}
export function getValueAxisNames(options: Options, valueAxisName: string) {
if (includes([AxisType.X, AxisType.CIRCULAR, AxisType.VERTICAL], valueAxisName)) {
return [valueAxisName];
}
const optionsUsingYAxis = options as ChartOptionsUsingYAxis;
const { yAxis, secondaryYAxis } = getYAxisOption(optionsUsingYAxis);
return secondaryYAxis
? [yAxis.chartType, secondaryYAxis.chartType].map((seriesName, index) =>
seriesName
? getValueAxisName(optionsUsingYAxis, seriesName, valueAxisName)
: ['yAxis', 'secondaryYAxis'][index]
)
: [valueAxisName];
}
export function getAxisTheme(theme: Theme, name: string) {
const { xAxis, yAxis, circularAxis } = theme;
let axisTheme;
if (name === AxisType.X) {
axisTheme = xAxis;
} else if (Array.isArray(yAxis)) {
axisTheme = name === AxisType.Y ? yAxis[0] : yAxis[1];
} else if (name === RadialAxisType.CIRCULAR) {
axisTheme = circularAxis;
} else {
axisTheme = yAxis;
}
return axisTheme;
}
function getRotationDegree(
distance: number,
labelWidth: number,
labelHeight: number,
axisLayout: Rect
) {
let degree = 0;
ANGLE_CANDIDATES.every((angle) => {
const compareWidth = calculateRotatedWidth(angle, labelWidth, labelHeight);
degree = angle;
return compareWidth > distance || compareWidth / 2 > axisLayout.x;
});
return distance < labelWidth || labelWidth / 2 > axisLayout.x ? degree : 0;
}
function hasYAxisMaxLabelLengthChanged(
previousAxes: Axes,
currentAxes: Axes,
field: 'yAxis' | 'secondaryYAxis'
) {
const prevYAxis = previousAxes[field];
const yAxis = currentAxes[field];
if (!prevYAxis && !yAxis) {
return false;
}
return prevYAxis?.maxLabelWidth !== yAxis?.maxLabelWidth;
}
function hasYAxisTypeMaxLabelChanged(previousAxes: Axes, currentAxes: Axes): boolean {
return (
hasYAxisMaxLabelLengthChanged(previousAxes, currentAxes, 'yAxis') ||
hasYAxisMaxLabelLengthChanged(previousAxes, currentAxes, 'secondaryYAxis')
);
}
function hasXAxisSizeChanged(previousAxes: Axes, currentAxes: Axes): boolean {
const { maxHeight: prevMaxHeight } = previousAxes.xAxis;
const { maxHeight } = currentAxes.xAxis;
return prevMaxHeight !== maxHeight;
}
export function hasAxesLayoutChanged(previousAxes: Axes, currentAxes: Axes) {
return (
hasYAxisTypeMaxLabelChanged(previousAxes, currentAxes) ||
hasXAxisSizeChanged(previousAxes, currentAxes)
);
}
export function getRotatableOption(options: Options) {
return options?.xAxis?.label?.rotatable ?? true;
}
type ViewAxisLabelParam = {
labels: string[];
pointOnColumn?: boolean;
labelDistance?: number;
scale?: ScaleData;
labelInterval: number;
tickDistance: number;
tickInterval: number;
tickCount: number;
};
export function getViewAxisLabels(axisData: ViewAxisLabelParam, axisSize: number) {
const {
labels,
pointOnColumn,
labelDistance,
tickDistance,
labelInterval,
tickInterval,
tickCount,
scale,
} = axisData;
let axisSizeAppliedRatio = axisSize;
let additional = 0;
let labelAdjustment = 0;
if (scale) {
const sizeRatio = scale?.sizeRatio ?? 1;
const positionRatio = scale?.positionRatio ?? 0;
axisSizeAppliedRatio = axisSize * sizeRatio;
additional = axisSize * positionRatio;
} else {
const interval = labelInterval === tickInterval ? labelInterval : 1;
labelAdjustment = pointOnColumn ? (labelDistance ?? tickDistance * interval) / 2 : 0;
}
const relativePositions = makeTickPixelPositions(axisSizeAppliedRatio, tickCount, additional);
return labels.reduce<ViewAxisLabel[]>((acc, text, index) => {
const offsetPos = relativePositions[index] + labelAdjustment;
const needRender = !(index % labelInterval) && offsetPos <= axisSize;
return needRender ? [...acc, { offsetPos, text }] : acc;
}, []);
}
export function makeTitleOption(title?: AxisTitle) {
if (isUndefined(title)) {
return title;
}
const defaultOption = { text: '', offsetX: 0, offsetY: 0 };
return isString(title) ? { ...defaultOption, text: title } : { ...defaultOption, ...title };
}
export function getAxisFormatter(options: ChartOptionsUsingYAxis, axisName: string) {
const axisOptions = {
...getYAxisOption(options),
xAxis: options.xAxis,
};
return axisOptions[axisName]?.label?.formatter ?? ((value) => value);
}
export function getLabelsAppliedFormatter(
labels: string[],
options: Options,
dateType: boolean,
axisName: string
) {
const dateFormatter = getDateFormat(options?.[axisName]?.date);
const formattedLabels =
dateType && dateFormatter
? labels.map((label) => formatDate(dateFormatter, new Date(label)))
: labels;
const formatter = getAxisFormatter(options as ChartOptionsUsingYAxis, axisName);
return formattedLabels.map((label, index) => formatter(label, { index, labels, axisName }));
}
export function makeRotationData(
maxLabelWidth: number,
maxLabelHeight: number,
distance: number,
rotatable: boolean,
axisLayout: Rect
): Required<RotationLabelData> {
const degree = getRotationDegree(distance, maxLabelWidth, maxLabelHeight, axisLayout);
if (!rotatable || degree === 0) {
return {
needRotateLabel: false,
radian: 0,
rotationHeight: maxLabelHeight,
};
}
return {
needRotateLabel: degree > 0,
radian: calculateDegreeToRadian(degree, 0),
rotationHeight: calculateRotatedHeight(degree, maxLabelWidth, maxLabelHeight),
};
}
export function getMaxLabelSize(labels: string[], xMargin: number, font = DEFAULT_LABEL_TEXT) {
const maxLengthLabel = labels.reduce((acc, cur) => (acc.length > cur.length ? acc : cur), '');
return {
maxLabelWidth: getTextWidth(maxLengthLabel, font) + xMargin,
maxLabelHeight: getTextHeight(maxLengthLabel, font),
};
}
export function getLabelXMargin(axisName: string, options: Options) {
if (axisName === 'xAxis') {
return 0;
}
const axisOptions = getYAxisOption(options as ChartOptionsUsingYAxis);
return Math.abs(axisOptions?.[axisName]?.label?.margin ?? 0);
}
export function getInitAxisIntervalData(isLabelAxis: boolean, params: AxisDataParams) {
const { axis, categories, layout, isCoordinateTypeChart } = params;
const tickInterval = axis?.tick?.interval;
const labelInterval = axis?.label?.interval;
const existIntervalOptions = isNumber(tickInterval) || isNumber(labelInterval);
const needAdjustInterval =
isLabelAxis &&
!isNumber(axis?.scale?.stepSize) &&
!params.shift &&
!existIntervalOptions &&
!isCoordinateTypeChart;
const initTickInterval = needAdjustInterval ? getInitTickInterval(categories, layout) : 1;
const initLabelInterval = needAdjustInterval ? initTickInterval : 1;
const axisData: InitAxisData = {
tickInterval: tickInterval ?? initTickInterval,
labelInterval: labelInterval ?? initLabelInterval,
};
return axisData;
}
function getInitTickInterval(categories?: string[], layout?: Layout) {
if (!categories || !layout) {
return 1;
}
const { width } = layout.xAxis;
const count = categories.length;
return getAutoAdjustingInterval(count, width, categories);
}
export function getDefaultRadialAxisData(
options: Options,
plot: Rect,
maxLabelWidth = 0,
maxLabelHeight = 0,
isLabelOnVerticalAxis = false
): DefaultRadialAxisData {
const centerX = plot.width / 2;
if (isLabelOnVerticalAxis) {
const { startAngle, endAngle, clockwise } = initSectorOptions(options?.series);
const isSemiCircular = isSemiCircle(clockwise, startAngle, endAngle);
return {
isSemiCircular,
axisSize: getDefaultRadius(plot, isSemiCircular, maxLabelWidth, maxLabelHeight),
centerX,
centerY: isSemiCircular ? getSemiCircleCenterY(plot.height, clockwise) : plot.height / 2,
totalAngle: getTotalAngle(clockwise, startAngle, endAngle),
drawingStartAngle: startAngle,
clockwise,
startAngle,
endAngle,
};
}
return {
isSemiCircular: false,
axisSize: getDefaultRadius(plot, false, maxLabelWidth, maxLabelHeight),
centerX,
centerY: plot.height / 2,
totalAngle: DEGREE_360,
drawingStartAngle: DEGREE_0,
clockwise: true,
startAngle: DEGREE_0,
endAngle: DEGREE_360,
};
}
export function getRadiusInfo(
axisSize: number,
radiusRange?: { inner?: number | string; outer?: number | string },
count = 1
): RadiusInfo {
const innerRadius = calculateSizeWithPercentString(axisSize, radiusRange?.inner ?? 0);
const outerRadius = calculateSizeWithPercentString(axisSize, radiusRange?.outer ?? axisSize);
return {
radiusRanges: makeTickPixelPositions(outerRadius - innerRadius, count, innerRadius)
.splice(innerRadius === 0 ? 1 : 0, count)
.reverse(),
innerRadius,
outerRadius,
};
}
export function isDateType(options: Options, axisName: string) {
return !!options[axisName]?.date;
} | the_stack |
"atomic component";
//import gl-matrix library
//https://github.com/toji/gl-matrix for more information
import {vec3, quat} from "gl-matrix";
//define constans
const MOVE_FORCE = 1.8;
const INAIR_MOVE_FORCE = 0.02;
const BRAKE_FORCE = 0.2;
const JUMP_FORCE = 7.0;
const YAW_SENSITIVITY = 0.1;
const INAIR_THRESHOLD_TIME = 0.1;
//define a component AvatarController
class AvatarController extends Atomic.JSComponent {
//define an inspectorFields to make variables visible in editor
inspectorFields = {
//needs default value to make editor understand type of that value
speed: 1.0
};
speed = 1.0;
cameraNode: Atomic.Node;
onGround = true;
okToJump = true;
inAirTime = 0.0;
softGrounded = true;
cameraMode = 0;
yaw = 0;
pitch = 0;
moveForward = false;
moveBackwards = false;
moveLeft = false;
moveRight = false;
mouseMoveX = 0.0;
mouseMoveY = 0.0;
button0 = false;
button1 = false;
lastButton0 = false;
lastButton1 = false;
idle = true;
start() {
//get main camera and set its node to cameraNode
const camera = this.node.scene.getMainCamera();
this.cameraNode = camera.node;
// Create rigidbody, and set non-zero mass so that the body becomes dynamic
const body = <Atomic.RigidBody>this.node.createComponent("RigidBody");
body.mass = 1.0;
// Set zero angular factor so that physics doesn't turn the character on its own.
// Instead we will control the character yaw manually
body.angularFactor = [0, 0, 0];
// Set the rigidbody to signal collision also when in rest, so that we get ground collisions properly
body.collisionEventMode = Atomic.CollisionEventMode.COLLISION_ALWAYS;
// Set a capsule shape for collision
const shape = <Atomic.CollisionShape>this.node.createComponent("CollisionShape");
shape.setCapsule(2, 4, [0, 2, 0]);
}
fixedUpdate(timeStep: number) {
//get a RigidBody component from the current node
const body = <Atomic.RigidBody>this.node.getComponent("RigidBody");
// Update the in air timer. Reset if grounded
if (!this.onGround) {
this.inAirTime += timeStep;
}
else {
this.inAirTime = 0.0;
}
// When character has been in air less than 1/10 second, it's still interpreted as being on ground
const softGrounded = this.inAirTime < INAIR_THRESHOLD_TIME;
// Get rotation of the current node
const rot = this.node.getRotation();
let moveDir = [0, 0, 0];
// Update movement & animation
const velocity = body.getLinearVelocity();
// Velocity on the XZ plane
const planeVelocity = [velocity[0], 0.0, velocity[2]];
if (this.cameraMode != 2) {
if (this.moveForward) {
vec3.add(moveDir, moveDir, [0, 0, 1]);
}
if (this.moveBackwards) {
vec3.add(moveDir, moveDir, [0, 0, -1]);
}
if (this.moveLeft) {
vec3.add(moveDir, moveDir, [-1, 0, 0]);
}
if (this.moveRight) {
vec3.add(moveDir, moveDir, [1, 0, 0]);
}
}
if (vec3.length(moveDir) > 0.0) {
vec3.normalize(moveDir, moveDir);
}
vec3.transformQuat(moveDir, moveDir, [rot[1], rot[2], rot[3], rot[0]]);
vec3.scale(moveDir, moveDir, (softGrounded ? MOVE_FORCE : INAIR_MOVE_FORCE));
if (this.softGrounded) {
vec3.scale(moveDir, moveDir, this.speed);
}
body.applyImpulse(moveDir);
if (this.softGrounded) {
// When on ground, apply a braking force to limit maximum ground velocity
vec3.negate(planeVelocity, planeVelocity);
vec3.scale(planeVelocity, planeVelocity, BRAKE_FORCE);
body.applyImpulse(planeVelocity);
// Jump. Must release jump control inbetween jumps
if (this.button1) {
if (this.okToJump) {
let jumpforce = [0, 1, 0];
vec3.scale(jumpforce, jumpforce, JUMP_FORCE);
//Apply impulse to the body
body.applyImpulse(jumpforce);
this.okToJump = false;
}
} else {
this.okToJump = true;
}
}
if (this.softGrounded && vec3.length(moveDir) > 0.0) {
this.idle = false;
} else {
this.idle = true;
}
// Reset grounded flag for next frame
this.onGround = true;
}
MoveCamera(timeStep) {
// Movement speed as world units per second
const MOVE_SPEED = 10.0;
// Mouse sensitivity as degrees per pixel
const MOUSE_SENSITIVITY = 0.1;
this.yaw = this.yaw + MOUSE_SENSITIVITY * this.mouseMoveX;
this.pitch = this.pitch + MOUSE_SENSITIVITY * this.mouseMoveY;
if (this.pitch < -90) {
this.pitch = -90;
}
if (this.pitch > 90) {
this.pitch = 90;
}
// Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
this.cameraNode.rotation = QuatFromEuler(this.pitch, this.yaw, 0.0);
let speed = MOVE_SPEED * timeStep;
//translate camera on the amount of speed value
if (this.moveForward) {
this.cameraNode.translate([0.0, 0.0, this.speed]);
}
if (this.moveBackwards) {
this.cameraNode.translate([0.0, 0.0, -this.speed]);
}
if (this.moveLeft) {
this.cameraNode.translate([-speed, 0.0, 0.0]);
}
if (this.moveRight) {
this.cameraNode.translate([speed, 0.0, 0.0]);
}
}
UpdateControls() {
let input = Atomic.input;
this.moveForward = false;
this.moveBackwards = false;
this.moveLeft = false;
this.moveRight = false;
this.mouseMoveX = 0.0;
this.mouseMoveY = 0.0;
this.button0 = false;
this.button1 = false;
// Movement speed as world units per second
// let MOVE_SPEED = 20.0; -- unused
// Mouse sensitivity as degrees per pixel
// let MOUSE_SENSITIVITY = 0.1; -- unused
//check input
if (input.getKeyDown(Atomic.KEY_W) || input.getKeyDown(Atomic.KEY_UP)) {
this.moveForward = true;
}
if (input.getKeyDown(Atomic.KEY_S) || input.getKeyDown(Atomic.KEY_DOWN)) {
this.moveBackwards = true;
}
if (input.getKeyDown(Atomic.KEY_A) || input.getKeyDown(Atomic.KEY_LEFT)) {
this.moveLeft = true;
}
if (input.getKeyDown(Atomic.KEY_D) || input.getKeyDown(Atomic.KEY_RIGHT)) {
this.moveRight = true;
}
if (input.getKeyPress(Atomic.KEY_F)) {
this.button0 = true;
}
if (input.getKeyPress(Atomic.KEY_SPACE)) {
this.button1 = true;
}
//if we are on mobile
if (Atomic.platform == "Android" || Atomic.platform == "iOS") {
//iterate through each TouchState, if it doesn't touch any widgets, use it as a `mouse`
for (let i = 0; i < Atomic.input.getNumTouches(); i++) {
let touchState = Atomic.input.getTouch(i);
if (touchState.touchedWidget == null) {
let delta = touchState.delta;
this.mouseMoveX = delta[0];
this.mouseMoveY = delta[1];
}
}
//if its a desktop
} else {
// update mouse coordinates
this.mouseMoveX = input.getMouseMoveX();
this.mouseMoveY = input.getMouseMoveY();
}
}
update(timeStep) {
this.UpdateControls();
//if it's a free view
if (this.cameraMode != 2) {
this.yaw += this.mouseMoveX * YAW_SENSITIVITY;
this.pitch += this.mouseMoveY * YAW_SENSITIVITY;
}
if (this.pitch < -80) {
this.pitch = -80;
}
if (this.pitch > 80) {
this.pitch = 80;
}
if (this.button0) {
this.cameraMode++;
if (this.cameraMode == 3) {
this.cameraMode = 0;
}
}
}
//that function called right after update function
postUpdate(timestep: number) {
// Get camera lookat dir from character yaw + pitch
let rot = this.node.getRotation();
//create quaternion
let dir = quat.create();
//set X value
quat.setAxisAngle(dir, [1, 0, 0], (this.pitch * Math.PI / 180.0));
quat.multiply(dir, [rot[1], rot[2], rot[3], rot[0]], dir);
let headNode = this.node.getChild("Head_Tip", true);
//if it's a FPS view
if (this.cameraMode == 1) {
let headPos = <number[]>headNode.getWorldPosition();
let offset = [0.0, 0.15, 0.2];
vec3.add(headPos, headPos, vec3.transformQuat(offset, offset, [rot[1], rot[2], rot[3], rot[0]]));
this.cameraNode.setPosition(headPos);
this.cameraNode.setRotation([dir[3], dir[0], dir[1], dir[2]]);
quat.setAxisAngle(dir, [0, 1, 0], (this.yaw * Math.PI / 180.0));
this.node.setRotation([dir[3], dir[0], dir[1], dir[2]]);
}
//if it's a third person view
if (this.cameraMode == 0) {
let aimPoint = <number[]>this.node.getWorldPosition();
let aimOffset = [0, 1.7, 0];
vec3.transformQuat(aimOffset, aimOffset, dir);
vec3.add(aimPoint, aimPoint, aimOffset);
let rayDir = vec3.create();
vec3.transformQuat(rayDir, [0, 0, -1], dir);
vec3.scale(rayDir, rayDir, 8);
vec3.add(aimPoint, aimPoint, rayDir);
this.cameraNode.setPosition(aimPoint);
this.cameraNode.setRotation([dir[3], dir[0], dir[1], dir[2]]);
quat.setAxisAngle(dir, [0, 1, 0], (this.yaw * Math.PI / 180.0));
this.node.setRotation([dir[3], dir[0], dir[1], dir[2]]);
}
else {
this.MoveCamera(timestep);
}
}
}
function QuatFromEuler(x, y, z) {
const M_PI = 3.14159265358979323846264338327950288;
let q = [0, 0, 0, 0];
x *= (M_PI / 360);
y *= (M_PI / 360);
z *= (M_PI / 360);
const sinX = Math.sin(x);
const cosX = Math.cos(x);
const sinY = Math.sin(y);
const cosY = Math.cos(y);
const sinZ = Math.sin(z);
const cosZ = Math.cos(z);
q[0] = cosY * cosX * cosZ + sinY * sinX * sinZ;
q[1] = cosY * sinX * cosZ + sinY * cosX * sinZ;
q[2] = sinY * cosX * cosZ - cosY * sinX * sinZ;
q[3] = cosY * cosX * sinZ - sinY * sinX * cosZ;
return q;
}
export = AvatarController; | the_stack |
'use strict';
import { ChildProcess } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import * as spawn from 'spawn-command-with-kill';
import * as vscode from 'vscode';
import GlslOptions from './options';
export interface GlslExportInclude {
fragment: string;
filename: string;
}
export default class GlslExport {
static terminal: vscode.Terminal;
static npm: boolean = false;
static onExport(extensionPath: string, options: GlslOptions) {
// console.log('GlslExport.onExport', extensionPath, options);
const includes = GlslExport.collectInlineIncludes(options.folder, options.fragment);
// console.log('GlslExport.includes', includes);
// const includeUris: string[] = GlslExport.getInlineIncludes(options);
const textureUris: string[] = GlslExport.getInlineTextures(options.fragment);
const modelUris: string[] = GlslExport.getInlineModels(options.fragment);
const uniforms: { [key: string]: any } = {};
for (let key in options.uniforms) {
const regexp = new RegExp('uniform\\s+\\w*\\s+(' + key + ')\\s*;');
if (regexp.test(options.fragment)) {
uniforms[key] = options.uniforms[key];
}
}
const textures: { [key: string]: string } = {};
for (let key in options.textures) {
const regexp = new RegExp('uniform\\s+sampler2D\\s+(u_texture_' + key + ')\\s*;');
if (regexp.test(options.fragment)) {
let texture = options.textures[key];
// if (texture.indexOf(options.workpath) === 0) {
if (texture.indexOf('http') === -1) {
// texture = texture.replace(options.workpath, '');
textureUris.push(texture);
}
textures[key] = texture;
}
}
// const uniforms = JSON.stringify(options.uniforms, null, '\t');
GlslExport.selectFolder().then((outputPath: string) => {
const resourcePath = vscode.Uri.file(path.join(extensionPath, 'resources', 'export')).fsPath;
const basePath = options.folder;
/*
const tasks1: Promise<string[] | string>[] = includeUris.map((x, i) => GlslExport.copyFile(
path.join(basePath, x),
path.join(outputPath, 'shaders', `${i}-${path.basename(x)}`)
));
*/
const tasks1: Promise<string[] | string>[] = includes.map((x, i) => GlslExport.writeFile(
x.fragment,
path.join(outputPath, x.filename)
));
const tasks2: Promise<string[] | string>[] = textureUris.map(x => GlslExport.copyFile(
path.join(basePath, x),
path.join(outputPath, x)
));
const tasks3: Promise<string[] | string>[] = modelUris.map(x => GlslExport.copyFile(
path.join(basePath, x),
path.join(outputPath, x)
));
const tasks4: Promise<string[] | string>[] = [
GlslExport.copyFolder(
path.join(resourcePath),
path.join(outputPath)
),
GlslExport.copyFolder(
path.join(resourcePath, 'css'),
path.join(outputPath, 'css')
),
GlslExport.copyFolder(
path.join(resourcePath, 'img'),
path.join(outputPath, 'img')
),
GlslExport.copyFile(
path.join(extensionPath, 'resources', 'model', 'duck-toy.obj'),
path.join(outputPath, 'model', 'duck-toy.obj')
),
GlslExport.copyFile(
path.join(extensionPath, 'node_modules', 'stats.js', 'build', 'stats.min.js'),
path.join(outputPath, 'js', 'stats.min.js')
),
GlslExport.copyFolder(
path.join(extensionPath, 'node_modules', 'glsl-canvas-js', 'dist', 'umd'),
path.join(outputPath, 'js')
),
/*
GlslExport.copyFile(
path.join(extensionPath, 'node_modules', 'glsl-canvas-js', 'dist', 'umd', 'glsl-canvas.min.js'),
path.join(outputPath, 'js', 'glsl-canvas.min.js')
),
*/
/*
GlslExport.writeFile(
options.fragment,
path.join(outputPath, 'shaders', 'fragment.glsl')
),
*/
GlslExport.writeFile(`<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=2,user-scalable=yes">
<title>GlslCanvas</title>
<link type="image/png" href="/img/favicon-32x32.png" sizes="32x32" rel="icon" />
<link type="image/png" href="/img/favicon-16x16.png" sizes="16x16" rel="icon" />
<link type="image/x-icon" href="/img/favicon.ico" rel="icon"/>
<link type="text/css" href="/css/glsl-canvas.css" rel="stylesheet"/>
<script type="text/javascript" src="/js/stats.min.js"></script>
<script type="text/javascript" src="/js/glsl-canvas.min.js"></script>
</head>
<body>
<canvas class="glsl-canvas" data-fragment-url="shaders/fragment.glsl"></canvas>
</body>
<script>
/*
stats.js
*/
var stats = new Stats();
stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom
document.body.appendChild(stats.dom);
/*
glsl-canvas.js
Attributes: data-fragment-url, data-vertex-url, data-fragment, data-vertex, controls, data-autoplay
Events: load, error, textureError, render, over, out, move, click
Methods: load, on, pause, play, toggle, setTexture, setUniform, setUniforms, destroy
*/
var options = {
backgroundColor: 'rgba(0.0, 0.0, 0.0, 0.0)',
alpha: true,
antialias: true,
premultipliedAlpha: false,
preserveDrawingBuffer: false, ${options.mode !== 'flat' ? `
mode: ${JSON.stringify(options.mode)},
mesh: 'model/duck-toy.obj',` : ``}
extensions: ${JSON.stringify(options.extensions)},
doubleSided: ${JSON.stringify(options.doubleSided)},
};
var canvas = document.querySelector('.glsl-canvas');
var glsl = new glsl.Canvas(canvas, options);
glsl.setUniforms(${JSON.stringify(uniforms)});${Object.keys(textures).map(x => `
glsl.setTexture('u_texture_${x}', '${textures[x]}', {
filtering: 'mipmap',
repeat: true,
});`).join('')}
glsl.on('render', function () {
stats.end();
// execute here custom code on every raf tick
stats.begin();
});
</script>
</html>`,
path.join(outputPath, 'index.html')
)
];
Promise.all(tasks1.concat(tasks2, tasks3, tasks4)).then(resolve => {
// console.log('GlslExport.all.resolve', resolve);
GlslExport.detectNpm().then(has => {
GlslExport.npmInstallOrStart(outputPath).then((success: vscode.Terminal) => {
// console.log('GlslExport.npmInstall.success', success);
}, (error: any) => {
console.log('GlslExport.npmInstallOrStart.error', error);
});
}, error => {
vscode.window.showInformationMessage(`All files exported to '${outputPath}'`);
});
}, reject => {
console.log('GlslExport.all.reject', reject);
});
});
}
static selectFolder(openLabel: string = 'Export'): Promise<string> {
return new Promise((resolve, reject) => {
const options: vscode.OpenDialogOptions = {
canSelectFiles: false,
canSelectFolders: true,
canSelectMany: false,
openLabel: openLabel,
};
vscode.window.showOpenDialog(options).then((uris: vscode.Uri[]) => {
if (uris && uris[0]) {
const outputPath = uris[0].fsPath;
// console.log('GlslExport', openLabel + ' ' + outputPath);
resolve(outputPath);
}
});
});
}
static readFiles(folder: string): Promise<string[]> {
return new Promise((resolve, reject) => {
fs.readdir(folder, (error, files) => {
if (error) {
reject(error);
} else {
resolve(files);
}
});
});
}
static copyFolder(src: string, dest: string): Promise<string[]> {
return new Promise((resolve, reject) => {
GlslExport.readFiles(src).then((files: string[]) => {
Promise.all(
files.filter(x => {
const filePath = path.join(src, x);
return fs.existsSync(filePath) && fs.lstatSync(filePath).isFile();
}).map(x => {
return GlslExport.copyFile(
path.join(src, x),
path.join(dest, x)
);
})
).then(files => {
resolve(files);
}, error => {
reject(error);
});
}, error => {
reject(error);
});
});
}
static copyFile(src: string, dest: string): Promise<string> {
return new Promise((resolve, reject) => {
const folder = path.dirname(dest);
GlslExport.existsOrCreateFolder(folder).then(_ => {
fs.copyFile(src, dest, (error) => {
if (error) {
reject(error);
} else {
resolve(dest);
}
});
}, error => {
reject(error);
});
});
}
static writeFile(content: string, dest: string): Promise<string> {
return new Promise((resolve, reject) => {
const folder = path.dirname(dest);
GlslExport.existsOrCreateFolder(folder).then(_ => {
fs.writeFile(dest, content, 'utf8', error => {
if (error) {
reject(error);
} else {
resolve(dest);
}
});
}, error => {
reject(error);
});
});
}
static readFile(src: string): string {
return fs.readFileSync(src, { encoding: 'utf8' });
}
static existsOrCreateFolder(folder: string): Promise<string> {
return new Promise((resolve, reject) => {
if (fs.existsSync(folder)) {
resolve(folder);
} else {
return fs.mkdir(folder, (error) => {
if (error) {
if (fs.existsSync(folder)) {
resolve(folder);
} else {
reject(error);
}
} else {
resolve(folder);
}
});
}
});
}
static npmInstallOrStart(dest: string): Thenable<vscode.Terminal> {
return new Promise((resolve, _) => {
if (fs.existsSync(path.join(dest, 'node_modules'))) {
const terminal = GlslExport.runCommand(['--prefix', `"${dest}"`, 'start', `"${dest}"`], dest);
resolve(terminal);
} else {
const terminal = GlslExport.runCommand(['--prefix', `"${dest}"`, 'install', `"${dest}"`], dest);
resolve(terminal);
}
});
}
static runCommand(args: string[], workpath: string | undefined): vscode.Terminal {
const cmd_args = Array.from(args);
if (!GlslExport.terminal) {
GlslExport.terminal = vscode.window.createTerminal('npm');
}
GlslExport.terminal.show();
if (workpath) {
// Replace single backslash with double backslash.
const textCwd = workpath.replace(/\\/g, '\\\\');
GlslExport.terminal.sendText(['cd', `"${textCwd}"`].join(' '));
}
cmd_args.splice(0, 0, 'npm');
GlslExport.terminal.sendText(cmd_args.join(' '));
return GlslExport.terminal;
}
/*
static getInlineIncludes(options: GlslOptions): string[] {
const fragmentString = options.fragment;
const slices: string[] = [];
const includes: string[] = [];
const regexp = /#include\s*['|"](.*.glsl)['|"]/gm;
let i = 0, n = 0;
let match: RegExpExecArray;
while ((match = regexp.exec(fragmentString)) !== null) {
slices.push(fragmentString.slice(i, match.index));
i = match.index + match[0].length;
// const include = match[1].replace(`${WORKPATH_SCHEME}/`, '');
const include = match[1];
const file = path.basename(include);
includes.push(include);
// console.log('GlslExport.include', include, 'file', file);
slices.push(`#include "shaders/${n}-${file}"`);
n++;
}
slices.push(fragmentString.slice(i));
const fragment = slices.join('');
options.fragment = fragment;
// console.log('GlslExport.fragment', fragment);
// return [];
return includes;
}
*/
static collectInlineIncludes(folder: string, fragmentString: string, filename: string = 'shaders/fragment.glsl', n:number = 0, includes: GlslExportInclude[] = []): GlslExportInclude[] {
const slices: string[] = [];
const regexp = /^\s*#include\s*['|"]((?!http:\/\/|https:\/\/).*.glsl)['|"]/gm;
let i = 0;
let match: RegExpExecArray;
while ((match = regexp.exec(fragmentString)) !== null) {
slices.push(fragmentString.slice(i, match.index));
i = match.index + match[0].length;
const fileName = match[1];
const filePath = path.join(folder, fileName);
const nextWorkpath = fileName.indexOf(':/') === -1 ? path.dirname(filePath) : '';
// console.log('GlslExport.collectInlineIncludes.filePath', filePath);
const includeFragment = GlslExport.readFile(filePath);
const uniqueFileName = `${n}-${path.basename(fileName)}`;
const uniqueFilePath = path.join('shaders', uniqueFileName);
n++;
includes = GlslExport.collectInlineIncludes(nextWorkpath, includeFragment, uniqueFilePath, n, includes);
slices.push(`#include "${uniqueFileName}"`);
}
slices.push(fragmentString.slice(i));
const fragment = slices.join('');
const include = { fragment, filename };
includes.push(include);
return includes;
}
static getInlineTextures(fragmentString: string): string[] {
const textures: string[] = [];
const textureExtensions = ['jpg', 'jpeg', 'png', 'ogv', 'webm', 'mp4'];
const regexp = /^\s*uniform\s+sampler2D\s+([\w]+);(\s*\/\/\s*((?!http:\/\/|https:\/\/)[\w|\.|\/|\-|\_]*)|\s*)/gm;
let matches: RegExpExecArray;
while ((matches = regexp.exec(fragmentString)) !== null) {
// const key = matches[1];
if (matches[3]) {
const ext = matches[3].split('.').pop().toLowerCase();
const url = matches[3];
if (url && textureExtensions.indexOf(ext) !== -1) {
textures.push(url);
}
}
}
return textures;
}
static getInlineModels(fragmentString: string): string[] {
const textures: string[] = [];
const textureExtensions = ['obj'];
const regexp = /^\s*attribute\s+vec4\s+([\w]+);(\s*\/\/\s*((?!http:\/\/|https:\/\/)[\w|\.|\/|\-|\_]*)|\s*)/gm;
let matches: RegExpExecArray;
while ((matches = regexp.exec(fragmentString)) !== null) {
// const key = matches[1];
if (matches[3]) {
const ext = matches[3].split('.').pop().toLowerCase();
const url = matches[3];
if (url && textureExtensions.indexOf(ext) !== -1) {
textures.push(url);
}
}
}
return textures;
}
static detectNpm(): Promise<boolean> {
return new Promise((resolve, reject) => {
const config = vscode.workspace.getConfiguration('glsl-canvas');
if (config['installOnExport'] === false) {
return reject(false);
}
if (GlslExport.npm) {
return resolve(true);
}
const childProcess: ChildProcess = spawn('npm -v');
childProcess.stdout.on('data', function (_) {
// console.log('GlslExport.stdout', data.toString());
GlslExport.npm = true;
resolve(true);
});
childProcess.stderr.on('data', function (data) {
// console.log('GlslExport.stderr', data.toString());
reject(data.toString());
});
childProcess.kill();
});
}
static dispose() {
if (GlslExport.terminal) {
GlslExport.terminal.dispose();
GlslExport.terminal = null;
}
}
} | the_stack |
import pick from 'lodash.pick';
import {VERSIONS} from './versions';
import {isValidFilterValue} from 'utils/filter-utils';
import {LAYER_VIS_CONFIGS} from 'layers/layer-factory';
import Schema from './schema';
import cloneDeep from 'lodash.clonedeep';
import {notNullorUndefined} from 'utils/data-utils';
/**
* V0 Schema
*/
export const dimensionPropsV0 = ['name', 'type'];
export type modifiedType = {
strokeColor?: any;
strokeColorRange?: any;
filled?: boolean;
stroked?: boolean;
};
// in v0 geojson there is only sizeField
// in v1 geojson
// stroke base on -> sizeField
// height based on -> heightField
// radius based on -> radiusField
// here we make our wiredst guess on which channel sizeField belongs to
function geojsonSizeFieldV0ToV1(config) {
const defaultRaiuds = 10;
const defaultRadiusRange = [0, 50];
// if extruded, sizeField is most likely used for height
if (config.visConfig.extruded) {
return 'heightField';
}
// if show stroke enabled, sizeField is most likely used for stroke
if (config.visConfig.stroked) {
return 'sizeField';
}
// if radius changed, or radius Range Changed, sizeField is most likely used for radius
// this is the most unreliable guess, that's why we put it in the end
if (
config.visConfig.radius !== defaultRaiuds ||
config.visConfig.radiusRange.some((d, i) => d !== defaultRadiusRange[i])
) {
return 'radiusField';
}
return 'sizeField';
}
// convert v0 to v1 layer config
class DimensionFieldSchemaV0 extends Schema {
version = VERSIONS.v0;
save(field) {
// should not be called anymore
return {
[this.key]: field !== null ? this.savePropertiesOrApplySchema(field)[this.key] : null
};
}
load(field, parents, accumulated) {
const [config] = parents.slice(-1);
let fieldName = this.key;
if (config.type === 'geojson' && this.key === 'sizeField' && field) {
fieldName = geojsonSizeFieldV0ToV1(config);
}
// fold into visualChannels to be load by VisualChannelSchemaV1
return {
visualChannels: {
...(accumulated.visualChannels || {}),
[fieldName]: field
}
};
}
}
class DimensionScaleSchemaV0 extends Schema {
version = VERSIONS.v0;
save(scale) {
return {[this.key]: scale};
}
load(scale, parents, accumulated) {
const [config] = parents.slice(-1);
// fold into visualChannels to be load by VisualChannelSchemaV1
if (this.key === 'sizeScale' && config.type === 'geojson') {
// sizeScale now split into radiusScale, heightScale
// no user customization, just use default
return {};
}
return {
visualChannels: {
...(accumulated.visualChannels || {}),
[this.key]: scale
}
};
}
}
// used to convert v0 to v1 layer config
class LayerConfigSchemaV0 extends Schema {
version = VERSIONS.v0;
load(saved, parents, accumulated) {
// fold v0 layer property into config.key
return {
config: {
...(accumulated.config || {}),
[this.key]: saved
}
};
}
}
// used to convert v0 to v1 layer columns
// only return column value for each column
class LayerColumnsSchemaV0 extends Schema {
version = VERSIONS.v0;
load(saved, parents, accumulated) {
// fold v0 layer property into config.key, flatten columns
return {
config: {
...(accumulated.config || {}),
columns: Object.keys(saved).reduce(
(accu, key) => ({
...accu,
[key]: saved[key].value
}),
{}
)
}
};
}
}
// used to convert v0 to v1 layer config.visConfig
class LayerConfigToVisConfigSchemaV0 extends Schema {
version = VERSIONS.v0;
load(saved, parents, accumulated) {
// fold v0 layer property into config.visConfig
const accumulatedConfig = accumulated.config || {};
return {
config: {
...accumulatedConfig,
visConfig: {
...(accumulatedConfig.visConfig || {}),
[this.key]: saved
}
}
};
}
}
class LayerVisConfigSchemaV0 extends Schema {
version = VERSIONS.v0;
key = 'visConfig';
load(visConfig, parents, accumulator) {
const [config] = parents.slice(-1);
const rename = {
geojson: {
extruded: 'enable3d',
elevationRange: 'heightRange'
}
};
if (config.type in rename) {
const propToRename = rename[config.type];
return {
config: {
...(accumulator.config || {}),
visConfig: Object.keys(visConfig).reduce(
(accu, key) => ({
...accu,
...(propToRename[key]
? {[propToRename[key]]: visConfig[key]}
: {[key]: visConfig[key]})
}),
{}
)
}
};
}
return {
config: {
...(accumulator.config || {}),
visConfig
}
};
}
}
class LayerConfigSchemaDeleteV0 extends Schema {
version = VERSIONS.v0;
load(value) {
return {};
}
}
/**
* V0 -> V1 Changes
* - layer is now a class
* - config saved in a config object
* - id, type, isAggregated is outside layer.config
* - visualChannels is outside config, it defines available visual channel and
* property names for field, scale, domain and range of each visual chanel.
* - enable3d, colorAggregation and sizeAggregation are moved into visConfig
* - GeojsonLayer - added height, radius specific properties
*/
export const layerPropsV0 = {
id: null,
type: null,
// move into layer.config
dataId: new LayerConfigSchemaV0({key: 'dataId'}),
label: new LayerConfigSchemaV0({key: 'label'}),
color: new LayerConfigSchemaV0({key: 'color'}),
isVisible: new LayerConfigSchemaV0({key: 'isVisible'}),
hidden: new LayerConfigSchemaV0({key: 'hidden'}),
// convert visConfig
visConfig: new LayerVisConfigSchemaV0({key: 'visConfig'}),
// move into layer.config
// flatten
columns: new LayerColumnsSchemaV0(),
// save into visualChannels
colorField: new DimensionFieldSchemaV0({
properties: dimensionPropsV0,
key: 'colorField'
}),
colorScale: new DimensionScaleSchemaV0({
key: 'colorScale'
}),
sizeField: new DimensionFieldSchemaV0({
properties: dimensionPropsV0,
key: 'sizeField'
}),
sizeScale: new DimensionScaleSchemaV0({
key: 'sizeScale'
}),
// move into config.visConfig
enable3d: new LayerConfigToVisConfigSchemaV0({key: 'enable3d'}),
colorAggregation: new LayerConfigToVisConfigSchemaV0({
key: 'colorAggregation'
}),
sizeAggregation: new LayerConfigToVisConfigSchemaV0({key: 'sizeAggregation'}),
// delete
isAggregated: new LayerConfigSchemaDeleteV0()
};
/**
* V1 Schema
*/
class ColumnSchemaV1 extends Schema {
save(columns, state) {
// starting from v1, only save column value
// fieldIdx will be calculated during merge
return {
[this.key]: Object.keys(columns).reduce(
(accu, ckey) => ({
...accu,
[ckey]: columns[ckey].value
}),
{}
)
};
}
load(columns) {
return {columns};
}
}
class TextLabelSchemaV1 extends Schema {
save(textLabel) {
return {
[this.key]: textLabel.map(tl => ({
...tl,
field: tl.field ? pick(tl.field, ['name', 'type']) : null
}))
};
}
load(textLabel) {
return {textLabel: Array.isArray(textLabel) ? textLabel : [textLabel]};
}
}
const visualChannelModificationV1 = {
geojson: (vc, parents, accumulator) => {
const [layer] = parents.slice(-1);
const isOld = !vc.hasOwnProperty('strokeColorField');
// make our best guess if this geojson layer contains point
const isPoint =
vc.radiusField || layer.config.visConfig.radius !== LAYER_VIS_CONFIGS.radius.defaultValue;
if (isOld && !isPoint && layer.config.visConfig.stroked) {
// if stroked is true, copy color config to stroke color config
return {
strokeColorField: vc.colorField,
strokeColorScale: vc.colorScale
};
}
return {};
}
};
/**
* V1: save [field]: {name, type}, [scale]: '' for each channel
*/
class VisualChannelSchemaV1 extends Schema {
save(visualChannels, parents) {
// only save field and scale of each channel
const [layer] = parents.slice(-1);
return {
[this.key]: Object.keys(visualChannels).reduce(
// save channel to null if didn't select any field
(accu, key) => ({
...accu,
[visualChannels[key].field]: layer.config[visualChannels[key].field]
? pick(layer.config[visualChannels[key].field], ['name', 'type'])
: null,
[visualChannels[key].scale]: layer.config[visualChannels[key].scale]
}),
{}
)
};
}
load(vc, parents, accumulator) {
// fold channels into config
const [layer] = parents.slice(-1);
const modified = visualChannelModificationV1[layer.type]
? visualChannelModificationV1[layer.type](vc, parents, accumulator)
: {};
return {
...accumulator,
config: {
...(accumulator.config || {}),
...vc,
...modified
}
};
}
}
const visConfigModificationV1 = {
point: (visConfig, parents, accumulated) => {
const modified: modifiedType = {};
const [layer] = parents.slice(-2, -1);
const isOld =
!visConfig.hasOwnProperty('filled') && !visConfig.strokeColor && !visConfig.strokeColorRange;
if (isOld) {
// color color & color range to stroke color
modified.strokeColor = layer.config.color;
modified.strokeColorRange = cloneDeep(visConfig.colorRange);
if (visConfig.outline) {
// point layer now supports both outline and fill
// for older schema where filled has not been added to point layer
// set it to false
modified.filled = false;
}
}
return modified;
},
geojson: (visConfig, parents, accumulated) => {
// is points?
const modified: modifiedType = {};
const [layer] = parents.slice(-2, -1);
const isOld =
layer.visualChannels &&
!layer.visualChannels.hasOwnProperty('strokeColorField') &&
!visConfig.strokeColor &&
!visConfig.strokeColorRange;
// make our best guess if this geojson layer contains point
const isPoint =
(layer.visualChannels && layer.visualChannels.radiusField) ||
(visConfig && visConfig.radius !== LAYER_VIS_CONFIGS.radius.defaultValue);
if (isOld) {
// color color & color range to stroke color
modified.strokeColor = layer.config.color;
modified.strokeColorRange = cloneDeep(visConfig.colorRange);
if (isPoint) {
// if is point, set stroke to false
modified.filled = true;
modified.stroked = false;
}
}
return modified;
}
};
class VisConfigSchemaV1 extends Schema {
key = 'visConfig';
load(visConfig, parents, accumulated) {
const [layer] = parents.slice(-2, -1);
const modified = visConfigModificationV1[layer.type]
? visConfigModificationV1[layer.type](visConfig, parents, accumulated)
: {};
return {
visConfig: {
...visConfig,
...modified
}
};
}
}
export const layerPropsV1 = {
id: null,
type: null,
config: new Schema({
version: VERSIONS.v1,
key: 'config',
properties: {
dataId: null,
label: null,
color: null,
highlightColor: null,
columns: new ColumnSchemaV1({
version: VERSIONS.v1,
key: 'columns'
}),
isVisible: null,
visConfig: new VisConfigSchemaV1({
version: VERSIONS.v1
}),
hidden: null,
textLabel: new TextLabelSchemaV1({
version: VERSIONS.v1,
key: 'textLabel'
})
}
}),
visualChannels: new VisualChannelSchemaV1({
version: VERSIONS.v1,
key: 'visualChannels'
})
};
export class LayerSchemaV0 extends Schema {
key = 'layers';
save(layers, parents) {
const [visState] = parents.slice(-1);
return {
[this.key]: visState.layerOrder.reduce((saved, index) => {
// save layers according to their rendering order
const layer = layers[index];
if (layer.isValidToSave()) {
saved.push(this.savePropertiesOrApplySchema(layer).layers);
}
return saved;
}, [])
};
}
load(layers) {
return {
[this.key]: layers.map(layer => this.loadPropertiesOrApplySchema(layer, layers).layers)
};
}
}
export class FilterSchemaV0 extends Schema {
key = 'filters';
save(filters) {
return {
filters: filters
.filter(isValidFilterValue)
.map(filter => this.savePropertiesOrApplySchema(filter).filters)
};
}
load(filters) {
return {filters};
}
}
const interactionPropsV0 = ['tooltip', 'brush'];
class InteractionSchemaV0 extends Schema {
key = 'interactionConfig';
save(interactionConfig) {
return Array.isArray(this.properties)
? {
[this.key]: this.properties.reduce(
(accu, key) => ({
...accu,
...(interactionConfig[key].enabled ? {[key]: interactionConfig[key].config} : {})
}),
{}
)
}
: {};
}
load(interactionConfig) {
// convert v0 -> v1
// return enabled: false if disabled,
return Array.isArray(this.properties)
? {
[this.key]: this.properties.reduce(
(accu, key) => ({
...accu,
...{
[key]: {
...(interactionConfig[key] || {}),
enabled: Boolean(interactionConfig[key])
}
}
}),
{}
)
}
: {};
}
}
const interactionPropsV1 = [...interactionPropsV0, 'geocoder', 'coordinate'];
export class InteractionSchemaV1 extends Schema {
key = 'interactionConfig';
save(interactionConfig) {
// save config even if disabled,
return Array.isArray(this.properties)
? {
[this.key]: this.properties.reduce(
(accu, key) => ({
...accu,
[key]: {
...interactionConfig[key].config,
enabled: interactionConfig[key].enabled
}
}),
{}
)
}
: {};
}
load(interactionConfig) {
const modifiedConfig = interactionConfig;
Object.keys(interactionConfig).forEach(configType => {
if (configType === 'tooltip') {
const fieldsToShow = modifiedConfig[configType].fieldsToShow;
if (!notNullorUndefined(fieldsToShow)) {
return {[this.key]: modifiedConfig};
}
Object.keys(fieldsToShow).forEach(key => {
fieldsToShow[key] = fieldsToShow[key].map(fieldData => {
if (!fieldData.name) {
return {
name: fieldData,
format: null
};
}
return fieldData;
});
});
}
return;
});
return {[this.key]: modifiedConfig};
}
}
export const filterPropsV0 = {
dataId: null,
id: null,
name: null,
type: null,
value: null,
enlarged: null
};
export class DimensionFieldSchema extends Schema {
save(field) {
return {
[this.key]: field ? this.savePropertiesOrApplySchema(field)[this.key] : null
};
}
load(field) {
return {[this.key]: field};
}
}
export class SplitMapsSchema extends Schema {
convertLayerSettings(accu, [key, value]) {
if (typeof value === 'boolean') {
return {
...accu,
[key]: value
};
} else if (value && typeof value === 'object' && value.isAvailable) {
return {
...accu,
[key]: Boolean(value.isVisible)
};
}
return accu;
}
load(splitMaps) {
// previous splitMaps Schema {layers: {layerId: {isVisible, isAvailable}}}
if (!Array.isArray(splitMaps) || !splitMaps.length) {
return {splitMaps: []};
}
return {
splitMaps: splitMaps.map(settings => ({
...settings,
layers: Object.entries(settings.layers || {}).reduce(this.convertLayerSettings, {})
}))
};
}
}
export const filterPropsV1 = {
...filterPropsV0,
plotType: null,
animationWindow: null,
yAxis: new DimensionFieldSchema({
version: VERSIONS.v1,
key: 'yAxis',
properties: {
name: null,
type: null
}
}),
// polygon filter properties
layerId: null,
speed: null
};
export const propertiesV0 = {
filters: new FilterSchemaV0({
version: VERSIONS.v0,
properties: filterPropsV0
}),
layers: new LayerSchemaV0({
version: VERSIONS.v0,
properties: layerPropsV0
}),
interactionConfig: new InteractionSchemaV0({
version: VERSIONS.v0,
properties: interactionPropsV0
}),
layerBlending: null
};
export const propertiesV1 = {
filters: new FilterSchemaV0({
version: VERSIONS.v1,
properties: filterPropsV1
}),
layers: new LayerSchemaV0({
version: VERSIONS.v1,
properties: layerPropsV1
}),
interactionConfig: new InteractionSchemaV1({
version: VERSIONS.v1,
properties: interactionPropsV1
}),
layerBlending: null,
splitMaps: new SplitMapsSchema({
key: 'splitMaps',
version: VERSIONS.v1
}),
animationConfig: new Schema({
version: VERSIONS.v1,
properties: {
currentTime: null,
speed: null
},
key: 'animationConfig'
})
};
export const visStateSchemaV0 = new Schema({
version: VERSIONS.v0,
properties: propertiesV0,
key: 'visState'
});
export const visStateSchemaV1 = new Schema({
version: VERSIONS.v1,
properties: propertiesV1,
key: 'visState'
});
export const visStateSchema = {
[VERSIONS.v0]: {
save: toSave => visStateSchemaV0.save(toSave),
load: toLoad => visStateSchemaV1.load(visStateSchemaV0.load(toLoad).visState)
},
[VERSIONS.v1]: visStateSchemaV1
};
// test load v0
export default visStateSchema; | the_stack |
import React, { FunctionComponent } from 'react';
import { unmountComponentAtNode, render, Switch, Route } from 'reactant-web';
// eslint-disable-next-line import/no-extraneous-dependencies
import { act } from 'react-dom/test-utils';
import {
injectable,
state,
action,
ViewModule,
useConnector,
subscribe,
createSharedApp,
spawn,
PortDetector,
createTransport,
Router,
mockPairTransports,
} from '..';
let serverContainer: Element;
let clientContainer: Element;
beforeEach(() => {
serverContainer = document.createElement('div');
document.body.appendChild(serverContainer);
clientContainer = document.createElement('div');
document.body.appendChild(clientContainer);
});
afterEach(() => {
unmountComponentAtNode(serverContainer);
serverContainer.remove();
unmountComponentAtNode(clientContainer);
clientContainer.remove();
});
describe('base', () => {
let onClientFn: jest.Mock<any, any>;
let subscribeOnClientFn: jest.Mock<any, any>;
let onServerFn: jest.Mock<any, any>;
let subscribeOnServerFn: jest.Mock<any, any>;
const Link: FunctionComponent<{
active: boolean;
onClick: () => any;
id?: string;
}> = ({ active, children, onClick, id }) => {
return (
<div
onClick={onClick}
style={{ color: active ? 'red' : 'black' }}
id={id}
>
{children}
</div>
);
};
@injectable({
name: 'counterView',
})
class CounterView extends ViewModule {
constructor(private portDetector: PortDetector) {
super();
this.portDetector.onClient(() => {
onClientFn?.();
return subscribe(this, () => {
subscribeOnClientFn?.();
});
});
this.portDetector.onServer(() => {
onServerFn?.();
return subscribe(this, () => {
subscribeOnServerFn?.();
});
});
}
name = 'counter';
path = '/counter';
@state
count = 0;
@action
increase() {
this.count += 1;
}
component(this: CounterView) {
const count = useConnector(() => this.count);
return (
<>
<div id="count">{count}</div>
<button
id="increase"
type="button"
onClick={() => spawn(this, 'increase', [])}
>
+
</button>
</>
);
}
}
@injectable({
name: 'appView',
})
class AppView extends ViewModule {
constructor(public counterView: CounterView, public router: Router) {
super();
}
async routerChange(path: string) {
await spawn(this.router, 'push', [path]);
}
component() {
const currentPath = useConnector(() => this.router.currentPath);
return (
<>
<ul>
<li>
<Link
active={currentPath === '/'}
onClick={() => this.routerChange('/')}
id="home"
>
Home
</Link>
</li>
<li>
<Link
active={currentPath === this.counterView.path}
onClick={() => this.routerChange(this.counterView.path)}
id={this.counterView.name}
>
{this.counterView.name}
</Link>
</li>
</ul>
<div id="content">
<Switch>
<Route exact path="/">
<h2>home</h2>
</Route>
<Route
path={this.counterView.path}
component={this.counterView.component}
/>
</Switch>
</div>
</>
);
}
}
test('base server/client port mode with router', async () => {
onClientFn = jest.fn();
subscribeOnClientFn = jest.fn();
onServerFn = jest.fn();
subscribeOnServerFn = jest.fn();
const transports = mockPairTransports();
const serverApp = await createSharedApp({
modules: [Router],
main: AppView,
render,
share: {
name: 'counter',
type: 'Base',
port: 'server',
transports: {
server: transports[0],
},
},
});
expect(onClientFn.mock.calls.length).toBe(0);
expect(subscribeOnClientFn.mock.calls.length).toBe(0);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(0);
act(() => {
serverApp.bootstrap(serverContainer);
});
await new Promise((resolve) => setTimeout(resolve));
expect(onClientFn.mock.calls.length).toBe(0);
expect(subscribeOnClientFn.mock.calls.length).toBe(0);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(1);
expect(serverContainer.querySelector('#content')?.textContent).toBe('home');
const clientApp = await createSharedApp({
modules: [Router],
main: AppView,
render,
share: {
name: 'counter',
type: 'Base',
port: 'client',
transports: {
client: transports[1],
},
},
});
expect(onClientFn.mock.calls.length).toBe(1);
expect(subscribeOnClientFn.mock.calls.length).toBe(0);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(1);
act(() => {
clientApp.bootstrap(clientContainer);
});
expect(onClientFn.mock.calls.length).toBe(1);
expect(subscribeOnClientFn.mock.calls.length).toBe(1);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(1);
expect(clientContainer.querySelector('#content')?.textContent).toBe('home');
act(() => {
serverContainer
.querySelector('#counter')!
.dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
await new Promise((resolve) => setTimeout(resolve));
expect(onClientFn.mock.calls.length).toBe(1);
expect(subscribeOnClientFn.mock.calls.length).toBe(5);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(2);
expect(serverContainer.querySelector('#content')?.textContent).toBe('0+');
// expect(clientContainer.querySelector('#content')?.textContent).toBe('0+');
act(() => {
clientContainer
.querySelector('#counter')!
.dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
await new Promise((resolve) => setTimeout(resolve));
expect(onClientFn.mock.calls.length).toBe(1);
expect(subscribeOnClientFn.mock.calls.length).toBe(7);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(3);
expect(serverContainer.querySelector('#content')?.textContent).toBe('0+');
expect(clientContainer.querySelector('#content')?.textContent).toBe('0+');
act(() => {
clientContainer
.querySelector('#home')!
.dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
expect(clientContainer.querySelector('#content')?.textContent).toBe('home');
});
});
describe('SharedWorker', () => {
let onClientFn: jest.Mock<any, any>;
let subscribeOnClientFn: jest.Mock<any, any>;
let onServerFn: jest.Mock<any, any>;
let subscribeOnServerFn: jest.Mock<any, any>;
const Link: FunctionComponent<{
active: boolean;
onClick: () => any;
id?: string;
}> = ({ active, children, onClick, id }) => {
return (
<div
onClick={onClick}
style={{ color: active ? 'red' : 'black' }}
id={id}
>
{children}
</div>
);
};
@injectable({
name: 'counterView',
})
class CounterView extends ViewModule {
constructor(private portDetector: PortDetector) {
super();
this.portDetector.onClient(() => {
onClientFn?.();
return subscribe(this, () => {
subscribeOnClientFn?.();
});
});
this.portDetector.onServer(() => {
onServerFn?.();
return subscribe(this, () => {
subscribeOnServerFn?.();
});
});
}
name = 'counter';
path = '/counter';
@state
count = 0;
@action
increase() {
this.count += 1;
}
component(this: CounterView) {
const count = useConnector(() => this.count);
return (
<>
<div id="count">{count}</div>
<button
id="increase"
type="button"
onClick={() => spawn(this, 'increase', [])}
>
+
</button>
</>
);
}
}
@injectable({
name: 'appView',
})
class AppView extends ViewModule {
constructor(public counterView: CounterView, public router: Router) {
super();
}
async routerChange(path: string) {
await spawn(this.router, 'push', [path]);
}
component() {
const currentPath = useConnector(() => this.router.currentPath);
return (
<>
<ul>
<li>
<Link
active={currentPath === '/'}
onClick={() => this.routerChange('/')}
id="home"
>
Home
</Link>
</li>
<li>
<Link
active={currentPath === this.counterView.path}
onClick={() => this.routerChange(this.counterView.path)}
id={this.counterView.name}
>
{this.counterView.name}
</Link>
</li>
</ul>
<div id="content">
<Switch>
<Route exact path="/">
<h2>home</h2>
</Route>
<Route
path={this.counterView.path}
component={this.counterView.component}
/>
</Switch>
</div>
</>
);
}
}
test('base server/client port mode with router in SharedWorker', async () => {
onClientFn = jest.fn();
subscribeOnClientFn = jest.fn();
onServerFn = jest.fn();
subscribeOnServerFn = jest.fn();
const transports = mockPairTransports();
const serverApp = await createSharedApp({
modules: [Router],
main: AppView,
render,
share: {
name: 'counter',
type: 'SharedWorker',
port: 'server',
transports: {
server: transports[0],
},
},
});
expect(onClientFn.mock.calls.length).toBe(0);
expect(subscribeOnClientFn.mock.calls.length).toBe(0);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(0);
await new Promise((resolve) => setTimeout(resolve));
expect(onClientFn.mock.calls.length).toBe(0);
expect(subscribeOnClientFn.mock.calls.length).toBe(0);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(0);
const clientApp = await createSharedApp({
modules: [Router],
main: AppView,
render,
share: {
name: 'counter',
type: 'SharedWorker',
port: 'client',
transports: {
client: transports[1],
},
},
});
expect(onClientFn.mock.calls.length).toBe(1);
expect(subscribeOnClientFn.mock.calls.length).toBe(0);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(0);
act(() => {
clientApp.bootstrap(clientContainer);
});
expect(onClientFn.mock.calls.length).toBe(1);
expect(subscribeOnClientFn.mock.calls.length).toBe(1);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(0);
expect(clientContainer.querySelector('#content')?.textContent).toBe('home');
await new Promise((resolve) => setTimeout(resolve));
expect(onClientFn.mock.calls.length).toBe(1);
expect(subscribeOnClientFn.mock.calls.length).toBe(1);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(0);
expect(clientContainer.querySelector('#content')?.textContent).toBe('home');
act(() => {
clientContainer
.querySelector('#counter')!
.dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
await new Promise((resolve) => setTimeout(resolve));
expect(onClientFn.mock.calls.length).toBe(1);
expect(subscribeOnClientFn.mock.calls.length).toBe(2);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(0);
expect(serverApp.instance.router.currentPath).toBe('/counter');
expect(clientContainer.querySelector('#content')?.textContent).toBe('0+');
act(() => {
clientContainer
.querySelector('#home')!
.dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
await new Promise((resolve) => setTimeout(resolve));
expect(serverApp.instance.router.currentPath).toBe('/');
expect(clientContainer.querySelector('#content')?.textContent).toBe('home');
});
});
describe('ServiceWorker', () => {
let onClientFn: jest.Mock<any, any>;
let subscribeOnClientFn: jest.Mock<any, any>;
let onServerFn: jest.Mock<any, any>;
let subscribeOnServerFn: jest.Mock<any, any>;
const Link: FunctionComponent<{
active: boolean;
onClick: () => any;
id?: string;
}> = ({ active, children, onClick, id }) => {
return (
<div
onClick={onClick}
style={{ color: active ? 'red' : 'black' }}
id={id}
>
{children}
</div>
);
};
@injectable({
name: 'counterView',
})
class CounterView extends ViewModule {
constructor(private portDetector: PortDetector) {
super();
this.portDetector.onClient(() => {
onClientFn?.();
return subscribe(this, () => {
subscribeOnClientFn?.();
});
});
this.portDetector.onServer(() => {
onServerFn?.();
return subscribe(this, () => {
subscribeOnServerFn?.();
});
});
}
name = 'counter';
path = '/counter';
@state
count = 0;
@action
increase() {
this.count += 1;
}
component(this: CounterView) {
const count = useConnector(() => this.count);
return (
<>
<div id="count">{count}</div>
<button
id="increase"
type="button"
onClick={() => spawn(this, 'increase', [])}
>
+
</button>
</>
);
}
}
@injectable({
name: 'appView',
})
class AppView extends ViewModule {
constructor(public counterView: CounterView, public router: Router) {
super();
}
async routerChange(path: string) {
await spawn(this.router, 'push', [path]);
}
component() {
const currentPath = useConnector(() => this.router.currentPath);
return (
<>
<ul>
<div id="replace" onClick={() => this.routerChange('/')}>
replace
</div>
<div id="go" onClick={() => this.router.go(-1)}>
go
</div>
<div id="goBack" onClick={() => this.router.goBack()}>
goBack
</div>
<div id="goForward" onClick={() => this.router.goForward()}>
goForward
</div>
<li>
<Link
active={currentPath === '/'}
onClick={() => this.routerChange('/')}
id="home"
>
Home
</Link>
</li>
<li>
<Link
active={currentPath === this.counterView.path}
onClick={() => this.routerChange(this.counterView.path)}
id={this.counterView.name}
>
{this.counterView.name}
</Link>
</li>
</ul>
<div id="content">
<Switch>
<Route exact path="/">
<h2>home</h2>
</Route>
<Route
path={this.counterView.path}
component={this.counterView.component}
/>
</Switch>
</div>
</>
);
}
}
test('base server/client port mode with router in ServiceWorker', async () => {
onClientFn = jest.fn();
subscribeOnClientFn = jest.fn();
onServerFn = jest.fn();
subscribeOnServerFn = jest.fn();
const transports = mockPairTransports();
const serverApp = await createSharedApp({
modules: [Router],
main: AppView,
render,
share: {
name: 'counter',
type: 'ServiceWorker',
port: 'server',
transports: {
server: transports[0],
},
},
});
expect(onClientFn.mock.calls.length).toBe(0);
expect(subscribeOnClientFn.mock.calls.length).toBe(0);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(0);
await new Promise((resolve) => setTimeout(resolve));
expect(onClientFn.mock.calls.length).toBe(0);
expect(subscribeOnClientFn.mock.calls.length).toBe(0);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(0);
const clientApp = await createSharedApp({
modules: [Router],
main: AppView,
render,
share: {
name: 'counter',
type: 'ServiceWorker',
port: 'client',
transports: {
client: transports[1],
},
},
});
expect(onClientFn.mock.calls.length).toBe(1);
expect(subscribeOnClientFn.mock.calls.length).toBe(0);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(0);
act(() => {
clientApp.bootstrap(clientContainer);
});
expect(onClientFn.mock.calls.length).toBe(1);
expect(subscribeOnClientFn.mock.calls.length).toBe(1);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(0);
expect(clientContainer.querySelector('#content')?.textContent).toBe('home');
await new Promise((resolve) => setTimeout(resolve));
expect(onClientFn.mock.calls.length).toBe(1);
expect(subscribeOnClientFn.mock.calls.length).toBe(1);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(0);
expect(clientContainer.querySelector('#content')?.textContent).toBe('home');
act(() => {
clientContainer
.querySelector('#counter')!
.dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
await new Promise((resolve) => setTimeout(resolve));
expect(onClientFn.mock.calls.length).toBe(1);
expect(subscribeOnClientFn.mock.calls.length).toBe(2);
expect(onServerFn.mock.calls.length).toBe(1);
expect(subscribeOnServerFn.mock.calls.length).toBe(0);
expect(serverApp.instance.router.currentPath).toBe('/counter');
expect(clientContainer.querySelector('#content')?.textContent).toBe('0+');
act(() => {
clientContainer
.querySelector('#replace')!
.dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
await new Promise((resolve) => setTimeout(resolve));
expect(serverApp.instance.router.currentPath).toBe('/');
expect(clientContainer.querySelector('#content')?.textContent).toBe('home');
act(() => {
clientContainer
.querySelector('#counter')!
.dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
await new Promise((resolve) => setTimeout(resolve));
expect(serverApp.instance.router.currentPath).toBe('/counter');
expect(clientContainer.querySelector('#content')?.textContent).toBe('0+');
act(() => {
clientContainer
.querySelector('#goBack')!
.dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
await new Promise((resolve) => setTimeout(resolve));
// todo: mock
// expect(serverApp.instance.router.currentPath).toBe('/counter');
expect(clientContainer.querySelector('#content')?.textContent).toBe('0+');
act(() => {
clientContainer
.querySelector('#goForward')!
.dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
await new Promise((resolve) => setTimeout(resolve));
// todo: mock
// expect(serverApp.instance.router.currentPath).toBe('/');
expect(clientContainer.querySelector('#content')?.textContent).toBe('home');
act(() => {
clientContainer
.querySelector('#go')!
.dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
await new Promise((resolve) => setTimeout(resolve));
// todo: mock
// expect(serverApp.instance.router.currentPath).toBe('/counter');
expect(clientContainer.querySelector('#content')?.textContent).toBe('0+');
});
}); | the_stack |
Copyright (c) 2020 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
* @packageDocumentation
* @hidden
*/
import { BulletSharedBody } from './bullet-shared-body';
import { BulletRigidBody } from './bullet-rigid-body';
import { BulletShape } from './shapes/bullet-shape';
import { ArrayCollisionMatrix } from '../utils/array-collision-matrix';
import { TupleDictionary } from '../utils/tuple-dictionary';
import { TriggerEventObject, CollisionEventObject, CC_V3_0, CC_V3_1, BulletCache } from './bullet-cache';
import { bullet2CocosVec3, cocos2BulletVec3 } from './bullet-utils';
import { Ray } from '../../core/geometry';
import { IRaycastOptions, IPhysicsWorld } from '../spec/i-physics-world';
import { PhysicsRayResult, PhysicsMaterial } from '../framework';
import { error, Node, RecyclePool, Vec3 } from '../../core';
import { IVec3Like } from '../../core/math/type-define';
import { BulletContactData } from './bullet-contact-data';
import { BulletConstraint } from './constraints/bullet-constraint';
import { fastRemoveAt } from '../../core/utils/array';
import { bt } from './instantiated';
const contactsPool: BulletContactData[] = [];
const v3_0 = CC_V3_0;
const v3_1 = CC_V3_1;
export class BulletWorld implements IPhysicsWorld {
setDefaultMaterial (v: PhysicsMaterial) { }
setAllowSleep (v: boolean) {
bt.ccDiscreteDynamicsWorld_setAllowSleep(this._world, v);
}
setGravity (gravity: IVec3Like) {
bt.DynamicsWorld_setGravity(this._world, cocos2BulletVec3(BulletCache.instance.BT_V3_0, gravity));
}
updateNeedEmitEvents (v: boolean) {
if (!this.ghosts) return; // return if destroyed
if (v) {
this._needEmitEvents = true;
} else {
this._needEmitEvents = false;
for (let i = 0; i < this.ghosts.length; i++) {
const ghost = this.ghosts[i];
const shapes = ghost.ghostStruct.wrappedShapes;
for (let j = 0; j < shapes.length; j++) {
const collider = shapes[j].collider;
if (collider.needCollisionEvent || collider.needTriggerEvent) {
this._needEmitEvents = true;
return;
}
}
}
for (let i = 0; i < this.bodies.length; i++) {
const body = this.bodies[i];
const shapes = body.bodyStruct.wrappedShapes;
for (let j = 0; j < shapes.length; j++) {
const collider = shapes[j].collider;
if (collider.needCollisionEvent || collider.needTriggerEvent) {
this._needEmitEvents = true;
return;
}
}
}
}
}
get impl () {
return this._world;
}
private readonly _world: Bullet.ptr;
private readonly _broadphase: Bullet.ptr;
private readonly _solver: Bullet.ptr;
private readonly _dispatcher: Bullet.ptr;
private _needEmitEvents = false;
private _needSyncAfterEvents = false;
readonly bodies: BulletSharedBody[] = [];
readonly ghosts: BulletSharedBody[] = [];
readonly constraints: BulletConstraint[] = [];
readonly triggerArrayMat = new ArrayCollisionMatrix();
readonly collisionArrayMat = new ArrayCollisionMatrix();
readonly contactsDic = new TupleDictionary();
readonly oldContactsDic = new TupleDictionary();
constructor () {
this._broadphase = bt.DbvtBroadphase_new();
this._dispatcher = bt.CollisionDispatcher_new();
this._solver = bt.SequentialImpulseConstraintSolver_new();
this._world = bt.ccDiscreteDynamicsWorld_new(this._dispatcher, this._broadphase, this._solver);
}
destroy (): void {
if (this.constraints.length || this.bodies.length) error('You should destroy all physics component first.');
bt.CollisionWorld_del(this._world);
bt.DbvtBroadphase_del(this._broadphase);
bt.CollisionDispatcher_del(this._dispatcher);
bt.SequentialImpulseConstraintSolver_del(this._solver);
(this as any).bodies = null;
(this as any).ghosts = null;
(this as any).constraints = null;
(this as any).triggerArrayMat = null;
(this as any).collisionArrayMat = null;
(this as any).contactsDic = null;
(this as any).oldContactsDic = null;
contactsPool.length = 0;
}
step (deltaTime: number, timeSinceLastCalled?: number, maxSubStep = 0) {
if (!this.bodies.length && !this.ghosts.length) return;
if (timeSinceLastCalled === undefined) timeSinceLastCalled = deltaTime;
bt.DynamicsWorld_stepSimulation(this._world, timeSinceLastCalled, maxSubStep, deltaTime);
}
syncSceneToPhysics (): void {
// Use reverse traversal order, because update dirty will mess up the ghosts or bodyies array.
for (let i = this.ghosts.length - 1; i >= 0; i--) {
const ghost = this.ghosts[i]; // Use temporary object, same reason as above
ghost.updateDirty();
ghost.syncSceneToGhost();
}
for (let i = this.bodies.length - 1; i >= 0; i--) {
const body = this.bodies[i];
body.updateDirty();
body.syncSceneToPhysics();
}
}
syncAfterEvents (): void {
if (!this._needSyncAfterEvents) return;
this.syncSceneToPhysics();
}
raycast (worldRay: Ray, options: IRaycastOptions, pool: RecyclePool<PhysicsRayResult>, results: PhysicsRayResult[]): boolean {
worldRay.computeHit(v3_0, options.maxDistance);
const to = cocos2BulletVec3(BulletCache.instance.BT_V3_0, v3_0);
const from = cocos2BulletVec3(BulletCache.instance.BT_V3_1, worldRay.o);
const allHitsCB = bt.ccAllRayCallback_static();
bt.ccAllRayCallback_reset(allHitsCB, from, to, options.mask, options.queryTrigger);
bt.CollisionWorld_rayTest(this._world, from, to, allHitsCB);
if (bt.RayCallback_hasHit(allHitsCB)) {
const posArray = bt.ccAllRayCallback_getHitPointWorld(allHitsCB);
const normalArray = bt.ccAllRayCallback_getHitNormalWorld(allHitsCB);
const ptrArray = bt.ccAllRayCallback_getCollisionShapePtrs(allHitsCB);
for (let i = 0, n = bt.int_array_size(ptrArray); i < n; i++) {
bullet2CocosVec3(v3_0, bt.Vec3_array_at(posArray, i));
bullet2CocosVec3(v3_1, bt.Vec3_array_at(normalArray, i));
const shape = BulletCache.getWrapper<BulletShape>(bt.int_array_at(ptrArray, i), BulletShape.TYPE);
const r = pool.add(); results.push(r);
r._assign(v3_0, Vec3.distance(worldRay.o, v3_0), shape.collider, v3_1);
}
return true;
}
return false;
}
raycastClosest (worldRay: Ray, options: IRaycastOptions, result: PhysicsRayResult): boolean {
worldRay.computeHit(v3_0, options.maxDistance);
const to = cocos2BulletVec3(BulletCache.instance.BT_V3_0, v3_0);
const from = cocos2BulletVec3(BulletCache.instance.BT_V3_1, worldRay.o);
const closeHitCB = bt.ccClosestRayCallback_static();
bt.ccClosestRayCallback_reset(closeHitCB, from, to, options.mask, options.queryTrigger);
bt.CollisionWorld_rayTest(this._world, from, to, closeHitCB);
if (bt.RayCallback_hasHit(closeHitCB)) {
bullet2CocosVec3(v3_0, bt.ccClosestRayCallback_getHitPointWorld(closeHitCB));
bullet2CocosVec3(v3_1, bt.ccClosestRayCallback_getHitNormalWorld(closeHitCB));
const shape = BulletCache.getWrapper<BulletShape>(bt.ccClosestRayCallback_getCollisionShapePtr(closeHitCB), BulletShape.TYPE);
result._assign(v3_0, Vec3.distance(worldRay.o, v3_0), shape.collider, v3_1);
return true;
}
return false;
}
getSharedBody (node: Node, wrappedBody?: BulletRigidBody) {
return BulletSharedBody.getSharedBody(node, this, wrappedBody);
}
addSharedBody (sharedBody: BulletSharedBody) {
const i = this.bodies.indexOf(sharedBody);
if (i < 0) {
this.bodies.push(sharedBody);
bt.DynamicsWorld_addRigidBody(this._world, sharedBody.body, sharedBody.collisionFilterGroup, sharedBody.collisionFilterMask);
}
}
removeSharedBody (sharedBody: BulletSharedBody) {
const i = this.bodies.indexOf(sharedBody);
if (i >= 0) {
fastRemoveAt(this.bodies, i);
bt.DynamicsWorld_removeRigidBody(this._world, sharedBody.body);
}
}
addGhostObject (sharedBody: BulletSharedBody) {
const i = this.ghosts.indexOf(sharedBody);
if (i < 0) {
this.ghosts.push(sharedBody);
bt.CollisionWorld_addCollisionObject(this._world, sharedBody.ghost, sharedBody.collisionFilterGroup, sharedBody.collisionFilterMask);
}
}
removeGhostObject (sharedBody: BulletSharedBody) {
const i = this.ghosts.indexOf(sharedBody);
if (i >= 0) {
fastRemoveAt(this.ghosts, i);
bt.CollisionWorld_removeCollisionObject(this._world, sharedBody.ghost);
}
}
addConstraint (constraint: BulletConstraint) {
const i = this.constraints.indexOf(constraint);
if (i < 0) {
this.constraints.push(constraint);
bt.DynamicsWorld_addConstraint(this.impl, constraint.impl, !constraint.constraint.enableCollision);
constraint.index = i;
}
}
removeConstraint (constraint: BulletConstraint) {
const i = this.constraints.indexOf(constraint);
if (i >= 0) {
this.constraints.splice(i, 1);
bt.DynamicsWorld_removeConstraint(this.impl, constraint.impl);
constraint.index = -1;
}
}
emitEvents () {
this._needSyncAfterEvents = false;
if (!this._needEmitEvents) return;
this.gatherConatactData();
// is enter or stay
let dicL = this.contactsDic.getLength();
while (dicL--) {
contactsPool.push.apply(contactsPool, CollisionEventObject.contacts as BulletContactData[]);
CollisionEventObject.contacts.length = 0;
const key = this.contactsDic.getKeyByIndex(dicL);
const data = this.contactsDic.getDataByKey<any>(key);
const shape0: BulletShape = data.shape0;
const shape1: BulletShape = data.shape1;
this.oldContactsDic.set(shape0.id, shape1.id, data);
const collider0 = shape0.collider;
const collider1 = shape1.collider;
if (collider0 && collider1) {
const isTrigger = collider0.isTrigger || collider1.isTrigger;
if (isTrigger) {
if (this.triggerArrayMat.get(shape0.id, shape1.id)) {
TriggerEventObject.type = 'onTriggerStay';
} else {
TriggerEventObject.type = 'onTriggerEnter';
this.triggerArrayMat.set(shape0.id, shape1.id, true);
}
TriggerEventObject.impl = data.impl;
TriggerEventObject.selfCollider = collider0;
TriggerEventObject.otherCollider = collider1;
collider0.emit(TriggerEventObject.type, TriggerEventObject);
TriggerEventObject.selfCollider = collider1;
TriggerEventObject.otherCollider = collider0;
collider1.emit(TriggerEventObject.type, TriggerEventObject);
this._needSyncAfterEvents = true;
} else {
const body0 = collider0.attachedRigidBody;
const body1 = collider1.attachedRigidBody;
if (body0 && body1) {
if (body0.isSleeping && body1.isSleeping) continue;
} else if (!body0 && body1) {
if (body1.isSleeping) continue;
} else if (!body1 && body0) {
if (body0.isSleeping) continue;
}
if (this.collisionArrayMat.get(shape0.id, shape1.id)) {
CollisionEventObject.type = 'onCollisionStay';
} else {
CollisionEventObject.type = 'onCollisionEnter';
this.collisionArrayMat.set(shape0.id, shape1.id, true);
}
for (let i = 0; i < data.contacts.length; i++) {
const cq = data.contacts[i];
if (contactsPool.length > 0) {
const c = contactsPool.pop(); c!.impl = cq;
CollisionEventObject.contacts.push(c!);
} else {
const c = new BulletContactData(CollisionEventObject); c.impl = cq;
CollisionEventObject.contacts.push(c);
}
}
CollisionEventObject.impl = data.impl;
CollisionEventObject.selfCollider = collider0;
CollisionEventObject.otherCollider = collider1;
collider0.emit(CollisionEventObject.type, CollisionEventObject);
CollisionEventObject.selfCollider = collider1;
CollisionEventObject.otherCollider = collider0;
collider1.emit(CollisionEventObject.type, CollisionEventObject);
this._needSyncAfterEvents = true;
}
if (this.oldContactsDic.get(shape0.id, shape1.id) == null) {
this.oldContactsDic.set(shape0.id, shape1.id, data);
}
}
}
// is exit
let oldDicL = this.oldContactsDic.getLength();
while (oldDicL--) {
const key = this.oldContactsDic.getKeyByIndex(oldDicL);
const data = this.oldContactsDic.getDataByKey<any>(key);
const shape0: BulletShape = data.shape0;
const shape1: BulletShape = data.shape1;
const collider0 = shape0.collider;
const collider1 = shape1.collider;
if (collider0 && collider1) {
const isTrigger = collider0.isTrigger || collider1.isTrigger;
if (this.contactsDic.getDataByKey(key) == null) {
if (isTrigger) {
if (this.triggerArrayMat.get(shape0.id, shape1.id)) {
TriggerEventObject.type = 'onTriggerExit';
TriggerEventObject.selfCollider = collider0;
TriggerEventObject.otherCollider = collider1;
collider0.emit(TriggerEventObject.type, TriggerEventObject);
TriggerEventObject.selfCollider = collider1;
TriggerEventObject.otherCollider = collider0;
collider1.emit(TriggerEventObject.type, TriggerEventObject);
this.triggerArrayMat.set(shape0.id, shape1.id, false);
this.oldContactsDic.set(shape0.id, shape1.id, null);
this._needSyncAfterEvents = true;
}
} else if (this.collisionArrayMat.get(shape0.id, shape1.id)) {
contactsPool.push.apply(contactsPool, CollisionEventObject.contacts as BulletContactData[]);
CollisionEventObject.contacts.length = 0;
CollisionEventObject.type = 'onCollisionExit';
CollisionEventObject.selfCollider = collider0;
CollisionEventObject.otherCollider = collider1;
collider0.emit(CollisionEventObject.type, CollisionEventObject);
CollisionEventObject.selfCollider = collider1;
CollisionEventObject.otherCollider = collider0;
collider1.emit(CollisionEventObject.type, CollisionEventObject);
this.collisionArrayMat.set(shape0.id, shape1.id, false);
this.oldContactsDic.set(shape0.id, shape1.id, null);
this._needSyncAfterEvents = true;
}
}
}
}
this.contactsDic.reset();
}
gatherConatactData () {
const numManifolds = bt.Dispatcher_getNumManifolds(this._dispatcher);
for (let i = 0; i < numManifolds; i++) {
const manifold = bt.Dispatcher_getManifoldByIndexInternal(this._dispatcher, i);
const numContacts = bt.PersistentManifold_getNumContacts(manifold);
for (let j = 0; j < numContacts; j++) {
const manifoldPoint = bt.PersistentManifold_getContactPoint(manifold, j);
const s0 = bt.ManifoldPoint_getShape0(manifoldPoint);
const s1 = bt.ManifoldPoint_getShape1(manifoldPoint);
const shape0: BulletShape = BulletCache.getWrapper(s0, BulletShape.TYPE);
const shape1: BulletShape = BulletCache.getWrapper(s1, BulletShape.TYPE);
if (shape0.collider.needTriggerEvent || shape1.collider.needTriggerEvent
|| shape0.collider.needCollisionEvent || shape1.collider.needCollisionEvent
) {
// current contact
let item = this.contactsDic.get<any>(shape0.id, shape1.id);
if (!item) {
item = this.contactsDic.set(shape0.id, shape1.id,
{ shape0, shape1, contacts: [], impl: manifold });
}
item.contacts.push(manifoldPoint);
}
}
}
}
} | the_stack |
* @module OrbitGT
*/
//package orbitgt.pointcloud.render;
type int8 = number;
type int16 = number;
type int32 = number;
type float32 = number;
type float64 = number;
import { Bounds } from "../../spatial/geom/Bounds";
import { Transform } from "../../spatial/geom/Transform";
import { AList } from "../../system/collection/AList";
import { StringMap } from "../../system/collection/StringMap";
import { ALong } from "../../system/runtime/ALong";
import { ASystem } from "../../system/runtime/ASystem";
import { Message } from "../../system/runtime/Message";
import { ContentLoader } from "../../system/storage/ContentLoader";
import { BlockIndex } from "../model/BlockIndex";
import { Grid } from "../model/Grid";
import { PointCloudReader } from "../model/PointCloudReader";
import { PointData } from "../model/PointData";
import { TileIndex } from "../model/TileIndex";
import { Block } from "./Block";
import { FrameData } from "./FrameData";
import { Level } from "./Level";
import { ViewTree } from "./ViewTree";
/**
* Class DataManager manages the (shared) data model part of the rendering in multiple layers (see the CLOUD-461 issue).
*
* @version 1.0 December 2017
*/
/** @internal */
export class DataManager {
/** The name of this module */
private static readonly MODULE: string = "DataManager";
/** The maximum size of a single file-content request */
private static readonly MAX_FILE_CONTENT_SIZE: int32 = 128 * 1024;
/** The expire time to unload unused point data (seconds) */
private static readonly POINT_DATA_EXIRE_TIME: float64 = 5 * 60.0;
/** The reader of the pointcloud */
private _pointCloudReader: PointCloudReader;
/*** The CRS of the pointcloud */
private _pointCloudCRS: string;
/** The data format to read */
private _dataFormat: int32;
/** The spatial index */
private _fileTileIndex: ViewTree;
/** The data pool */
private _dataPool: StringMap<PointData>;
/** The set of levels we requested (index) */
private _levelsLoading: StringMap<Level>;
/** The set of levels we received (index) */
private _levelsLoaded: StringMap<Level>;
/** The set of blocks we requested (key) */
private _blocksLoading: StringMap<BlockIndex>;
/** The set of blocks we received (key) */
private _blocksLoaded: StringMap<BlockIndex>;
/** The set of tiles we requested (key) */
private _tilesLoading: StringMap<TileIndex>;
/** The set of tiles we received (key) */
private _tilesLoaded: StringMap<TileIndex>;
/** Is new data being loaded? */
private _loadingData: boolean;
/** The time when the data loading stopped */
private _loadedDataTime: float64;
/** The total size of data that has been loaded */
private _dataLoadSize: ALong;
/** The last garbage collection time */
private _lastGarbageCollectTime: float64;
/**
* Create a new data model (to be shared between different views).
* @param pointCloudReader the reader of the pointcloud file.
* @param pointCloudCRS the CRS of the point cloud.
* @param dataFormat the requested data format to load point data (PointDataRaw.TYPE for example).
*/
public constructor(pointCloudReader: PointCloudReader, pointCloudCRS: string, dataFormat: int32) {
/* Store the parameters */
this._pointCloudReader = pointCloudReader;
this._pointCloudCRS = pointCloudCRS;
this._dataFormat = dataFormat;
/* Initialize */
if (this._pointCloudCRS == null) this._pointCloudCRS = this._pointCloudReader.getFileCRS();
/* Clear */
this._fileTileIndex = this.createSpatialIndex();
this._dataPool = new StringMap<PointData>();
this._levelsLoading = new StringMap<Level>();
this._levelsLoaded = new StringMap<Level>();
this._blocksLoading = new StringMap<BlockIndex>();
this._blocksLoaded = new StringMap<BlockIndex>();
this._tilesLoading = new StringMap<TileIndex>();
this._tilesLoaded = new StringMap<TileIndex>();
this._loadingData = false;
this._loadedDataTime = 0.0;
this._dataLoadSize = ALong.ZERO;
this._lastGarbageCollectTime = 0.0;
/* Log */
Message.print(DataManager.MODULE, "Pointcloud CRS is " + this._pointCloudCRS);
}
/**
* Close the data model.
*/
public close(): void {
if (this._pointCloudReader != null) {
this._pointCloudReader.close();
this._pointCloudReader = null;
}
this._fileTileIndex = null;
this._dataPool.clear();
this._levelsLoading.clear();
this._levelsLoaded.clear();
this._blocksLoading.clear();
this._blocksLoaded.clear();
this._tilesLoading.clear();
this._tilesLoaded.clear();
}
/**
* Create a spatial index of a pointcloud.
* @return the spatial index.
*/
private createSpatialIndex(): ViewTree {
/* Create the levels */
Message.print(DataManager.MODULE, "Creating pointcloud spatial index");
let levels: Array<Level> = new Array<Level>(this._pointCloudReader.getLevelCount());
for (let i: number = 0; i < levels.length; i++) {
/* Get the grids */
let blockGrid: Grid = this._pointCloudReader.getLevelBlockGrid(i);
let tileGrid: Grid = this._pointCloudReader.getLevelTileGrid(i);
/* Get the blocks */
let blockIndexes: Array<BlockIndex> = this._pointCloudReader.peekBlockIndexes(i);
let blockList: Array<Block> = new Array<Block>(blockIndexes.length);
for (let j: number = 0; j < blockList.length; j++) blockList[j] = new Block(blockIndexes[j]);
/* Create the level */
levels[i] = new Level(i, blockGrid, tileGrid, blockList);
Message.print(DataManager.MODULE, "Level " + i + " has " + blockList.length + " blocks");
}
/* Get the data bounds */
let dataBounds: Bounds = this._pointCloudReader.getFileBounds();
Message.print(DataManager.MODULE, "The data bounds are " + dataBounds);
/* Return a new spatial index */
return new ViewTree(this, levels, dataBounds);
}
/**
* Get the pointcloud reader.
* @return the pointcloud reader.
*/
public getPointCloudReader(): PointCloudReader {
return this._pointCloudReader;
}
/**
* Get the pointcloud CRS.
* @return the pointcloud CRS.
*/
public getPointCloudCRS(): string {
return this._pointCloudCRS;
}
/**
* Get the bounds of the data.
* @return the bounds of the data.
*/
public getPointCloudBounds(): Bounds {
return this._pointCloudReader.getFileBounds();
}
/**
* Get the spatial index.
* @return the spatial index.
*/
public getViewTree(): ViewTree {
return this._fileTileIndex;
}
/**
* Check if a tile has been loaded to the data pool.
* @param tileIndex the index of the tile.
* @return the point data if loaded, null otherwise.
*/
public isTileLoaded(tileIndex: TileIndex): PointData {
return this._dataPool.get(tileIndex.key);
}
/**
* Is the model loading data?
* @return true when loading data.
*/
public isLoadingData(): boolean {
return this._loadingData;
}
/**
* Get the size of the loaded data.
* @return the size of the loaded data.
*/
public getDataLoadSize(): ALong {
return this._dataLoadSize;
}
/**
* Filter the list of blocks and tiles that should be loaded.
* @param levelsToLoad the list of levels to load.
* @param blocksToLoad the list of blocks to load.
* @param tilesToLoad the list of tiles to load.
* @param levelList the filtered list of levels to load.
* @param blockList the filtered list of blocks to load.
* @param tileList the filtered list of tiles to load.
*/
public filterLoadList(levelsToLoad: AList<Level>, blocksToLoad: AList<BlockIndex>, tilesToLoad: AList<TileIndex>, levelList: AList<Level>, blockList: AList<BlockIndex>, tileList: AList<TileIndex>): void {
/* Filter the levels to load */
for (let i: number = 0; i < levelsToLoad.size(); i++) {
/* Do not request the same level twice */
let level: Level = levelsToLoad.get(i);
if (this._levelsLoading.contains(level.getKey())) continue;
if (this._levelsLoaded.contains(level.getKey())) continue;
/* Add the level */
levelList.add(level);
}
levelsToLoad.clear();
/* Filter the blocks to load */
for (let i: number = 0; i < blocksToLoad.size(); i++) {
/* Do not request the same block twice */
let blockIndex: BlockIndex = blocksToLoad.get(i);
if (this._blocksLoading.contains(blockIndex.key)) continue;
if (this._blocksLoaded.contains(blockIndex.key)) continue;
/* Add the block */
blockList.add(blockIndex);
}
blocksToLoad.clear();
/* Filter the tiles to load */
for (let i: number = 0; i < tilesToLoad.size(); i++) {
/* Do not request the same tile twice */
let tileIndex: TileIndex = tilesToLoad.get(i);
if (this._tilesLoading.contains(tileIndex.key)) continue;
if (this._tilesLoaded.contains(tileIndex.key)) continue;
/* Add the tile */
tileList.add(tileIndex);
}
tilesToLoad.clear();
}
/**
* Load blocks and tiles.
* @param layer the layer requesting the load.
* @param levelList the filtered list of levels to load.
* @param blockList the filtered list of blocks to load.
* @param tileList the filtered list of tiles to load.
* @return the data model.
*/
public async loadData(frameData: FrameData): Promise<FrameData> {
/* No data to load? */
if (frameData.hasMissingData() == false) return frameData;
/* Do not make overlapping load requests */
if (this._loadingData) return frameData;
this._loadingData = true;
/* Log */
let levelList: AList<Level> = frameData.levelsToLoad;
let blockList: AList<BlockIndex> = frameData.blocksToLoad;
let tileList: AList<TileIndex> = frameData.tilesToLoad;
// Message.print(MODULE,"Loading "+levelList.size()+" levels, "+blockList.size()+" blocks and "+tileList.size()+" tiles");
// Message.print(MODULE,"Already loaded "+this._blocksLoaded.size()+" blocks");
// Message.print(MODULE,"Already loading "+this._blocksLoading.size()+" blocks");
// Message.print(MODULE,"Already loaded "+this._tilesLoaded.size()+" tiles");
// Message.print(MODULE,"Already loading "+this._tilesLoading.size()+" tiles");
/* Define the content we are going to need */
let loadTime: float64 = ASystem.time();
let fileContents: ContentLoader = new ContentLoader(this._pointCloudReader.getFileStorage(), this._pointCloudReader.getFileName());
/* Prepare the loading of the levels */
for (let i: number = 0; i < levelList.size(); i++) {
/* Prepare to load the block */
let level: Level = levelList.get(i);
this._levelsLoading.set(level.getKey(), level);
this._pointCloudReader.readBlockIndexes(level.getIndex(), fileContents);
Message.print(DataManager.MODULE, "Loading level " + level.getIndex());
}
/* Prepare the loading of the blocks */
for (let i: number = 0; i < blockList.size(); i++) {
/* Prepare to load the block */
let blockIndex: BlockIndex = blockList.get(i);
this._blocksLoading.set(blockIndex.key, blockIndex);
this._pointCloudReader.readTileIndexes(blockIndex, fileContents);
}
/* Prepare the loading of the tiles */
let loadTileCount: int32 = 0;
for (let i: number = 0; i < tileList.size(); i++) {
/* Prepare to load the tile */
let tileIndex: TileIndex = tileList.get(i);
this._tilesLoading.set(tileIndex.key, tileIndex);
this._pointCloudReader.readPointData(tileIndex, this._dataFormat, loadTime, fileContents);
loadTileCount++;
/* Do not load too many tiles at once */
if (fileContents.getTotalRequestSize() > DataManager.MAX_FILE_CONTENT_SIZE) {
/* Stop loading tiles */
Message.print(DataManager.MODULE, "Limited pointcloud content load request to " + fileContents.getTotalRequestSize() + " bytes");
break;
}
}
/* Log */
Message.print(DataManager.MODULE, "Loading of " + blockList.size() + " blocks, " + loadTileCount + "/" + tileList.size() + " tiles, " + fileContents.getTotalRequestSize() + " bytes");
/* Load the data */
this._dataLoadSize = this._dataLoadSize.addInt(fileContents.getTotalRequestSize());
fileContents = await fileContents.load();
//Message.print(MODULE,"Creating "+blockList.size()+" blocks and "+tileList.size()+" tiles");
/* Load the levels */
for (let i: number = 0; i < levelList.size(); i++) {
/* Load the block list */
let level: Level = levelList.get(i);
this._levelsLoaded.set(level.getKey(), level);
this._levelsLoading.remove(level.getKey());
let blockIndexes: Array<BlockIndex> = this._pointCloudReader.readBlockIndexes(level.getIndex(), fileContents);
/* Add the blocks */
this._fileTileIndex.setLevelBlocks(level, blockIndexes);
}
/* Load the blocks */
for (let i: number = 0; i < blockList.size(); i++) {
/* Load the block */
let blockIndex: BlockIndex = blockList.get(i);
this._blocksLoaded.set(blockIndex.key, blockIndex);
this._blocksLoading.remove(blockIndex.key);
let tileIndexes: Array<TileIndex> = this._pointCloudReader.readTileIndexes(blockIndex, fileContents);
/* Add the block */
this._fileTileIndex.setBlockTiles(blockIndex, tileIndexes);
}
/* Load the tiles */
let newTiles: AList<TileIndex> = new AList<TileIndex>();
for (let i: number = 0; i < loadTileCount; i++) {
/* Get the next tile */
let tileIndex: TileIndex = tileList.get(i);
newTiles.add(tileIndex);
/* Load the tile */
this._tilesLoaded.set(tileIndex.key, tileIndex);
this._tilesLoading.remove(tileIndex.key);
let pointData: PointData = this._pointCloudReader.readPointData(tileIndex, this._dataFormat, loadTime, fileContents);
/* Add the tile */
this._dataPool.set(tileIndex.key, pointData);
}
/* We stopped loading */
this._loadingData = false;
this._loadedDataTime = ASystem.time();
/* Log */
Message.print(DataManager.MODULE, "Created " + blockList.size() + " blocks and " + loadTileCount + " tiles");
/* Return the frame data */
return frameData;
}
/**
* Do a garbage collect (this method can be called often, it throttles itself to once per minute).
* @param time the current time.
*/
public doGarbageCollect(time: float64): void {
/* First call? */
if (this._lastGarbageCollectTime == 0.0) this._lastGarbageCollectTime = time;
/* Throttle to one per minute */
if (time < this._lastGarbageCollectTime + 60.0) return;
this._lastGarbageCollectTime = time;
/* Define the expire time */
let expireTime: float64 = (time - DataManager.POINT_DATA_EXIRE_TIME);
/* Check all loaded tiles */
let dropCount: int32 = 0;
let dataKeys: AList<string> = this._dataPool.keys();
for (let i: number = 0; i < dataKeys.size(); i++) {
/* Get the next tile */
let tileKey: string = dataKeys.get(i);
let pointData: PointData = this._dataPool.get(tileKey);
/* Expired? */
if (pointData.tileIndex.accessTime < expireTime) {
this._dataPool.remove(tileKey);
this._tilesLoaded.remove(tileKey);
dropCount++;
}
}
/* Log? */
if (dropCount > 0) Message.print(DataManager.MODULE, "Dropped the point data of " + dropCount + " tiles");
}
} | the_stack |
'use strict'
import * as React from 'react-native';
import RNTSExample from '../RNTSExample'
import RNTSExampleModule from '../RNTSExampleModule'
const {
StyleSheet,
Text,
View,
} = React
const styles = StyleSheet.create(
{
backgroundColorText: {
left: 5,
backgroundColor: 'rgba(100, 100, 100, 0.3)'
},
entity: {
fontWeight: '500',
color: '#527fe4',
},
}
)
class Entity extends React.Component<any,any> {
render() {
return (
<Text style={styles.entity}>
{this.props.children}
</Text>
)
}
}
interface AttrTogglerState {
fontWeight?: string
fontSize?: number
}
class AttributeToggler extends React.Component<any, AttrTogglerState> {
componentWillMount() {
this.setState(
{
fontWeight: '500',
fontSize: 15
}
)
}
private increaseSize = (): void => {
this.setState( {
fontSize: this.state.fontSize + 1
} )
}
render() {
const curStyle: React.TextStyle = { fontSize: this.state.fontSize }
return (
<Text>
<Text style={curStyle}>
Tap the controls below to change attributes.
</Text>
<Text>
See how it will even work on{' '}
<Text style={curStyle}>
this nested text
</Text>
<Text onPress={this.increaseSize}>
{'>> Increase Size <<'}
</Text>
</Text>
</Text>
)
}
}
export default {
title: '<Text>',
description: 'Base component for rendering styled text.',
displayName: 'TextExample',
examples: [
{
title: 'Wrap',
render: function () {
return (
<Text>
The text should wrap if it goes on multiple lines. See, this is going to
the next line.
</Text>
)
},
},
{
title: 'Padding',
render: function () {
return (
<Text style={{padding: 10}}>
This text is indented by 10px padding on all sides.
</Text>
)
},
},
{
title: 'Font Family',
render: function () {
return (
<View>
<Text style={{fontFamily: 'Cochin'}}>
Cochin
</Text>
<Text style={{fontFamily: 'Cochin', fontWeight: 'bold'}}>
Cochin bold
</Text>
<Text style={{fontFamily: 'Helvetica'}}>
Helvetica
</Text>
<Text style={{fontFamily: 'Helvetica', fontWeight: 'bold'}}>
Helvetica bold
</Text>
<Text style={{fontFamily: 'Verdana'}}>
Verdana
</Text>
<Text style={{fontFamily: 'Verdana', fontWeight: 'bold'}}>
Verdana bold
</Text>
</View>
)
},
},
{
title: 'Font Size',
render: function () {
return (
<View>
<Text style={{fontSize: 23}}>
Size 23
</Text>
<Text style={{fontSize: 8}}>
Size 8
</Text>
</View>
)
},
},
{
title: 'Color',
render: function () {
return (
<View>
<Text style={{color: 'red'}}>
Red color
</Text>
<Text style={{color: 'blue'}}>
Blue color
</Text>
</View>
)
},
},
{
title: 'Font Weight',
render: function () {
return (
<View>
<Text style={{fontWeight: '100'}}>
Move fast and be ultralight
</Text>
<Text style={{fontWeight: '200'}}>
Move fast and be light
</Text>
<Text style={{fontWeight: 'normal'}}>
Move fast and be normal
</Text>
<Text style={{fontWeight: 'bold'}}>
Move fast and be bold
</Text>
<Text style={{fontWeight: '900'}}>
Move fast and be ultrabold
</Text>
</View>
)
},
},
{
title: 'Font Style',
render: function () {
return (
<View>
<Text style={{fontStyle: 'normal'}}>
Normal text
</Text>
<Text style={{fontStyle: 'italic'}}>
Italic text
</Text>
</View>
)
},
},
{
title: 'Nested',
description: 'Nested text components will inherit the styles of their ' +
'parents (only backgroundColor is inherited from non-Text parents). ' +
'<Text> only supports other <Text> and raw text (strings) as children.',
render: function () {
return (
<View>
<Text>
(Normal text,
<Text style={{fontWeight: 'bold'}}>
(and bold
<Text style={{fontSize: 11, color: '#527fe4'}}>
(and tiny inherited bold blue)
</Text>
)
</Text>
)
</Text>
<Text style={{fontSize: 12}}>
<Entity>Entity Name</Entity>
</Text>
</View>
)
},
},
{
title: 'Text Align',
render: function () {
return (
<View>
<Text style={{textAlign: 'left'}}>
left left left left left left left left left left left left left left left
</Text>
<Text style={{textAlign: 'center'}}>
center center center center center center center center center center center
</Text>
<Text style={{textAlign: 'right'}}>
right right right right right right right right right right right right right
</Text>
</View>
)
},
},
{
title: 'Spaces',
render: function () {
return (
<Text>
A {'generated'} {' '} {'string'} and some     spaces
</Text>
)
},
},
{
title: 'Line Height',
render: function () {
return (
<Text>
<Text style={{lineHeight: 35}}>
A lot of space between the lines of this long passage that should
wrap once.
</Text>
</Text>
)
},
},
{
title: 'Empty Text',
description: 'It\'s ok to have Text with zero or null children.',
render: function () {
return (
<Text />
)
},
},
{
title: 'Toggling Attributes',
render: (): React.ReactElement<any> => {
return <AttributeToggler />
},
},
{
title: 'backgroundColor attribute',
description: 'backgroundColor is inherited from all types of views.',
render: function () {
return (
<View style={{backgroundColor: 'yellow'}}>
<Text>
Yellow background inherited from View parent,
<Text style={{backgroundColor: '#ffaaaa'}}>
{' '}red background,
<Text style={{backgroundColor: '#aaaaff'}}>
{' '}blue background,
<Text>
{' '}inherited blue background,
<Text style={{backgroundColor: '#aaffaa'}}>
{' '}nested green background.
</Text>
</Text>
</Text>
</Text>
</Text>
</View>
)
},
},
{
title: 'containerBackgroundColor attribute',
render: function () {
return (
<View>
<View style={{flexDirection: 'row', height: 85}}>
<View style={{backgroundColor: '#ffaaaa', width: 150}}/>
<View style={{backgroundColor: '#aaaaff', width: 150}}/>
</View>
<Text style={[styles.backgroundColorText, {top: -80}]}>
Default containerBackgroundColor (inherited) + backgroundColor wash
</Text>
<Text style={[
styles.backgroundColorText,
{top: -70, containerBackgroundColor: 'transparent'}
]}>
{"containerBackgroundColor: 'transparent' + backgroundColor wash"}
</Text>
</View>
)
},
},
{
title: 'numberOfLines attribute',
render: function () {
return (
<View>
<Text numberOfLines={1}>
Maximum of one line no matter now much I write here. If I keep writing it{"'"}ll just truncate after one line
</Text>
<Text numberOfLines={2} style={{marginTop: 20}}>
Maximum of two lines no matter now much I write here. If I keep writing it{"'"}ll just truncate after two lines
</Text>
<Text style={{marginTop: 20}}>
No maximum lines specified no matter now much I write here. If I keep writing it{"'"}ll just keep going and going
</Text>
</View>
)
}
} ] as RNTSExample[]
} as RNTSExampleModule | the_stack |
import { Tree } from '@angular-devkit/schematics';
import { UnitTestTree } from '@angular-devkit/schematics/testing';
import type { Linter } from 'eslint';
import {
updateArrPropAndRemoveDuplication,
updateObjPropAndRemoveDuplication,
} from '../../src/convert-tslint-to-eslint/utils';
import { isTSLintUsedInWorkspace } from '../../src/utils';
describe('utils', () => {
describe('isTSLintUsedInWorkspace()', () => {
const testCases = [
{
angularJson: {
$schema: './node_modules/@angular/cli/lib/config/schema.json',
version: 1,
newProjectRoot: 'projects',
projects: {
foo: {
projectType: 'application',
schematics: {},
root: '',
sourceRoot: 'src',
prefix: 'app',
architect: {
build: {},
serve: {},
'extract-i18n': {},
test: {},
lint: {},
e2e: {},
},
},
},
},
expected: false,
},
{
angularJson: {
$schema: './node_modules/@angular/cli/lib/config/schema.json',
version: 1,
newProjectRoot: 'projects',
projects: {
foo: {
projectType: 'application',
schematics: {},
root: '',
sourceRoot: 'src',
prefix: 'app',
// "targets" is an undocumented but supported alias of "architect"
targets: {
build: {},
serve: {},
'extract-i18n': {},
test: {},
lint: {},
e2e: {},
},
},
},
},
expected: false,
},
{
angularJson: {
$schema: './node_modules/@angular/cli/lib/config/schema.json',
version: 1,
newProjectRoot: 'projects',
projects: {
foo: {
projectType: 'application',
schematics: {},
root: '',
sourceRoot: 'src',
prefix: 'app',
architect: {
build: {},
serve: {},
'extract-i18n': {},
test: {},
lint: {
builder: '@angular-devkit/build-angular:tslint',
options: {
tsConfig: [
'tsconfig.app.json',
'tsconfig.spec.json',
'e2e/tsconfig.json',
],
exclude: ['**/node_modules/**'],
},
e2e: {},
},
},
},
},
},
expected: true,
},
{
angularJson: {
$schema: './node_modules/@angular/cli/lib/config/schema.json',
version: 1,
newProjectRoot: 'projects',
projects: {
foo: {
projectType: 'application',
schematics: {},
root: '',
sourceRoot: 'src',
prefix: 'app',
// "targets" is an undocumented but supported alias of "architect"
targets: {
build: {},
serve: {},
'extract-i18n': {},
test: {},
lint: {
builder: '@angular-devkit/build-angular:tslint',
options: {
tsConfig: [
'tsconfig.app.json',
'tsconfig.spec.json',
'e2e/tsconfig.json',
],
exclude: ['**/node_modules/**'],
},
e2e: {},
},
},
},
},
},
expected: true,
},
];
testCases.forEach((tc, i) => {
it(`should return true if TSLint is still being used in the workspace, CASE ${i}`, () => {
const workspaceTree = new UnitTestTree(Tree.empty());
workspaceTree.create('angular.json', JSON.stringify(tc.angularJson));
expect(isTSLintUsedInWorkspace(workspaceTree)).toEqual(tc.expected);
});
});
});
describe('updateArrPropAndRemoveDuplication()', () => {
interface TestCase {
json: Linter.Config;
configBeingExtended: Linter.Config;
arrPropName: string;
deleteIfUltimatelyEmpty: boolean;
expectedJSON: Linter.Config;
}
const testCases: TestCase[] = [
{
json: {
extends: ['eslint:recommended'],
},
configBeingExtended: {
extends: ['eslint:recommended'],
},
arrPropName: 'extends',
deleteIfUltimatelyEmpty: true,
expectedJSON: {},
},
{
json: {
extends: ['eslint:recommended'],
},
configBeingExtended: {
extends: ['eslint:recommended'],
},
arrPropName: 'extends',
deleteIfUltimatelyEmpty: false,
expectedJSON: {
extends: [],
},
},
{
json: {
extends: ['eslint:recommended', 'something-custom'],
},
configBeingExtended: {
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
'prettier',
'prettier/@typescript-eslint',
],
},
arrPropName: 'extends',
deleteIfUltimatelyEmpty: false,
expectedJSON: {
extends: ['something-custom'],
},
},
{
json: {
plugins: ['@typescript-eslint', 'some-entirely-custom-user-plugin'],
},
configBeingExtended: {
plugins: ['@typescript-eslint'],
},
arrPropName: 'plugins',
deleteIfUltimatelyEmpty: true,
expectedJSON: {
plugins: ['some-entirely-custom-user-plugin'],
},
},
];
testCases.forEach((tc, i) => {
it(`should remove duplication between the array property of the first-party config and the config being extended, CASE ${i}`, () => {
updateArrPropAndRemoveDuplication(
tc.json,
tc.configBeingExtended,
tc.arrPropName,
tc.deleteIfUltimatelyEmpty,
);
expect(tc.json).toEqual(tc.expectedJSON);
});
});
});
describe('updateObjPropAndRemoveDuplication()', () => {
interface TestCase {
json: Linter.Config;
configBeingExtended: Linter.Config;
objPropName: string;
deleteIfUltimatelyEmpty: boolean;
expectedJSON: Linter.Config;
}
const testCases: TestCase[] = [
{
json: {},
configBeingExtended: {},
objPropName: 'rules',
deleteIfUltimatelyEmpty: false,
expectedJSON: {
rules: {},
},
},
{
json: {},
configBeingExtended: {},
objPropName: 'rules',
deleteIfUltimatelyEmpty: true,
expectedJSON: {},
},
{
json: {
rules: {
'@typescript-eslint/explicit-member-accessibility': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-parameter-properties': 'off',
},
},
configBeingExtended: {
rules: {
'@typescript-eslint/explicit-member-accessibility': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-parameter-properties': 'off',
},
},
objPropName: 'rules',
deleteIfUltimatelyEmpty: false,
expectedJSON: {
rules: {},
},
},
{
json: {
rules: {
'extra-rule-in-first-party': 'error',
'rule-1-same-despite-options-order': [
'error',
{ configOption1: true, configOption2: 'SOMETHING' },
],
'rule-2-different-severity': ['off'],
'rule-3-same-severity-different-options': [
'error',
{
a: false,
},
],
},
},
configBeingExtended: {
rules: {
'extra-rule-in-extended': 'error',
'rule-1-same-despite-options-order': [
'error',
{ configOption2: 'SOMETHING', configOption1: true },
],
'rule-2-different-severity': ['error'],
'rule-3-same-severity-different-options': [
'error',
{
a: true,
},
],
},
},
objPropName: 'rules',
deleteIfUltimatelyEmpty: false,
expectedJSON: {
rules: {
'extra-rule-in-first-party': 'error',
'rule-2-different-severity': ['off'],
'rule-3-same-severity-different-options': [
'error',
{
a: false,
},
],
},
},
},
{
json: {
settings: { react: { version: 'detect' } },
},
configBeingExtended: {
settings: { react: { version: 'detect' } },
},
objPropName: 'settings',
deleteIfUltimatelyEmpty: true,
expectedJSON: {},
},
{
json: {
// Different env in first party config
env: {
browser: true,
commonjs: false,
es6: false,
jest: true,
node: true,
},
},
configBeingExtended: {
env: {
browser: true,
commonjs: true,
es6: true,
jest: true,
node: false,
},
},
objPropName: 'env',
deleteIfUltimatelyEmpty: true,
expectedJSON: {
env: {
commonjs: false,
es6: false,
node: true,
},
},
},
];
testCases.forEach((tc, i) => {
it(`should remove duplication between the object property of the first-party config and the config being extended, CASE ${i}`, () => {
updateObjPropAndRemoveDuplication(
tc.json,
tc.configBeingExtended,
tc.objPropName,
tc.deleteIfUltimatelyEmpty,
);
expect(tc.json).toEqual(tc.expectedJSON);
});
});
});
}); | the_stack |
import {
IConfig, PageViewPerformance, IAppInsights, PageView, RemoteDependencyData, Event as EventTelemetry, IEventTelemetry,
createTelemetryItem, Metric, Exception, eSeverityLevel, Trace, IDependencyTelemetry,
IExceptionTelemetry, ITraceTelemetry, IMetricTelemetry, IAutoExceptionTelemetry,
IPageViewTelemetryInternal, IPageViewTelemetry, IPageViewPerformanceTelemetry, IPageViewPerformanceTelemetryInternal,
IExceptionInternal, PropertiesPluginIdentifier, AnalyticsPluginIdentifier, stringToBoolOrDefault, createDomEvent,
strNotSpecified, isCrossOriginError, utlDisableStorage, utlEnableStorage, dataSanitizeString, createDistributedTraceContextFromTrace
} from "@microsoft/applicationinsights-common";
import {
IPlugin, IConfiguration, IAppInsightsCore,
BaseTelemetryPlugin, ITelemetryItem, IProcessTelemetryContext, ITelemetryPluginChain,
eLoggingSeverity, _eInternalMessageId, ICustomProperties,
getWindow, getDocument, getHistory, getLocation, objForEachKey,
isString, isFunction, isNullOrUndefined, arrForEach, generateW3CId, dumpObj, getExceptionName, ICookieMgr, safeGetCookieMgr,
TelemetryInitializerFunction, hasHistory, strUndefined, objDefineAccessors, InstrumentEvent, IInstrumentCallDetails, eventOn, eventOff,
mergeEvtNamespace, createUniqueNamespace, ITelemetryInitializerHandler, throwError, isUndefined, hasWindow, createProcessTelemetryContext,
ITelemetryUnloadState, IProcessTelemetryUnloadContext, IDistributedTraceContext
} from "@microsoft/applicationinsights-core-js";
import { PageViewManager, IAppInsightsInternal } from "./Telemetry/PageViewManager";
import { PageVisitTimeManager } from "./Telemetry/PageVisitTimeManager";
import { PageViewPerformanceManager } from "./Telemetry/PageViewPerformanceManager";
import dynamicProto from "@microsoft/dynamicproto-js";
// For types only
import { PropertiesPlugin } from "@microsoft/applicationinsights-properties-js";
import { Timing } from "./Timing";
"use strict";
const durationProperty: string = "duration";
const strEvent = "event";
function _dispatchEvent(target:EventTarget, evnt: Event) {
if (target && target.dispatchEvent && evnt) {
target.dispatchEvent(evnt);
}
}
function _getReason(error: any) {
if (error && error.reason) {
const reason = error.reason;
if (!isString(reason) && isFunction(reason.toString)) {
return reason.toString();
}
return dumpObj(reason);
}
// Pass the original object down which will eventually get evaluated for any message or description
return error || "";
}
const MinMilliSeconds = 60000;
function _configMilliseconds(value: number, defValue: number) {
value = value || defValue;
if (value < MinMilliSeconds) {
value = MinMilliSeconds;
}
return value;
}
function _getDefaultConfig(config?: IConfig): IConfig {
if (!config) {
config = {};
}
// set default values
config.sessionRenewalMs = _configMilliseconds(config.sessionRenewalMs, 30 * 60 * 1000);
config.sessionExpirationMs = _configMilliseconds(config.sessionExpirationMs, 24 * 60 * 60 * 1000);
config.disableExceptionTracking = stringToBoolOrDefault(config.disableExceptionTracking);
config.autoTrackPageVisitTime = stringToBoolOrDefault(config.autoTrackPageVisitTime);
config.overridePageViewDuration = stringToBoolOrDefault(config.overridePageViewDuration);
config.enableUnhandledPromiseRejectionTracking = stringToBoolOrDefault(config.enableUnhandledPromiseRejectionTracking);
if (isNaN(config.samplingPercentage) || config.samplingPercentage <= 0 || config.samplingPercentage >= 100) {
config.samplingPercentage = 100;
}
config.isStorageUseDisabled = stringToBoolOrDefault(config.isStorageUseDisabled);
config.isBrowserLinkTrackingEnabled = stringToBoolOrDefault(config.isBrowserLinkTrackingEnabled);
config.enableAutoRouteTracking = stringToBoolOrDefault(config.enableAutoRouteTracking);
config.namePrefix = config.namePrefix || "";
config.enableDebug = stringToBoolOrDefault(config.enableDebug);
config.disableFlushOnBeforeUnload = stringToBoolOrDefault(config.disableFlushOnBeforeUnload);
config.disableFlushOnUnload = stringToBoolOrDefault(config.disableFlushOnUnload, config.disableFlushOnBeforeUnload);
return config;
}
function _updateStorageUsage(extConfig: IConfig) {
// Not resetting the storage usage as someone may have manually called utlDisableStorage, so this will only
// reset based if the configuration option is provided
if (!isUndefined(extConfig.isStorageUseDisabled)) {
if (extConfig.isStorageUseDisabled) {
utlDisableStorage();
} else {
utlEnableStorage();
}
}
}
export class AnalyticsPlugin extends BaseTelemetryPlugin implements IAppInsights, IAppInsightsInternal {
public static Version = "2.8.4"; // Not currently used anywhere
public static getDefaultConfig = _getDefaultConfig;
public identifier: string = AnalyticsPluginIdentifier; // do not change name or priority
public priority: number = 180; // take from reserved priority range 100- 200
public config: IConfig;
public queue: Array<() => void>;
public autoRoutePVDelay = 500; // ms; Time to wait after a route change before triggering a pageview to allow DOM changes to take place
constructor() {
super();
let _eventTracking: Timing;
let _pageTracking: Timing;
let _pageViewManager: PageViewManager;
let _pageViewPerformanceManager: PageViewPerformanceManager;
let _pageVisitTimeManager: PageVisitTimeManager;
let _preInitTelemetryInitializers: TelemetryInitializerFunction[];
let _isBrowserLinkTrackingEnabled: boolean;
let _browserLinkInitializerAdded: boolean;
let _enableAutoRouteTracking: boolean;
let _historyListenerAdded: boolean;
let _disableExceptionTracking: boolean;
let _autoExceptionInstrumented: boolean;
let _enableUnhandledPromiseRejectionTracking: boolean;
let _autoUnhandledPromiseInstrumented: boolean;
// Counts number of trackAjax invocations.
// By default we only monitor X ajax call per view to avoid too much load.
// Default value is set in config.
// This counter keeps increasing even after the limit is reached.
let _trackAjaxAttempts: number = 0;
// array with max length of 2 that store current url and previous url for SPA page route change trackPageview use.
let _prevUri: string; // Assigned in the constructor
let _currUri: string;
let _evtNamespace: string | string[];
dynamicProto(AnalyticsPlugin, this, (_self, _base) => {
let _addHook = _base._addHook;
_initDefaults();
_self.getCookieMgr = () => {
return safeGetCookieMgr(_self.core);
};
_self.processTelemetry = (env: ITelemetryItem, itemCtx?: IProcessTelemetryContext) => {
_self.processNext(env, itemCtx);
};
_self.trackEvent = (event: IEventTelemetry, customProperties?: ICustomProperties): void => {
try {
let telemetryItem = createTelemetryItem<IEventTelemetry>(
event,
EventTelemetry.dataType,
EventTelemetry.envelopeType,
_self.diagLog(),
customProperties
);
_self.core.track(telemetryItem);
} catch (e) {
_throwInternal(eLoggingSeverity.WARNING,
_eInternalMessageId.TrackTraceFailed,
"trackTrace failed, trace will not be collected: " + getExceptionName(e),
{ exception: dumpObj(e) });
}
};
/**
* Start timing an extended event. Call `stopTrackEvent` to log the event when it ends.
* @param name A string that identifies this event uniquely within the document.
*/
_self.startTrackEvent = (name: string) => {
try {
_eventTracking.start(name);
} catch (e) {
_throwInternal(eLoggingSeverity.CRITICAL,
_eInternalMessageId.StartTrackEventFailed,
"startTrackEvent failed, event will not be collected: " + getExceptionName(e),
{ exception: dumpObj(e) });
}
};
/**
* Log an extended event that you started timing with `startTrackEvent`.
* @param name The string you used to identify this event in `startTrackEvent`.
* @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty.
* @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty.
*/
_self.stopTrackEvent = (name: string, properties?: { [key: string]: string }, measurements?: { [key: string]: number }) => {
try {
_eventTracking.stop(name, undefined, properties); // Todo: Fix to pass measurements once type is updated
} catch (e) {
_throwInternal(eLoggingSeverity.CRITICAL,
_eInternalMessageId.StopTrackEventFailed,
"stopTrackEvent failed, event will not be collected: " + getExceptionName(e),
{ exception: dumpObj(e) });
}
};
/**
* @description Log a diagnostic message
* @param {ITraceTelemetry} trace
* @param ICustomProperties.
* @memberof ApplicationInsights
*/
_self.trackTrace = (trace: ITraceTelemetry, customProperties?: ICustomProperties): void => {
try {
let telemetryItem = createTelemetryItem<ITraceTelemetry>(
trace,
Trace.dataType,
Trace.envelopeType,
_self.diagLog(),
customProperties);
_self.core.track(telemetryItem);
} catch (e) {
_throwInternal(eLoggingSeverity.WARNING,
_eInternalMessageId.TrackTraceFailed,
"trackTrace failed, trace will not be collected: " + getExceptionName(e),
{ exception: dumpObj(e) });
}
};
/**
* @description Log a numeric value that is not associated with a specific event. Typically
* used to send regular reports of performance indicators. To send single measurement, just
* use the name and average fields of {@link IMetricTelemetry}. If you take measurements
* frequently, you can reduce the telemetry bandwidth by aggregating multiple measurements
* and sending the resulting average at intervals
* @param {IMetricTelemetry} metric input object argument. Only name and average are mandatory.
* @param {{[key: string]: any}} customProperties additional data used to filter metrics in the
* portal. Defaults to empty.
* @memberof ApplicationInsights
*/
_self.trackMetric = (metric: IMetricTelemetry, customProperties?: ICustomProperties): void => {
try {
let telemetryItem = createTelemetryItem<IMetricTelemetry>(
metric,
Metric.dataType,
Metric.envelopeType,
_self.diagLog(),
customProperties
);
_self.core.track(telemetryItem);
} catch (e) {
_throwInternal(eLoggingSeverity.CRITICAL,
_eInternalMessageId.TrackMetricFailed,
"trackMetric failed, metric will not be collected: " + getExceptionName(e),
{ exception: dumpObj(e) });
}
};
/**
* Logs that a page or other item was viewed.
* @param IPageViewTelemetry The string you used as the name in startTrackPage. Defaults to the document title.
* @param customProperties Additional data used to filter events and metrics. Defaults to empty.
* If a user wants to provide duration for pageLoad, it'll have to be in pageView.properties.duration
*/
_self.trackPageView = (pageView?: IPageViewTelemetry, customProperties?: ICustomProperties) => {
try {
let inPv = pageView || {};
_pageViewManager.trackPageView(inPv, {...inPv.properties, ...inPv.measurements, ...customProperties});
if (_self.config.autoTrackPageVisitTime) {
_pageVisitTimeManager.trackPreviousPageVisit(inPv.name, inPv.uri);
}
} catch (e) {
_throwInternal(
eLoggingSeverity.CRITICAL,
_eInternalMessageId.TrackPVFailed,
"trackPageView failed, page view will not be collected: " + getExceptionName(e),
{ exception: dumpObj(e) });
}
};
/**
* Create a page view telemetry item and send it to the SDK pipeline through the core.track API
* @param pageView Page view item to be sent
* @param properties Custom properties (Part C) that a user can add to the telemetry item
* @param systemProperties System level properties (Part A) that a user can add to the telemetry item
*/
_self.sendPageViewInternal = (pageView: IPageViewTelemetryInternal, properties?: { [key: string]: any }, systemProperties?: { [key: string]: any }) => {
let doc = getDocument();
if (doc) {
pageView.refUri = pageView.refUri === undefined ? doc.referrer : pageView.refUri;
}
let telemetryItem = createTelemetryItem<IPageViewTelemetryInternal>(
pageView,
PageView.dataType,
PageView.envelopeType,
_self.diagLog(),
properties,
systemProperties);
_self.core.track(telemetryItem);
// reset ajaxes counter
_trackAjaxAttempts = 0;
};
/**
* @ignore INTERNAL ONLY
* @param pageViewPerformance
* @param properties
*/
_self.sendPageViewPerformanceInternal = (pageViewPerformance: IPageViewPerformanceTelemetryInternal, properties?: { [key: string]: any }, systemProperties?: { [key: string]: any }) => {
let telemetryItem = createTelemetryItem<IPageViewPerformanceTelemetryInternal>(
pageViewPerformance,
PageViewPerformance.dataType,
PageViewPerformance.envelopeType,
_self.diagLog(),
properties,
systemProperties);
_self.core.track(telemetryItem);
};
/**
* Send browser performance metrics.
* @param pageViewPerformance
* @param customProperties
*/
_self.trackPageViewPerformance = (pageViewPerformance: IPageViewPerformanceTelemetry, customProperties?: ICustomProperties): void => {
let inPvp = pageViewPerformance || {};
try {
_pageViewPerformanceManager.populatePageViewPerformanceEvent(inPvp);
_self.sendPageViewPerformanceInternal(inPvp, customProperties);
} catch (e) {
_throwInternal(
eLoggingSeverity.CRITICAL,
_eInternalMessageId.TrackPVFailed,
"trackPageViewPerformance failed, page view will not be collected: " + getExceptionName(e),
{ exception: dumpObj(e) });
}
};
/**
* Starts the timer for tracking a page load time. Use this instead of `trackPageView` if you want to control when the page view timer starts and stops,
* but don't want to calculate the duration yourself. This method doesn't send any telemetry. Call `stopTrackPage` to log the end of the page view
* and send the event.
* @param name A string that idenfities this item, unique within this HTML document. Defaults to the document title.
*/
_self.startTrackPage = (name?: string) => {
try {
if (typeof name !== "string") {
let doc = getDocument();
name = doc && doc.title || "";
}
_pageTracking.start(name);
} catch (e) {
_throwInternal(
eLoggingSeverity.CRITICAL,
_eInternalMessageId.StartTrackFailed,
"startTrackPage failed, page view may not be collected: " + getExceptionName(e),
{ exception: dumpObj(e) });
}
};
/**
* Stops the timer that was started by calling `startTrackPage` and sends the pageview load time telemetry with the specified properties and measurements.
* The duration of the page view will be the time between calling `startTrackPage` and `stopTrackPage`.
* @param name The string you used as the name in startTrackPage. Defaults to the document title.
* @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location.
* @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty.
* @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty.
*/
_self.stopTrackPage = (name?: string, url?: string, properties?: { [key: string]: string }, measurement?: { [key: string]: number }) => {
try {
if (typeof name !== "string") {
let doc = getDocument();
name = doc && doc.title || "";
}
if (typeof url !== "string") {
let loc = getLocation();
url = loc && loc.href || "";
}
_pageTracking.stop(name, url, properties, measurement);
if (_self.config.autoTrackPageVisitTime) {
_pageVisitTimeManager.trackPreviousPageVisit(name, url);
}
} catch (e) {
_throwInternal(
eLoggingSeverity.CRITICAL,
_eInternalMessageId.StopTrackFailed,
"stopTrackPage failed, page view will not be collected: " + getExceptionName(e),
{ exception: dumpObj(e) });
}
};
/**
* @ignore INTERNAL ONLY
* @param exception
* @param properties
* @param systemProperties
*/
_self.sendExceptionInternal = (exception: IExceptionTelemetry, customProperties?: { [key: string]: any }, systemProperties?: { [key: string]: any }) => {
const theError = exception.exception || exception.error || new Error(strNotSpecified);
let exceptionPartB = new Exception(
_self.diagLog(),
theError,
exception.properties || customProperties,
exception.measurements,
exception.severityLevel,
exception.id
).toInterface();
let telemetryItem: ITelemetryItem = createTelemetryItem<IExceptionInternal>(
exceptionPartB,
Exception.dataType,
Exception.envelopeType,
_self.diagLog(),
customProperties,
systemProperties
);
_self.core.track(telemetryItem);
};
/**
* Log an exception you have caught.
*
* @param {IExceptionTelemetry} exception Object which contains exception to be sent
* @param {{[key: string]: any}} customProperties Additional data used to filter pages and metrics in the portal. Defaults to empty.
*
* Any property of type double will be considered a measurement, and will be treated by Application Insights as a metric.
* @memberof ApplicationInsights
*/
_self.trackException = (exception: IExceptionTelemetry, customProperties?: ICustomProperties): void => {
if (exception && !exception.exception && (exception as any).error) {
exception.exception = (exception as any).error;
}
try {
_self.sendExceptionInternal(exception, customProperties);
} catch (e) {
_throwInternal(
eLoggingSeverity.CRITICAL,
_eInternalMessageId.TrackExceptionFailed,
"trackException failed, exception will not be collected: " + getExceptionName(e),
{ exception: dumpObj(e) });
}
};
/**
* @description Custom error handler for Application Insights Analytics
* @param {IAutoExceptionTelemetry} exception
* @memberof ApplicationInsights
*/
_self._onerror = (exception: IAutoExceptionTelemetry): void => {
let error = exception && exception.error;
let evt = exception && exception.evt;
try {
if (!evt) {
let _window = getWindow();
if (_window) {
evt = _window[strEvent];
}
}
const url = (exception && exception.url) || (getDocument() || {} as any).URL;
// If no error source is provided assume the default window.onerror handler
const errorSrc = exception.errorSrc || "window.onerror@" + url + ":" + (exception.lineNumber || 0) + ":" + (exception.columnNumber || 0);
let properties = {
errorSrc,
url,
lineNumber: exception.lineNumber || 0,
columnNumber: exception.columnNumber || 0,
message: exception.message
};
if (isCrossOriginError(exception.message, exception.url, exception.lineNumber, exception.columnNumber, exception.error)) {
_sendCORSException(Exception.CreateAutoException(
"Script error: The browser's same-origin policy prevents us from getting the details of this exception. Consider using the 'crossorigin' attribute.",
url,
exception.lineNumber || 0,
exception.columnNumber || 0,
error,
evt,
null,
errorSrc
), properties);
} else {
if (!exception.errorSrc) {
exception.errorSrc = errorSrc;
}
_self.trackException({ exception, severityLevel: eSeverityLevel.Error }, properties);
}
} catch (e) {
const errorString = error ? (error.name + ", " + error.message) : "null";
_throwInternal(
eLoggingSeverity.CRITICAL,
_eInternalMessageId.ExceptionWhileLoggingError,
"_onError threw exception while logging error, error will not be collected: "
+ getExceptionName(e),
{ exception: dumpObj(e), errorString }
);
}
};
_self.addTelemetryInitializer = (telemetryInitializer: TelemetryInitializerFunction): ITelemetryInitializerHandler | void => {
if (_self.core) {
// Just add to the core
return _self.core.addTelemetryInitializer(telemetryInitializer);
}
// Handle "pre-initialization" telemetry initializers (for backward compatibility)
if (!_preInitTelemetryInitializers) {
_preInitTelemetryInitializers = [];
}
_preInitTelemetryInitializers.push(telemetryInitializer);
};
_self.initialize = (config: IConfiguration & IConfig, core: IAppInsightsCore, extensions: IPlugin[], pluginChain?:ITelemetryPluginChain) => {
if (_self.isInitialized()) {
return;
}
if (isNullOrUndefined(core)) {
throwError("Error initializing");
}
_base.initialize(config, core, extensions, pluginChain);
try {
_evtNamespace = mergeEvtNamespace(createUniqueNamespace(_self.identifier), core.evtNamespace && core.evtNamespace());
if (_preInitTelemetryInitializers) {
arrForEach(_preInitTelemetryInitializers, (initializer) => {
core.addTelemetryInitializer(initializer);
});
_preInitTelemetryInitializers = null;
}
let extConfig = _populateDefaults(config);
_updateStorageUsage(extConfig);
_pageViewPerformanceManager = new PageViewPerformanceManager(_self.core);
_pageViewManager = new PageViewManager(this, extConfig.overridePageViewDuration, _self.core, _pageViewPerformanceManager);
_pageVisitTimeManager = new PageVisitTimeManager(_self.diagLog(), (pageName, pageUrl, pageVisitTime) => trackPageVisitTime(pageName, pageUrl, pageVisitTime))
_updateBrowserLinkTracking(extConfig, config);
_eventTracking = new Timing(_self.diagLog(), "trackEvent");
_eventTracking.action =
(name?: string, url?: string, duration?: number, properties?: { [key: string]: string }) => {
if (!properties) {
properties = {};
}
properties[durationProperty] = duration.toString();
_self.trackEvent({ name, properties } as IEventTelemetry);
}
// initialize page view timing
_pageTracking = new Timing(_self.diagLog(), "trackPageView");
_pageTracking.action = (name, url, duration, properties, measurements) => {
// duration must be a custom property in order for the collector to extract it
if (isNullOrUndefined(properties)) {
properties = {};
}
properties[durationProperty] = duration.toString();
let pageViewItem: IPageViewTelemetry = {
name,
uri: url,
properties,
measurements
};
_self.sendPageViewInternal(pageViewItem, properties);
}
if (hasWindow()) {
_updateExceptionTracking(extConfig);
_updateLocationChange(extConfig);
}
} catch (e) {
// resetting the initialized state because of failure
_self.setInitialized(false);
throw e;
}
};
_self._doTeardown = (unloadCtx?: IProcessTelemetryUnloadContext, unloadState?: ITelemetryUnloadState) => {
_pageViewManager && _pageViewManager.teardown(unloadCtx, unloadState)
// Just register to remove all events associated with this namespace
eventOff(window, null, null, _evtNamespace);
_initDefaults();
};
function _populateDefaults(config: IConfiguration) {
let ctx = createProcessTelemetryContext(null, config, _self.core);
let identifier = _self.identifier;
// load default values if specified
const defaults: IConfig = _getDefaultConfig(config);
let extConfig = _self.config = ctx.getExtCfg<IConfig>(identifier);
if (defaults !== undefined) {
objForEachKey(defaults, (field, value) => {
// for each unspecified field, set the default value
extConfig[field] = ctx.getConfig(identifier, field, value);
if (extConfig[field] === undefined) {
extConfig = value;
}
});
}
return extConfig;
}
function _updateBrowserLinkTracking(extConfig: IConfig, config: IConfig) {
_isBrowserLinkTrackingEnabled = extConfig.isBrowserLinkTrackingEnabled || config.isBrowserLinkTrackingEnabled;
_addDefaultTelemetryInitializers();
}
/**
* Log a page visit time
* @param pageName Name of page
* @param pageVisitDuration Duration of visit to the page in milleseconds
*/
function trackPageVisitTime(pageName: string, pageUrl: string, pageVisitTime: number) {
let properties = { PageName: pageName, PageUrl: pageUrl };
_self.trackMetric({
name: "PageVisitTime",
average: pageVisitTime,
max: pageVisitTime,
min: pageVisitTime,
sampleCount: 1
}, properties);
}
function _addDefaultTelemetryInitializers() {
if (!_browserLinkInitializerAdded && _isBrowserLinkTrackingEnabled) {
const browserLinkPaths = ["/browserLinkSignalR/", "/__browserLink/"];
const dropBrowserLinkRequests = (envelope: ITelemetryItem) => {
if (_isBrowserLinkTrackingEnabled && envelope.baseType === RemoteDependencyData.dataType) {
let remoteData = envelope.baseData as IDependencyTelemetry;
if (remoteData) {
for (let i = 0; i < browserLinkPaths.length; i++) {
if (remoteData.target && remoteData.target.indexOf(browserLinkPaths[i]) >= 0) {
return false;
}
}
}
}
return true;
}
_self.addTelemetryInitializer(dropBrowserLinkRequests);
_browserLinkInitializerAdded = true;
}
}
function _sendCORSException(exception: IAutoExceptionTelemetry, properties?: ICustomProperties) {
let telemetryItem: ITelemetryItem = createTelemetryItem<IAutoExceptionTelemetry>(
exception,
Exception.dataType,
Exception.envelopeType,
_self.diagLog(),
properties
);
_self.core.track(telemetryItem);
}
function _updateExceptionTracking(extConfig: IConfig) {
let _window = getWindow();
let locn = getLocation(true);
_disableExceptionTracking = extConfig.disableExceptionTracking;
if (!_disableExceptionTracking && !_autoExceptionInstrumented && !extConfig.autoExceptionInstrumented) {
// We want to enable exception auto collection and it has not been done so yet
_addHook(InstrumentEvent(_window, "onerror", {
ns: _evtNamespace,
rsp: (callDetails: IInstrumentCallDetails, message, url, lineNumber, columnNumber, error) => {
if (!_disableExceptionTracking && callDetails.rslt !== true) {
_self._onerror(Exception.CreateAutoException(
message,
url,
lineNumber,
columnNumber,
error,
callDetails.evt
));
}
}
}, false));
_autoExceptionInstrumented = true;
}
_addUnhandledPromiseRejectionTracking(extConfig, _window, locn);
}
function _updateLocationChange(extConfig: IConfig) {
let win = getWindow();
let locn = getLocation(true);
_enableAutoRouteTracking = extConfig.enableAutoRouteTracking === true;
/**
* Create a custom "locationchange" event which is triggered each time the history object is changed
*/
if (win && _enableAutoRouteTracking && hasHistory()) {
let _history = getHistory();
if (isFunction(_history.pushState) && isFunction(_history.replaceState) && typeof Event !== strUndefined) {
_addHistoryListener(extConfig, win, _history, locn);
}
}
}
function _getDistributedTraceCtx(): IDistributedTraceContext {
let distributedTraceCtx: IDistributedTraceContext = null;
if (_self.core && _self.core.getTraceCtx) {
distributedTraceCtx = _self.core.getTraceCtx(false);
}
if (!distributedTraceCtx) {
// Fallback when using an older Core and PropertiesPlugin
let properties = _self.core.getPlugin<PropertiesPlugin>(PropertiesPluginIdentifier);
if (properties) {
let context = properties.plugin.context;
if (context) {
distributedTraceCtx = createDistributedTraceContextFromTrace(context.telemetryTrace);
}
}
}
return distributedTraceCtx;
}
/**
* Create a custom "locationchange" event which is triggered each time the history object is changed
*/
function _addHistoryListener(extConfig: IConfig, win: Window, history: History, locn: Location) {
function _popstateHandler() {
if (_enableAutoRouteTracking) {
_dispatchEvent(win, createDomEvent(extConfig.namePrefix + "locationchange"));
}
}
function _locationChangeHandler() {
// We always track the changes (if the handler is installed) to handle the feature being disabled between location changes
if (_currUri) {
_prevUri = _currUri;
_currUri = locn && locn.href || "";
} else {
_currUri = locn && locn.href || "";
}
if (_enableAutoRouteTracking) {
let distributedTraceCtx = _getDistributedTraceCtx();
if (distributedTraceCtx) {
distributedTraceCtx.setTraceId(generateW3CId());
let traceLocationName = "_unknown_";
if (locn && locn.pathname) {
traceLocationName = locn.pathname + (locn.hash || "");
}
// This populates the ai.operation.name which has a maximum size of 1024 so we need to sanitize it
distributedTraceCtx.setName(dataSanitizeString(_self.diagLog(), traceLocationName));
}
setTimeout(((uri: string) => {
// todo: override start time so that it is not affected by autoRoutePVDelay
_self.trackPageView({ refUri: uri, properties: { duration: 0 } }); // SPA route change loading durations are undefined, so send 0
}).bind(this, _prevUri), _self.autoRoutePVDelay);
}
}
if (!_historyListenerAdded) {
_addHook(InstrumentEvent(history, "pushState", {
ns: _evtNamespace,
rsp: () => {
if (_enableAutoRouteTracking) {
_dispatchEvent(win, createDomEvent(extConfig.namePrefix + "pushState"));
_dispatchEvent(win, createDomEvent(extConfig.namePrefix + "locationchange"));
}
}
}, true));
_addHook(InstrumentEvent(history, "replaceState", {
ns: _evtNamespace,
rsp: () => {
if (_enableAutoRouteTracking) {
_dispatchEvent(win, createDomEvent(extConfig.namePrefix + "replaceState"));
_dispatchEvent(win, createDomEvent(extConfig.namePrefix + "locationchange"));
}
}
}, true));
eventOn(win, extConfig.namePrefix + "popstate", _popstateHandler, _evtNamespace);
eventOn(win, extConfig.namePrefix + "locationchange", _locationChangeHandler, _evtNamespace);
_historyListenerAdded = true;
}
}
function _addUnhandledPromiseRejectionTracking(extConfig: IConfig, _window: Window, _location: Location) {
_enableUnhandledPromiseRejectionTracking = extConfig.enableUnhandledPromiseRejectionTracking === true;
if (_enableUnhandledPromiseRejectionTracking && !_autoUnhandledPromiseInstrumented) {
// We want to enable exception auto collection and it has not been done so yet
_addHook(InstrumentEvent(_window, "onunhandledrejection", {
ns: _evtNamespace,
rsp: (callDetails: IInstrumentCallDetails, error: PromiseRejectionEvent) => {
if (_enableUnhandledPromiseRejectionTracking && callDetails.rslt !== true) { // handled could be typeof function
_self._onerror(Exception.CreateAutoException(
_getReason(error),
_location ? _location.href : "",
0,
0,
error,
callDetails.evt
));
}
}
}, false));
_autoUnhandledPromiseInstrumented = true;
extConfig.autoUnhandledPromiseInstrumented = _autoUnhandledPromiseInstrumented;
}
}
/**
* This method will throw exceptions in debug mode or attempt to log the error as a console warning.
* @param severity {LoggingSeverity} - The severity of the log message
* @param message {_InternalLogMessage} - The log message.
*/
function _throwInternal(severity: eLoggingSeverity, msgId: _eInternalMessageId, msg: string, properties?: Object, isUserAct?: boolean): void {
_self.diagLog().throwInternal(severity, msgId, msg, properties, isUserAct);
}
function _initDefaults() {
_eventTracking = null;
_pageTracking = null;
_pageViewManager = null;
_pageViewPerformanceManager = null;
_pageVisitTimeManager = null;
_preInitTelemetryInitializers = null;
_isBrowserLinkTrackingEnabled = false;
_browserLinkInitializerAdded = false;
_enableAutoRouteTracking = false;
_historyListenerAdded = false;
_disableExceptionTracking = false;
_autoExceptionInstrumented = false;
_enableUnhandledPromiseRejectionTracking = false;
_autoUnhandledPromiseInstrumented = false;
// Counts number of trackAjax invocations.
// By default we only monitor X ajax call per view to avoid too much load.
// Default value is set in config.
// This counter keeps increasing even after the limit is reached.
_trackAjaxAttempts = 0;
// array with max length of 2 that store current url and previous url for SPA page route change trackPageview use.
let location = getLocation(true);
_prevUri = location && location.href || "";
_currUri = null;
_evtNamespace = null;
}
// For backward compatibility
objDefineAccessors(_self, "_pageViewManager", () => _pageViewManager);
objDefineAccessors(_self, "_pageViewPerformanceManager", () => _pageViewPerformanceManager);
objDefineAccessors(_self, "_pageVisitTimeManager", () => _pageVisitTimeManager);
objDefineAccessors(_self, "_evtNamespace", () => "." + _evtNamespace);
});
}
/**
* Get the current cookie manager for this instance
*/
public getCookieMgr(): ICookieMgr {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return null;
}
public processTelemetry(env: ITelemetryItem, itemCtx?: IProcessTelemetryContext) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
public trackEvent(event: IEventTelemetry, customProperties?: ICustomProperties): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* Start timing an extended event. Call `stopTrackEvent` to log the event when it ends.
* @param name A string that identifies this event uniquely within the document.
*/
public startTrackEvent(name: string) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* Log an extended event that you started timing with `startTrackEvent`.
* @param name The string you used to identify this event in `startTrackEvent`.
* @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty.
* @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty.
*/
public stopTrackEvent(name: string, properties?: { [key: string]: string }, measurements?: { [key: string]: number }) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* @description Log a diagnostic message
* @param {ITraceTelemetry} trace
* @param ICustomProperties.
* @memberof ApplicationInsights
*/
public trackTrace(trace: ITraceTelemetry, customProperties?: ICustomProperties): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* @description Log a numeric value that is not associated with a specific event. Typically
* used to send regular reports of performance indicators. To send single measurement, just
* use the name and average fields of {@link IMetricTelemetry}. If you take measurements
* frequently, you can reduce the telemetry bandwidth by aggregating multiple measurements
* and sending the resulting average at intervals
* @param {IMetricTelemetry} metric input object argument. Only name and average are mandatory.
* @param {{[key: string]: any}} customProperties additional data used to filter metrics in the
* portal. Defaults to empty.
* @memberof ApplicationInsights
*/
public trackMetric(metric: IMetricTelemetry, customProperties?: ICustomProperties): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* Logs that a page or other item was viewed.
* @param IPageViewTelemetry The string you used as the name in startTrackPage. Defaults to the document title.
* @param customProperties Additional data used to filter events and metrics. Defaults to empty.
* If a user wants to provide duration for pageLoad, it'll have to be in pageView.properties.duration
*/
public trackPageView(pageView?: IPageViewTelemetry, customProperties?: ICustomProperties) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* Create a page view telemetry item and send it to the SDK pipeline through the core.track API
* @param pageView Page view item to be sent
* @param properties Custom properties (Part C) that a user can add to the telemetry item
* @param systemProperties System level properties (Part A) that a user can add to the telemetry item
*/
public sendPageViewInternal(pageView: IPageViewTelemetryInternal, properties?: { [key: string]: any }, systemProperties?: { [key: string]: any }) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* @ignore INTERNAL ONLY
* @param pageViewPerformance
* @param properties
*/
public sendPageViewPerformanceInternal(pageViewPerformance: IPageViewPerformanceTelemetryInternal, properties?: { [key: string]: any }, systemProperties?: { [key: string]: any }) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* Send browser performance metrics.
* @param pageViewPerformance
* @param customProperties
*/
public trackPageViewPerformance(pageViewPerformance: IPageViewPerformanceTelemetry, customProperties?: ICustomProperties): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* Starts the timer for tracking a page load time. Use this instead of `trackPageView` if you want to control when the page view timer starts and stops,
* but don't want to calculate the duration yourself. This method doesn't send any telemetry. Call `stopTrackPage` to log the end of the page view
* and send the event.
* @param name A string that idenfities this item, unique within this HTML document. Defaults to the document title.
*/
public startTrackPage(name?: string) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* Stops the timer that was started by calling `startTrackPage` and sends the pageview load time telemetry with the specified properties and measurements.
* The duration of the page view will be the time between calling `startTrackPage` and `stopTrackPage`.
* @param name The string you used as the name in startTrackPage. Defaults to the document title.
* @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location.
* @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty.
* @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty.
*/
public stopTrackPage(name?: string, url?: string, properties?: { [key: string]: string }, measurement?: { [key: string]: number }) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* @ignore INTERNAL ONLY
* @param exception
* @param properties
* @param systemProperties
*/
public sendExceptionInternal(exception: IExceptionTelemetry, customProperties?: { [key: string]: any }, systemProperties?: { [key: string]: any }) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* Log an exception you have caught.
*
* @param {IExceptionTelemetry} exception Object which contains exception to be sent
* @param {{[key: string]: any}} customProperties Additional data used to filter pages and metrics in the portal. Defaults to empty.
*
* Any property of type double will be considered a measurement, and will be treated by Application Insights as a metric.
* @memberof ApplicationInsights
*/
public trackException(exception: IExceptionTelemetry, customProperties?: ICustomProperties): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* @description Custom error handler for Application Insights Analytics
* @param {IAutoExceptionTelemetry} exception
* @memberof ApplicationInsights
*/
public _onerror(exception: IAutoExceptionTelemetry): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
public addTelemetryInitializer(telemetryInitializer: (item: ITelemetryItem) => boolean | void): ITelemetryInitializerHandler | void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
public initialize(config: IConfiguration & IConfig, core: IAppInsightsCore, extensions: IPlugin[], pluginChain?:ITelemetryPluginChain) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
} | the_stack |
/// <reference types="node" />
import { EventEmitter } from 'events';
import { Writable as NodeJSWritable, Readable as NodeJSReadable, Stream as NodeJSStream } from 'stream';
export interface AbortSignalLike {
addEventListener: (type: 'abort', listener: (this: AbortSignalLike, event: any) => any) => void;
}
export type AnyStream = NodeJSStream | Stream;
export type AnyWritable<TType = any, TMap = TType, TByte = TMap> =
| NodeJSWritable
| Writable<TType, TMap, TByte>
| Duplex<TType, TByte, TMap, TByte>;
export type AnyReadable<TType = any, TMap = TType, TByte = TMap> = NodeJSReadable | Readable<TType, TMap, TByte>;
export interface Callback {
(err?: Error | null): void;
}
export interface ResultCallback<T> {
(err?: Error | null, result?: T): void;
}
export interface StreamOptions<TStream extends Stream<TByteType>, TByteType = any> {
highWaterMark?: number | undefined;
byteLength?: ByteLengthFunction<TStream, TByteType> | undefined;
open?: ((this: TStream, cb: Callback) => void) | undefined;
destroy?: ((this: TStream, cb: Callback) => void) | undefined;
predestroy?: ((this: TStream, cb: Callback) => void) | undefined;
signal?: AbortSignalLike | undefined;
}
/* tslint:disable-next-line interface-over-type-literal - cause: https://github.com/microsoft/TypeScript/issues/15300 */
export type StreamEvents = {
open: () => void;
close: () => void;
error: (error: Error) => void;
};
export type Events = { [event: string]: (...args: any[]) => void } | undefined;
export type EventName<TEvents extends Events> = TEvents extends undefined ? string | symbol : keyof TEvents;
export type EventListener<TEvents extends Events, TEvent extends string | symbol | number> = TEvents extends undefined
? (...args: any[]) => void
: TEvent extends keyof TEvents
? TEvents[TEvent]
: (...args: any[]) => void;
export class Stream<
TByteType = any,
TReadable extends boolean = false,
TWritable extends boolean = false,
TEvents extends StreamEvents = StreamEvents
> extends EventEmitter {
constructor(opts?: StreamOptions<Stream<TByteType>, TByteType>);
_open(cb: Callback): void;
_destroy(cb: Callback): void;
_predestroy(cb: Callback): void;
readonly readable: TReadable;
readonly writable: TWritable;
readonly destroyed: boolean;
readonly destroying: boolean;
destroy(error?: Error | null): void;
addListener<TEvent extends EventName<TEvents>>(event: TEvent, listener: EventListener<TEvents, TEvent>): this;
on<TEvent extends EventName<TEvents>>(event: TEvent, listener: EventListener<TEvents, TEvent>): this;
once<TEvent extends EventName<TEvents>>(event: TEvent, listener: EventListener<TEvents, TEvent>): this;
removeListener<TEvent extends EventName<TEvents>>(event: TEvent, listener: EventListener<TEvents, TEvent>): this;
off<TEvent extends EventName<TEvents>>(event: TEvent, listener: EventListener<TEvents, TEvent>): this;
removeAllListeners(event?: EventName<TEvents>): this;
setMaxListeners(n: number): this;
getMaxListeners(): number;
listeners<TEvent extends EventName<TEvents>>(event: TEvent): Array<EventListener<TEvents, TEvent>>;
rawListeners<TEvent extends EventName<TEvents>>(event: TEvent): Array<EventListener<TEvents, TEvent>>;
emit<TEvent extends EventName<TEvents>>(
event: TEvent,
...rest: Parameters<EventListener<TEvents, TEvent>>
): boolean;
listenerCount(event: EventName<TEvents>): number;
// Added in Node 6...
prependListener<TEvent extends EventName<TEvents>>(event: TEvent, listener: EventListener<TEvents, TEvent>): this;
prependOnceListener<TEvent extends EventName<TEvents>>(
event: TEvent,
listener: EventListener<TEvents, TEvent>,
): this;
eventNames(): Array<string | symbol>;
}
export type MapFunction<TThis, TIn, TOut> = ((this: TThis, input: TIn) => TOut) | null | undefined;
export type ByteLengthFunction<TThis, TData> = ((this: TThis, data: TData) => number) | null | undefined;
export interface BaseReadableOptions<
TStream extends Readable<TType, TMapType, TByteType, any, any>,
TType,
TMapType,
TByteType
> extends StreamOptions<TStream, TByteType> {
read?: ((this: TStream, cb: ResultCallback<TType>) => void) | undefined;
byteLengthReadable?: ByteLengthFunction<TStream, TByteType> | undefined;
}
export type ReadableOptions<
TStream extends Readable<TType, TMapType, TByteType, any, any>,
TType,
TMapType,
TByteType,
TMapFallback = any
> = BaseReadableOptions<TStream, TType, TMapType, TByteType> &
(
| {}
| {
map?: TMapFallback | undefined;
mapReadable: MapFunction<TStream, TType, TMapType>;
}
| {
map: MapFunction<TStream, TType, TMapType>;
}
);
type FromType<TData> = TData extends Readable
? TData
: TData extends Iterable<infer TType>
? Readable<TType>
: TData extends AsyncIterable<infer TType>
? Readable<TType>
: Readable<TData>;
export type ReadableEvents<TMapType> = StreamEvents & {
piping: (writable: Writable<TMapType>) => void;
readable: () => void;
data: (data: TMapType) => void;
end: () => void;
};
export class Readable<
TType = any,
TMapType = TType,
TByteType = TMapType,
TReadable extends boolean = true,
TWritable extends boolean = false,
TEvents extends ReadableEvents<TMapType> = ReadableEvents<TMapType>
> extends Stream<TByteType, TReadable, TWritable, TEvents> {
constructor(opts?: ReadableOptions<Readable<TType, TMapType>, TType, TMapType, TByteType>);
_read(cb: ResultCallback<TType>): void;
pipe<TTarget extends AnyWritable<TMapType, any, any> = AnyWritable<TMapType, any, any>>(
dest: TTarget,
cb?: Callback,
): TTarget;
read(): TMapType;
push(data: TType | null): boolean;
unshift(data: TType | null): void;
resume(): this;
pause(): this;
static from<TInput = any>(input?: TInput): FromType<TInput>;
static isPaused(rs: Readable): boolean;
static isBackpressured(rs: Readable): boolean;
[Symbol.asyncIterator]: () => AsyncIterator<TType>;
}
export interface BaseWritableOptions<
TStream extends Writable<TType, TMapType, TByteType, any, any>,
TType,
TMapType,
TByteType
> extends StreamOptions<TStream, TByteType> {
writev?: ((this: TStream, batch: TMapType[], cb: Callback) => void) | undefined;
write?: ((this: TStream, data: TMapType, cb: Callback) => void) | undefined;
final?: ((this: TStream, cb: Callback) => void) | undefined;
byteLengthWritable?: ByteLengthFunction<TStream, TByteType> | undefined;
}
export type WritableOptions<
TStream extends Writable<TType, TMapType, TByteType, any, any>,
TType,
TMapType,
TByteType,
TMapFallback = any
> = BaseWritableOptions<TStream, TType, TMapType, TByteType> &
(
| {}
| {
map?: TMapFallback | undefined;
mapWritable: MapFunction<TStream, TType, TMapType>;
}
| {
map: MapFunction<TStream, TType, TMapType>;
}
);
export type WritableEvents<TType> = StreamEvents & {
/* tslint:disable-next-line use-default-type-parameter */
pipe: (readable: Readable<any, TType>) => void;
finish: () => void;
drain: () => void;
};
export class Writable<
TType = any,
TMapType = TType,
TByteType = TType,
TReadable extends boolean = false,
TWritable extends boolean = true,
TEvents extends WritableEvents<TType> = WritableEvents<TType>
> extends Stream<TByteType, TReadable, TWritable, TEvents> {
constructor(opts?: WritableOptions<Writable<TType, TMapType, TByteType>, TType, TMapType, TByteType>);
_writev(batch: TMapType[], cb: Callback): void;
_write(data: TMapType, cb: Callback): void;
_final(cb: Callback): void;
write(data: TType): boolean;
end(data?: TType | Callback): void;
static isBackpressured(ws: Writable): boolean;
}
export type DuplexOptions<
TStream extends Duplex<TWriteType, TReadType, TInternal, TByteType, TReadable, TWritable>,
TWriteType = any,
TReadType = TWriteType,
TInternal = TWriteType,
TByteType = TWriteType | TReadType,
TReadable extends boolean = boolean,
TWritable extends boolean = boolean
> = BaseReadableOptions<TStream, TInternal, TReadType, TByteType> &
BaseWritableOptions<TStream, TWriteType, TInternal, TInternal> & {
map?: MapFunction<TStream, TByteType, TByteType> | undefined;
mapReadable?: MapFunction<TStream, TInternal, TReadType> | undefined;
mapWritable?: MapFunction<TStream, TWriteType, TInternal> | undefined;
};
export type DuplexEvents<TWriteType, TReadType> = ReadableEvents<TReadType> & WritableEvents<TWriteType>;
export class Duplex<
TWriteType = any,
TReadType = TWriteType,
TInternal = TWriteType,
TByteType = TWriteType | TReadType,
TReadable extends boolean = true,
TWritable extends boolean = true,
TEvents extends DuplexEvents<TWriteType, TReadType> = DuplexEvents<TWriteType, TReadType>
>
extends Readable<TInternal, TReadType, TByteType, TReadable, TWritable, TEvents>
implements Writable<TWriteType, TInternal, TByteType, TReadable, TWritable, TEvents> {
constructor(
opts?: DuplexOptions<
Duplex<TWriteType, TReadType, TInternal, TByteType, TReadable, TWritable>,
TWriteType,
TReadType,
TInternal,
TByteType,
TReadable,
TWritable
>,
);
_writev(batch: TInternal[], cb: Callback): void;
_write(data: TInternal, cb: Callback): void;
_final(cb: Callback): void;
write(data: TWriteType): boolean;
end(data?: TWriteType | Callback): void;
}
export interface TransformOptions<
TStream extends Transform<TWriteType, TReadType, TInternal, TByteType, TReadable, TWritable>,
TWriteType = any,
TReadType = TWriteType,
TInternal = TWriteType,
TByteType = TWriteType | TReadType,
TReadable extends boolean = true,
TWritable extends boolean = true
> extends DuplexOptions<TStream, TWriteType, TReadType, TInternal, TByteType, TReadable, TWritable> {
transform?: ((this: TStream, data: TWriteType, cb: ResultCallback<TReadType>) => void) | undefined;
flush?: ((this: TStream, cb: Callback) => void) | undefined;
}
export class Transform<
TWriteType = any,
TReadType = TWriteType,
TInternal = TWriteType,
TByteType = TWriteType | TReadType,
TReadable extends boolean = true,
TWritable extends boolean = true
> extends Duplex<TWriteType, TReadType, TInternal, TByteType, TReadable, TWritable> {
constructor(
opts?: TransformOptions<
Transform<TWriteType, TReadType, TInternal, TByteType, TReadable, TWritable>,
TWriteType,
TReadType,
TInternal,
TByteType,
TReadable,
TWritable
>,
);
_transform(data: TWriteType, cb: ResultCallback<TReadType>): void;
_flush(cb: Callback): void;
}
export class PassThrough<TRead = any, TWrite = any> extends Transform<TRead, TWrite> {
constructor(opts?: TransformOptions<Transform<TRead, TWrite>, TRead, TWrite>);
}
export function isStream(input: object): input is AnyStream;
export function isStreamx(input: object): input is Stream;
export {}; | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement, Operator } from "../shared";
/**
* Statement provider for service [networkmanager](https://docs.aws.amazon.com/service-authorization/latest/reference/list_networkmanager.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Networkmanager extends PolicyStatement {
public servicePrefix = 'networkmanager';
/**
* Statement provider for service [networkmanager](https://docs.aws.amazon.com/service-authorization/latest/reference/list_networkmanager.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 associate a customer gateway to a device
*
* Access Level: Write
*
* Possible conditions:
* - .ifCgwArn()
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_AssociateCustomerGateway.html
*/
public toAssociateCustomerGateway() {
return this.to('AssociateCustomerGateway');
}
/**
* Grants permission to associate a link to a device
*
* Access Level: Write
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_AssociateLink.html
*/
public toAssociateLink() {
return this.to('AssociateLink');
}
/**
* Grants permission to associate a transit gateway connect peer to a device
*
* Access Level: Write
*
* Possible conditions:
* - .ifTgwConnectPeerArn()
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_AssociateTransitGatewayConnectPeer.html
*/
public toAssociateTransitGatewayConnectPeer() {
return this.to('AssociateTransitGatewayConnectPeer');
}
/**
* Grants permission to create a new connection
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_CreateConnection.html
*/
public toCreateConnection() {
return this.to('CreateConnection');
}
/**
* Grants permission to create a new device
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_CreateDevice.html
*/
public toCreateDevice() {
return this.to('CreateDevice');
}
/**
* Grants permission to create a new global network
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* Dependent actions:
* - iam:CreateServiceLinkedRole
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_CreateGlobalNetwork.html
*/
public toCreateGlobalNetwork() {
return this.to('CreateGlobalNetwork');
}
/**
* Grants permission to create a new link
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_CreateLink.html
*/
public toCreateLink() {
return this.to('CreateLink');
}
/**
* Grants permission to create a new site
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_CreateSite.html
*/
public toCreateSite() {
return this.to('CreateSite');
}
/**
* Grants permission to delete a connection
*
* Access Level: Write
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_DeleteConnection.html
*/
public toDeleteConnection() {
return this.to('DeleteConnection');
}
/**
* Grants permission to delete a device
*
* Access Level: Write
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_DeleteDevice.html
*/
public toDeleteDevice() {
return this.to('DeleteDevice');
}
/**
* Grants permission to delete a global network
*
* Access Level: Write
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_DeleteGlobalNetwork.html
*/
public toDeleteGlobalNetwork() {
return this.to('DeleteGlobalNetwork');
}
/**
* Grants permission to delete a link
*
* Access Level: Write
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_DeleteLink.html
*/
public toDeleteLink() {
return this.to('DeleteLink');
}
/**
* Grants permission to delete a site
*
* Access Level: Write
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_DeleteSite.html
*/
public toDeleteSite() {
return this.to('DeleteSite');
}
/**
* Grants permission to deregister a transit gateway from a global network
*
* Access Level: Write
*
* Possible conditions:
* - .ifTgwArn()
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_DeregisterTransitGateway.html
*/
public toDeregisterTransitGateway() {
return this.to('DeregisterTransitGateway');
}
/**
* Grants permission to describe global networks
*
* Access Level: List
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_DescribeGlobalNetworks.html
*/
public toDescribeGlobalNetworks() {
return this.to('DescribeGlobalNetworks');
}
/**
* Grants permission to disassociate a customer gateway from a device
*
* Access Level: Write
*
* Possible conditions:
* - .ifCgwArn()
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_DisassociateCustomerGateway.html
*/
public toDisassociateCustomerGateway() {
return this.to('DisassociateCustomerGateway');
}
/**
* Grants permission to disassociate a link from a device
*
* Access Level: Write
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_DisassociateLink.html
*/
public toDisassociateLink() {
return this.to('DisassociateLink');
}
/**
* Grants permission to disassociate a transit gateway connect peer from a device
*
* Access Level: Write
*
* Possible conditions:
* - .ifTgwConnectPeerArn()
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_DisassociateTransitGatewayConnectPeer.html
*/
public toDisassociateTransitGatewayConnectPeer() {
return this.to('DisassociateTransitGatewayConnectPeer');
}
/**
* Grants permission to describe connections
*
* Access Level: List
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_GetConnections.html
*/
public toGetConnections() {
return this.to('GetConnections');
}
/**
* Grants permission to describe customer gateway associations
*
* Access Level: List
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_GetCustomerGatewayAssociations.html
*/
public toGetCustomerGatewayAssociations() {
return this.to('GetCustomerGatewayAssociations');
}
/**
* Grants permission to describe devices
*
* Access Level: List
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_GetDevices.html
*/
public toGetDevices() {
return this.to('GetDevices');
}
/**
* Grants permission to describe link associations
*
* Access Level: List
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_GetLinkAssociations.html
*/
public toGetLinkAssociations() {
return this.to('GetLinkAssociations');
}
/**
* Grants permission to describe links
*
* Access Level: List
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_GetLinks.html
*/
public toGetLinks() {
return this.to('GetLinks');
}
/**
* Grants permission to describe global networks
*
* Access Level: List
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_GetSites.html
*/
public toGetSites() {
return this.to('GetSites');
}
/**
* Grants permission to describe transit gateway connect peer associations
*
* Access Level: List
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_GetTransitGatewayConnectPeerAssociations.html
*/
public toGetTransitGatewayConnectPeerAssociations() {
return this.to('GetTransitGatewayConnectPeerAssociations');
}
/**
* Grants permission to describe transit gateway registrations
*
* Access Level: List
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_GetTransitGatewayRegistrations.html
*/
public toGetTransitGatewayRegistrations() {
return this.to('GetTransitGatewayRegistrations');
}
/**
* Grants permission to lists tag for a Network Manager resource
*
* Access Level: Read
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_ListTagsForResource.html
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Grants permission to register a transit gateway to a global network
*
* Access Level: Write
*
* Possible conditions:
* - .ifTgwArn()
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_RegisterTransitGateway.html
*/
public toRegisterTransitGateway() {
return this.to('RegisterTransitGateway');
}
/**
* Grants permission to tag a Network Manager resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_TagResource.html
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Grants permission to untag a Network Manager resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_UntagResource.html
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Grants permission to update a connection
*
* Access Level: Write
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_UpdateConnection.html
*/
public toUpdateConnection() {
return this.to('UpdateConnection');
}
/**
* Grants permission to update a device
*
* Access Level: Write
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_UpdateDevice.html
*/
public toUpdateDevice() {
return this.to('UpdateDevice');
}
/**
* Grants permission to update a global network
*
* Access Level: Write
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_UpdateGlobalNetwork.html
*/
public toUpdateGlobalNetwork() {
return this.to('UpdateGlobalNetwork');
}
/**
* Grants permission to update a link
*
* Access Level: Write
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_UpdateLink.html
*/
public toUpdateLink() {
return this.to('UpdateLink');
}
/**
* Grants permission to update a site
*
* Access Level: Write
*
* https://docs.aws.amazon.com/networkmanager/latest/APIReference/API_UpdateSite.html
*/
public toUpdateSite() {
return this.to('UpdateSite');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"AssociateCustomerGateway",
"AssociateLink",
"AssociateTransitGatewayConnectPeer",
"CreateConnection",
"CreateDevice",
"CreateGlobalNetwork",
"CreateLink",
"CreateSite",
"DeleteConnection",
"DeleteDevice",
"DeleteGlobalNetwork",
"DeleteLink",
"DeleteSite",
"DeregisterTransitGateway",
"DisassociateCustomerGateway",
"DisassociateLink",
"DisassociateTransitGatewayConnectPeer",
"RegisterTransitGateway",
"UpdateConnection",
"UpdateDevice",
"UpdateGlobalNetwork",
"UpdateLink",
"UpdateSite"
],
"List": [
"DescribeGlobalNetworks",
"GetConnections",
"GetCustomerGatewayAssociations",
"GetDevices",
"GetLinkAssociations",
"GetLinks",
"GetSites",
"GetTransitGatewayConnectPeerAssociations",
"GetTransitGatewayRegistrations"
],
"Read": [
"ListTagsForResource"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type global-network to the statement
*
* https://docs.aws.amazon.com/vpc/latest/tgw/what-is-network-manager.html
*
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onGlobalNetwork(resourceId: string, account?: string, partition?: string) {
var arn = 'arn:${Partition}:networkmanager::${Account}:global-network/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type site to the statement
*
* https://docs.aws.amazon.com/vpc/latest/tgw/what-is-network-manager.html
*
* @param globalNetworkId - Identifier for the globalNetworkId.
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onSite(globalNetworkId: string, resourceId: string, account?: string, partition?: string) {
var arn = 'arn:${Partition}:networkmanager::${Account}:site/${GlobalNetworkId}/${ResourceId}';
arn = arn.replace('${GlobalNetworkId}', globalNetworkId);
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type link to the statement
*
* https://docs.aws.amazon.com/vpc/latest/tgw/what-is-network-manager.html
*
* @param globalNetworkId - Identifier for the globalNetworkId.
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onLink(globalNetworkId: string, resourceId: string, account?: string, partition?: string) {
var arn = 'arn:${Partition}:networkmanager::${Account}:link/${GlobalNetworkId}/${ResourceId}';
arn = arn.replace('${GlobalNetworkId}', globalNetworkId);
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type device to the statement
*
* https://docs.aws.amazon.com/vpc/latest/tgw/what-is-network-manager.html
*
* @param globalNetworkId - Identifier for the globalNetworkId.
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onDevice(globalNetworkId: string, resourceId: string, account?: string, partition?: string) {
var arn = 'arn:${Partition}:networkmanager::${Account}:device/${GlobalNetworkId}/${ResourceId}';
arn = arn.replace('${GlobalNetworkId}', globalNetworkId);
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type connection to the statement
*
* https://docs.aws.amazon.com/vpc/latest/tgw/what-is-network-manager.html
*
* @param globalNetworkId - Identifier for the globalNetworkId.
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onConnection(globalNetworkId: string, resourceId: string, account?: string, partition?: string) {
var arn = 'arn:${Partition}:networkmanager::${Account}:connection/${GlobalNetworkId}/${ResourceId}';
arn = arn.replace('${GlobalNetworkId}', globalNetworkId);
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Controls which customer gateways can be associated or disassociated
*
* https://docs.aws.amazon.com/vpc/latest/tgw/nm-security-iam.html
*
* Applies to actions:
* - .toAssociateCustomerGateway()
* - .toDisassociateCustomerGateway()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifCgwArn(value: string | string[], operator?: Operator | string) {
return this.if(`cgwArn`, value, operator || 'StringLike');
}
/**
* Controls which transit gateways can be registered or deregistered
*
* https://docs.aws.amazon.com/vpc/latest/tgw/nm-security-iam.html
*
* Applies to actions:
* - .toDeregisterTransitGateway()
* - .toRegisterTransitGateway()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifTgwArn(value: string | string[], operator?: Operator | string) {
return this.if(`tgwArn`, value, operator || 'StringLike');
}
/**
* Controls which connect peers can be associated or disassociated
*
* https://docs.aws.amazon.com/vpc/latest/tgw/nm-security-iam.html
*
* Applies to actions:
* - .toAssociateTransitGatewayConnectPeer()
* - .toDisassociateTransitGatewayConnectPeer()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifTgwConnectPeerArn(value: string | string[], operator?: Operator | string) {
return this.if(`tgwConnectPeerArn`, value, operator || 'StringLike');
}
} | the_stack |
import {ResourceBase, ResourceTag} from '../resource'
import {Value, List} from '../dataTypes'
export class TlsValidationContextSdsTrust {
SecretName!: Value<string>
constructor(properties: TlsValidationContextSdsTrust) {
Object.assign(this, properties)
}
}
export class ClientPolicyTls {
Validation!: TlsValidationContext
Enforce?: Value<boolean>
Ports?: List<Value<number>>
Certificate?: ClientTlsCertificate
constructor(properties: ClientPolicyTls) {
Object.assign(this, properties)
}
}
export class FileAccessLog {
Path!: Value<string>
constructor(properties: FileAccessLog) {
Object.assign(this, properties)
}
}
export class AwsCloudMapInstanceAttribute {
Value!: Value<string>
Key!: Value<string>
constructor(properties: AwsCloudMapInstanceAttribute) {
Object.assign(this, properties)
}
}
export class ListenerTlsValidationContext {
SubjectAlternativeNames?: SubjectAlternativeNames
Trust!: ListenerTlsValidationContextTrust
constructor(properties: ListenerTlsValidationContext) {
Object.assign(this, properties)
}
}
export class TcpTimeout {
Idle?: Duration
constructor(properties: TcpTimeout) {
Object.assign(this, properties)
}
}
export class Backend {
VirtualService?: VirtualServiceBackend
constructor(properties: Backend) {
Object.assign(this, properties)
}
}
export class ListenerTimeout {
TCP?: TcpTimeout
HTTP2?: HttpTimeout
HTTP?: HttpTimeout
GRPC?: GrpcTimeout
constructor(properties: ListenerTimeout) {
Object.assign(this, properties)
}
}
export class PortMapping {
Port!: Value<number>
Protocol!: Value<string>
constructor(properties: PortMapping) {
Object.assign(this, properties)
}
}
export class ListenerTls {
Validation?: ListenerTlsValidationContext
Mode!: Value<string>
Certificate!: ListenerTlsCertificate
constructor(properties: ListenerTls) {
Object.assign(this, properties)
}
}
export class ListenerTlsSdsCertificate {
SecretName!: Value<string>
constructor(properties: ListenerTlsSdsCertificate) {
Object.assign(this, properties)
}
}
export class BackendDefaults {
ClientPolicy?: ClientPolicy
constructor(properties: BackendDefaults) {
Object.assign(this, properties)
}
}
export class VirtualNodeTcpConnectionPool {
MaxConnections!: Value<number>
constructor(properties: VirtualNodeTcpConnectionPool) {
Object.assign(this, properties)
}
}
export class HttpTimeout {
PerRequest?: Duration
Idle?: Duration
constructor(properties: HttpTimeout) {
Object.assign(this, properties)
}
}
export class HealthCheck {
Path?: Value<string>
UnhealthyThreshold!: Value<number>
Port?: Value<number>
HealthyThreshold!: Value<number>
TimeoutMillis!: Value<number>
Protocol!: Value<string>
IntervalMillis!: Value<number>
constructor(properties: HealthCheck) {
Object.assign(this, properties)
}
}
export class AwsCloudMapServiceDiscovery {
NamespaceName!: Value<string>
ServiceName!: Value<string>
Attributes?: List<AwsCloudMapInstanceAttribute>
constructor(properties: AwsCloudMapServiceDiscovery) {
Object.assign(this, properties)
}
}
export class VirtualNodeHttpConnectionPool {
MaxConnections!: Value<number>
MaxPendingRequests?: Value<number>
constructor(properties: VirtualNodeHttpConnectionPool) {
Object.assign(this, properties)
}
}
export class ListenerTlsFileCertificate {
PrivateKey!: Value<string>
CertificateChain!: Value<string>
constructor(properties: ListenerTlsFileCertificate) {
Object.assign(this, properties)
}
}
export class TlsValidationContext {
SubjectAlternativeNames?: SubjectAlternativeNames
Trust!: TlsValidationContextTrust
constructor(properties: TlsValidationContext) {
Object.assign(this, properties)
}
}
export class VirtualNodeSpec {
Logging?: Logging
Backends?: List<Backend>
Listeners?: List<Listener>
BackendDefaults?: BackendDefaults
ServiceDiscovery?: ServiceDiscovery
constructor(properties: VirtualNodeSpec) {
Object.assign(this, properties)
}
}
export class Listener {
ConnectionPool?: VirtualNodeConnectionPool
Timeout?: ListenerTimeout
HealthCheck?: HealthCheck
TLS?: ListenerTls
PortMapping!: PortMapping
OutlierDetection?: OutlierDetection
constructor(properties: Listener) {
Object.assign(this, properties)
}
}
export class DnsServiceDiscovery {
Hostname!: Value<string>
ResponseType?: Value<string>
constructor(properties: DnsServiceDiscovery) {
Object.assign(this, properties)
}
}
export class TlsValidationContextFileTrust {
CertificateChain!: Value<string>
constructor(properties: TlsValidationContextFileTrust) {
Object.assign(this, properties)
}
}
export class GrpcTimeout {
PerRequest?: Duration
Idle?: Duration
constructor(properties: GrpcTimeout) {
Object.assign(this, properties)
}
}
export class VirtualNodeConnectionPool {
TCP?: VirtualNodeTcpConnectionPool
HTTP2?: VirtualNodeHttp2ConnectionPool
HTTP?: VirtualNodeHttpConnectionPool
GRPC?: VirtualNodeGrpcConnectionPool
constructor(properties: VirtualNodeConnectionPool) {
Object.assign(this, properties)
}
}
export class Logging {
AccessLog?: AccessLog
constructor(properties: Logging) {
Object.assign(this, properties)
}
}
export class ServiceDiscovery {
DNS?: DnsServiceDiscovery
AWSCloudMap?: AwsCloudMapServiceDiscovery
constructor(properties: ServiceDiscovery) {
Object.assign(this, properties)
}
}
export class Duration {
Value!: Value<number>
Unit!: Value<string>
constructor(properties: Duration) {
Object.assign(this, properties)
}
}
export class TlsValidationContextTrust {
SDS?: TlsValidationContextSdsTrust
ACM?: TlsValidationContextAcmTrust
File?: TlsValidationContextFileTrust
constructor(properties: TlsValidationContextTrust) {
Object.assign(this, properties)
}
}
export class ListenerTlsAcmCertificate {
CertificateArn!: Value<string>
constructor(properties: ListenerTlsAcmCertificate) {
Object.assign(this, properties)
}
}
export class VirtualNodeHttp2ConnectionPool {
MaxRequests!: Value<number>
constructor(properties: VirtualNodeHttp2ConnectionPool) {
Object.assign(this, properties)
}
}
export class ListenerTlsCertificate {
SDS?: ListenerTlsSdsCertificate
ACM?: ListenerTlsAcmCertificate
File?: ListenerTlsFileCertificate
constructor(properties: ListenerTlsCertificate) {
Object.assign(this, properties)
}
}
export class VirtualServiceBackend {
ClientPolicy?: ClientPolicy
VirtualServiceName!: Value<string>
constructor(properties: VirtualServiceBackend) {
Object.assign(this, properties)
}
}
export class OutlierDetection {
MaxEjectionPercent!: Value<number>
BaseEjectionDuration!: Duration
MaxServerErrors!: Value<number>
Interval!: Duration
constructor(properties: OutlierDetection) {
Object.assign(this, properties)
}
}
export class TlsValidationContextAcmTrust {
CertificateAuthorityArns!: List<Value<string>>
constructor(properties: TlsValidationContextAcmTrust) {
Object.assign(this, properties)
}
}
export class ClientPolicy {
TLS?: ClientPolicyTls
constructor(properties: ClientPolicy) {
Object.assign(this, properties)
}
}
export class ClientTlsCertificate {
SDS?: ListenerTlsSdsCertificate
File?: ListenerTlsFileCertificate
constructor(properties: ClientTlsCertificate) {
Object.assign(this, properties)
}
}
export class ListenerTlsValidationContextTrust {
SDS?: TlsValidationContextSdsTrust
File?: TlsValidationContextFileTrust
constructor(properties: ListenerTlsValidationContextTrust) {
Object.assign(this, properties)
}
}
export class AccessLog {
File?: FileAccessLog
constructor(properties: AccessLog) {
Object.assign(this, properties)
}
}
export class SubjectAlternativeNameMatchers {
Exact?: List<Value<string>>
constructor(properties: SubjectAlternativeNameMatchers) {
Object.assign(this, properties)
}
}
export class SubjectAlternativeNames {
Match!: SubjectAlternativeNameMatchers
constructor(properties: SubjectAlternativeNames) {
Object.assign(this, properties)
}
}
export class VirtualNodeGrpcConnectionPool {
MaxRequests!: Value<number>
constructor(properties: VirtualNodeGrpcConnectionPool) {
Object.assign(this, properties)
}
}
export interface VirtualNodeProperties {
MeshName: Value<string>
MeshOwner?: Value<string>
Spec: VirtualNodeSpec
VirtualNodeName?: Value<string>
Tags?: List<ResourceTag>
}
export default class VirtualNode extends ResourceBase<VirtualNodeProperties> {
static TlsValidationContextSdsTrust = TlsValidationContextSdsTrust
static ClientPolicyTls = ClientPolicyTls
static FileAccessLog = FileAccessLog
static AwsCloudMapInstanceAttribute = AwsCloudMapInstanceAttribute
static ListenerTlsValidationContext = ListenerTlsValidationContext
static TcpTimeout = TcpTimeout
static Backend = Backend
static ListenerTimeout = ListenerTimeout
static PortMapping = PortMapping
static ListenerTls = ListenerTls
static ListenerTlsSdsCertificate = ListenerTlsSdsCertificate
static BackendDefaults = BackendDefaults
static VirtualNodeTcpConnectionPool = VirtualNodeTcpConnectionPool
static HttpTimeout = HttpTimeout
static HealthCheck = HealthCheck
static AwsCloudMapServiceDiscovery = AwsCloudMapServiceDiscovery
static VirtualNodeHttpConnectionPool = VirtualNodeHttpConnectionPool
static ListenerTlsFileCertificate = ListenerTlsFileCertificate
static TlsValidationContext = TlsValidationContext
static VirtualNodeSpec = VirtualNodeSpec
static Listener = Listener
static DnsServiceDiscovery = DnsServiceDiscovery
static TlsValidationContextFileTrust = TlsValidationContextFileTrust
static GrpcTimeout = GrpcTimeout
static VirtualNodeConnectionPool = VirtualNodeConnectionPool
static Logging = Logging
static ServiceDiscovery = ServiceDiscovery
static Duration = Duration
static TlsValidationContextTrust = TlsValidationContextTrust
static ListenerTlsAcmCertificate = ListenerTlsAcmCertificate
static VirtualNodeHttp2ConnectionPool = VirtualNodeHttp2ConnectionPool
static ListenerTlsCertificate = ListenerTlsCertificate
static VirtualServiceBackend = VirtualServiceBackend
static OutlierDetection = OutlierDetection
static TlsValidationContextAcmTrust = TlsValidationContextAcmTrust
static ClientPolicy = ClientPolicy
static ClientTlsCertificate = ClientTlsCertificate
static ListenerTlsValidationContextTrust = ListenerTlsValidationContextTrust
static AccessLog = AccessLog
static SubjectAlternativeNameMatchers = SubjectAlternativeNameMatchers
static SubjectAlternativeNames = SubjectAlternativeNames
static VirtualNodeGrpcConnectionPool = VirtualNodeGrpcConnectionPool
constructor(properties: VirtualNodeProperties) {
super('AWS::AppMesh::VirtualNode', properties)
}
} | the_stack |
import { AfterViewInit, Component, Input, OnDestroy, OnInit, ViewChild } from '@angular/core';
import interact from 'interactjs';
import { Exercise } from 'app/entities/exercise.model';
import { Lecture } from 'app/entities/lecture.model';
import { DisplayPriority, PageType, SortDirection, VOTE_EMOJI_ID } from 'app/shared/metis/metis.util';
import { Course } from 'app/entities/course.model';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { combineLatest, map } from 'rxjs';
import { MetisService } from 'app/shared/metis/metis.service';
import { Post } from 'app/entities/metis/post.model';
import { Reaction } from 'app/entities/metis/reaction.model';
import { PostCreateEditModalComponent } from 'app/shared/metis/posting-create-edit-modal/post-create-edit-modal/post-create-edit-modal.component';
import { CourseManagementService } from 'app/course/manage/course-management.service';
import { HttpResponse } from '@angular/common/http';
import { faArrowLeft, faChevronLeft, faChevronRight, faGripLinesVertical, faLongArrowRight } from '@fortawesome/free-solid-svg-icons';
import { CourseDiscussionDirective } from 'app/shared/metis/course-discussion.directive';
import { FormBuilder } from '@angular/forms';
@Component({
selector: 'jhi-discussion-section',
templateUrl: './discussion-section.component.html',
styleUrls: ['./discussion-section.component.scss'],
providers: [MetisService],
})
export class DiscussionSectionComponent extends CourseDiscussionDirective implements OnInit, AfterViewInit, OnDestroy {
@Input() exercise?: Exercise;
@Input() lecture?: Lecture;
@ViewChild(PostCreateEditModalComponent) postCreateEditModal?: PostCreateEditModalComponent;
collapsed = false;
currentPostId?: number;
currentPost?: Post;
readonly pageType = PageType.PAGE_SECTION;
// Icons
faChevronRight = faChevronRight;
faChevronLeft = faChevronLeft;
faGripLinesVertical = faGripLinesVertical;
faArrowLeft = faArrowLeft;
faLongArrowRight = faLongArrowRight;
constructor(
protected metisService: MetisService,
private activatedRoute: ActivatedRoute,
private courseManagementService: CourseManagementService,
private router: Router,
private formBuilder: FormBuilder,
) {
super(metisService);
}
/**
* on initialization: initializes the metis service, fetches the posts for the exercise or lecture the discussion section is placed at,
* creates the subscription to posts to stay updated on any changes of posts in this course
*/
ngOnInit(): void {
this.paramSubscription = combineLatest({
params: this.activatedRoute.params,
queryParams: this.activatedRoute.queryParams,
}).subscribe((routeParams: { params: Params; queryParams: Params }) => {
const { params, queryParams } = routeParams;
const courseId = params.courseId;
this.currentPostId = +queryParams.postId;
this.courseManagementService.findOneForDashboard(courseId).subscribe((res: HttpResponse<Course>) => {
if (res.body !== undefined) {
this.course = res.body!;
this.metisService.setCourse(this.course!);
this.metisService.setPageType(this.pageType);
this.metisService.getFilteredPosts({
exerciseId: this.exercise?.id,
lectureId: this.lecture?.id,
});
this.createEmptyPost();
this.resetFormGroup();
}
});
});
this.postsSubscription = this.metisService.posts.pipe(map((posts: Post[]) => posts.sort(this.sectionSortFn))).subscribe((posts: Post[]) => {
this.posts = posts;
this.isLoading = false;
if (this.currentPostId && this.posts.length > 0) {
this.currentPost = this.posts.find((post) => post.id === this.currentPostId);
}
});
}
/**
* on leaving the page, the modal should be closed
*/
ngOnDestroy(): void {
super.onDestroy();
this.postCreateEditModal?.modalRef?.close();
}
/**
* on changing the sort direction via icon, the metis service is invoked to deliver the posts for the currently set context,
* sorted on the backend
*/
onChangeSortDir(): void {
switch (this.currentSortDirection) {
case undefined: {
this.currentSortDirection = SortDirection.ASCENDING;
break;
}
case SortDirection.ASCENDING: {
this.currentSortDirection = SortDirection.DESCENDING;
break;
}
default: {
this.currentSortDirection = undefined;
break;
}
}
this.posts.sort(this.sectionSortFn);
}
/**
* sorts posts by following criteria
* 1. criterion: displayPriority is PINNED -> pinned posts come first
* 2. criterion: displayPriority is ARCHIVED -> archived posts come last
* -- in between pinned and archived posts --
* 3. criterion (optional): creationDate - if activated by user through the sort arrow -> most recent comes at the end (chronologically from top to bottom)
* 4. criterion: if 3'rd criterion was not activated by the user, vote-emoji count -> posts with more vote-emoji counts comes first
* 5. criterion: most recent posts comes at the end (chronologically from top to bottom)
* @return Post[] sorted array of posts
*/
sectionSortFn = (postA: Post, postB: Post): number => {
// 1st criterion
if (postA.displayPriority === DisplayPriority.PINNED && postB.displayPriority !== DisplayPriority.PINNED) {
return -1;
}
if (postA.displayPriority !== DisplayPriority.PINNED && postB.displayPriority === DisplayPriority.PINNED) {
return 1;
}
// 2nd criterion
if (postA.displayPriority === DisplayPriority.ARCHIVED && postB.displayPriority !== DisplayPriority.ARCHIVED) {
return 1;
}
if (postA.displayPriority !== DisplayPriority.ARCHIVED && postB.displayPriority === DisplayPriority.ARCHIVED) {
return -1;
}
// 3rd criterion
if (!!this.currentSortDirection) {
const comparison = this.sortByDate(postA, postB, this.currentSortDirection);
if (comparison !== 0) {
return comparison;
}
}
// 4th criterion
const postAVoteEmojiCount = postA.reactions?.filter((reaction: Reaction) => reaction.emojiId === VOTE_EMOJI_ID).length ?? 0;
const postBVoteEmojiCount = postB.reactions?.filter((reaction: Reaction) => reaction.emojiId === VOTE_EMOJI_ID).length ?? 0;
if (postAVoteEmojiCount > postBVoteEmojiCount) {
return -1;
}
if (postAVoteEmojiCount < postBVoteEmojiCount) {
return 1;
}
// 5th criterion
return this.sortByDate(postA, postB, SortDirection.ASCENDING);
};
/**
* invoke metis service to create an empty default post that is needed on initialization of a modal to create a post,
* this empty post has either exercise or lecture set as context, depending on if this component holds an exercise or a lecture reference
*/
createEmptyPost(): void {
this.createdPost = this.metisService.createEmptyPostForContext(undefined, this.exercise, this.lecture);
}
/**
* defines a function that returns the post id as unique identifier,
* by this means, Angular determines which post in the collection of posts has to be reloaded/destroyed on changes
*/
postsTrackByFn = (index: number, post: Post): number => post.id!;
/**
* makes discussion section expandable by configuring 'interact'
*/
ngAfterViewInit(): void {
interact('.expanded-discussion')
.resizable({
edges: { left: '.draggable-left', right: false, bottom: false, top: false },
modifiers: [
// Set maximum width
interact.modifiers!.restrictSize({
min: { width: 375, height: 0 },
max: { width: 600, height: 4000 },
}),
],
inertia: true,
})
.on('resizestart', function (event: any) {
event.target.classList.add('card-resizable');
})
.on('resizeend', function (event: any) {
event.target.classList.remove('card-resizable');
})
.on('resizemove', function (event: any) {
const target = event.target;
target.style.width = event.rect.width + 'px';
});
}
/**
* sets the filter options after receiving user input
*/
setFilterAndSort(): void {
this.currentPostContextFilter = {
courseId: undefined,
exerciseId: this.exercise?.id,
lectureId: this.lecture?.id,
searchText: this.searchText,
filterToUnresolved: this.formGroup.get('filterToUnresolved')?.value,
filterToOwn: this.formGroup.get('filterToOwn')?.value,
filterToAnsweredOrReacted: this.formGroup.get('filterToAnsweredOrReacted')?.value,
};
}
resetCurrentPost() {
this.currentPost = undefined;
this.currentPostId = undefined;
this.router.navigate([], {
queryParams: {
postId: this.currentPostId,
},
queryParamsHandling: 'merge',
});
}
/**
* by default, the form group fields are set to show all posts of the current exercise or lecture
*/
resetFormGroup(): void {
this.formGroup = this.formBuilder.group({
exerciseId: this.exercise?.id,
lectureId: this.lecture?.id,
filterToUnresolved: false,
filterToOwn: false,
filterToAnsweredOrReacted: false,
});
}
/**
* helper method which returns the order which posts must be listed
* @param postA first post to compare
* @param postB second post to compare
* @return number the order which posts must be listed
*/
sortByDate = (postA: Post, postB: Post, sortDirection: SortDirection): number => {
if (Number(postA.creationDate) > Number(postB.creationDate)) {
return sortDirection === SortDirection.DESCENDING ? -1 : 1;
}
if (Number(postA.creationDate) < Number(postB.creationDate)) {
return sortDirection === SortDirection.DESCENDING ? 1 : -1;
}
return 0;
};
} | the_stack |
/**
* @license Copyright © 2019 onwards, Andrew Whewell
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
namespace VRS
{
/**
* Describes the settings and current state for a single map layer.
*/
export class MapLayerSetting
{
// Events
private _Dispatcher = new EventHandler({
name: 'VRS.MapLayerSetting'
});
private _Events = {
visibilityChanged: 'visibilityChanged',
opacityOverrideChanged: 'opacityOverrideChanged'
};
// Fields
private _TileServerSettings: ITileServerSettings;
private _Opacity: number;
private _Map: IMap;
private _DisplayOrder: number; // The ticks when the map was made visible. These can be compared to work out the order in which layers were made visible.
private _IsSuppressed: boolean; // True if this has been suppressed from display for some reason.
//
// Properties
get IsVisible(): boolean { return this._Map && this._Map.hasLayer(this.Name); }
get DisplayOrder(): number { return this.IsVisible ? this._DisplayOrder : -1; }
get TileServerSettings(): ITileServerSettings { return this._TileServerSettings; }
get Name(): string { return this._TileServerSettings.Name; }
get Opacity(): number { return this._Opacity === undefined ? this._TileServerSettings.DefaultOpacity : this._Opacity ; }
get OpacityDefault(): number { return this._TileServerSettings.DefaultOpacity; }
get OpacityOverride(): number { return this._Opacity; }
set OpacityOverride(value: number) {
var newOpacity = isNaN(value) || value === null || value === undefined || value === this._TileServerSettings.DefaultOpacity
? undefined
: Math.max(0, Math.min(100, value));
if(newOpacity !== this._Opacity) {
this._Opacity = newOpacity;
this.raiseOpacityOverrideChanged();
}
}
get IsSuppressed() : boolean { return this._IsSuppressed; }
set IsSuppressed(value: boolean) {
if(this._IsSuppressed != !!value) {
this._IsSuppressed = !!value;
if(this.IsSuppressed && this.IsVisible) {
this.hide();
}
}
}
//
// Event methods
hookVisibilityChanged(callback: (layer: MapLayerSetting) => void, forceThis?: Object) : IEventHandle
{
return this._Dispatcher.hook(this._Events.visibilityChanged, callback, forceThis);
}
private raiseVisibilityChanged()
{
this._Dispatcher.raise(this._Events.visibilityChanged, [ this ]);
}
hookOpacityOverrideChanged(callback: (layer: MapLayerSetting) => void, forceThis?: Object) : IEventHandle
{
return this._Dispatcher.hook(this._Events.opacityOverrideChanged, callback, forceThis);
}
private raiseOpacityOverrideChanged()
{
this._Dispatcher.raise(this._Events.opacityOverrideChanged, [ this ]);
}
unhook(hookResult: IEventHandle)
{
this._Dispatcher.unhook(hookResult);
}
//
// Ctor
constructor(map: IMap, tileServerSettings: ITileServerSettings)
{
this._Map = map;
this._TileServerSettings = tileServerSettings;
}
//
// Visibility methods
show()
{
if(!this.IsVisible && this._Map && !this.IsSuppressed) {
this._DisplayOrder = new Date().getTime();
this._Map.addLayer(this.TileServerSettings, this.OpacityOverride);
this.raiseVisibilityChanged();
}
}
hide()
{
if(this.IsVisible && this._Map) {
this._Map.destroyLayer(this.Name);
this.raiseVisibilityChanged();
}
}
toggleVisible()
{
if(this.IsVisible) {
this.hide();
} else {
this.show();
}
}
//
// Opacity methods
getMapOpacity()
{
return this.IsVisible ? this._Map.getLayerOpacity(this.Name) : this.Opacity;
}
setMapOpacity(value: number)
{
this.OpacityOverride = value;
if(this.IsVisible) {
this._Map.setLayerOpacity(this.Name, value);
}
}
}
// Saved state
export interface MapLayerManager_SaveState
{
// The names of the layouts visible at time of save. Order of names indicates order
// in which they were added to the map.
visibleLayouts: string[];
// Associative array of layout names and the opacity override associated with the name.
opacityOverrides: { [layoutName: string]: number };
}
// Records all of the event handles hooked for a map layer.
class HookHandles
{
opacityOverrideChangedEventHandle: IEventHandle;
visibilityChangedEventHandle: IEventHandle;
}
// Singleton object that handles the creation of map MapLayerSetting objects and persistence
// of their state.
export class MapLayerManager implements ISelfPersist<MapLayerManager_SaveState>
{
// Fields
private _Map: IMap;
private _MapLayerSettings: MapLayerSetting[] = [];
private _HookHandles: { [layoutName: string]: HookHandles } = {};
private _ConfigurationChangedHook: IEventHandle;
private _PersistenceKey = 'vrsMapLayerManager';
private _ApplyingState = false;
private _CustomMapLayerSettings: ITileServerSettings[] = [];
private _SuppressedMapLayers: string[] = [];
/**
* Called once to register a map to draw layers on.
* @param map
*/
registerMap(map: IMap)
{
this._Map = map;
this.buildMapLayerSettings();
this.loadAndApplyState();
this._ConfigurationChangedHook = VRS.globalDispatch.hook(VRS.globalEvent.serverConfigChanged, this.configurationChanged, this);
}
/**
* A method that lets custom content plugins register a layer settings directly instead
* of adding them to the custom tile server settings JSON file on the server.
* @param layerTileServerSettings
*/
registerCustomMapLayerSetting(layerTileServerSettings: ITileServerSettings)
{
if(layerTileServerSettings && layerTileServerSettings.IsLayer && layerTileServerSettings.Name) {
if(!VRS.arrayHelper.findFirst(this._MapLayerSettings, (r) => r.Name === layerTileServerSettings.Name) &&
!VRS.arrayHelper.findFirst(this._CustomMapLayerSettings, (r) => r.Name === layerTileServerSettings.Name)
) {
this._CustomMapLayerSettings.push(layerTileServerSettings);
this.buildMapLayerSettings();
this.loadAndApplyState();
}
}
}
/**
* Suppresses the use / display of a standard layer.
* @param layerName
*/
suppressStandardLayer(layerName: string)
{
if(layerName) {
if(VRS.arrayHelper.indexOf(this._SuppressedMapLayers, layerName) === -1) {
this._SuppressedMapLayers.push(layerName);
var layerTileServerSettings = VRS.arrayHelper.findFirst(this._MapLayerSettings, (r) => r.Name == layerName);
if(layerTileServerSettings) {
layerTileServerSettings.IsSuppressed = true;
}
}
}
}
/**
* Gets all known map layers.
*/
getMapLayerSettings() : MapLayerSetting[]
{
var result: MapLayerSetting[] = [];
$.each(this._MapLayerSettings, (idx, mapLayerSetting) => {
result.push(mapLayerSetting);
});
return result;
}
//
// State persistence methods
saveState()
{
if(!this._ApplyingState && this._Map) {
VRS.configStorage.save(this._PersistenceKey, this.createSettings());
}
}
loadState() : MapLayerManager_SaveState
{
var savedSettings = VRS.configStorage.load(this._PersistenceKey, {});
return $.extend(this.createSettings(), savedSettings);
}
applyState(settings: MapLayerManager_SaveState)
{
if(!this._ApplyingState && this._Map) {
try {
this._ApplyingState = true;
// Set opacities before making layers visible
$.each(this._MapLayerSettings, (idx, mapLayerSetting) => {
var opacityOverride = settings.opacityOverrides[mapLayerSetting.Name];
if(opacityOverride !== null && opacityOverride !== undefined && !isNaN(opacityOverride) && mapLayerSetting.OpacityOverride !== opacityOverride) {
mapLayerSetting.OpacityOverride = opacityOverride;
}
});
// Ensure all suppressed layers are flagged as suppressed before showing anything
$.each(this._SuppressedMapLayers, (idx, suppressedMapLayerName) => {
var mapLayer = VRS.arrayHelper.findFirst(this._MapLayerSettings, r => r.Name == suppressedMapLayerName);
if(mapLayer && !mapLayer.IsSuppressed) {
mapLayer.IsSuppressed = true;
}
});
// Ensure that layers are made visible in the same order that the user originally applied them
$.each(settings.visibleLayouts, (idx, visibleLayoutName) => {
var mapLayerSetting = VRS.arrayHelper.findFirst(this._MapLayerSettings, (r) => r.Name === visibleLayoutName);
if(mapLayerSetting && !mapLayerSetting.IsVisible) {
mapLayerSetting.show();
}
});
// I don't think I should hide layers that are already visible but aren't in the saved state... they were
// made visible by the user, I shouldn't override them.
} finally {
this._ApplyingState = false;
}
}
}
loadAndApplyState()
{
this.applyState(this.loadState());
}
private createSettings() : MapLayerManager_SaveState
{
var result: MapLayerManager_SaveState = {
visibleLayouts: [],
opacityOverrides: {}
};
this._MapLayerSettings.sort((lhs, rhs) => lhs.DisplayOrder - rhs.DisplayOrder);
$.each(this._MapLayerSettings, (idx, mapLayerSetting) => {
if(mapLayerSetting.IsVisible) {
result.visibleLayouts.push(mapLayerSetting.Name);
}
if(mapLayerSetting.OpacityOverride !== undefined) {
result.opacityOverrides[mapLayerSetting.Name] = mapLayerSetting.OpacityOverride;
}
});
return result;
}
/**
* Builds the _MapLayerSettings array of all known map layer settings, hooking new layers and
* unhooking & destroying old ones.
*/
private buildMapLayerSettings()
{
if(this._Map) {
var newMapLayerSettings: MapLayerSetting[] = [];
var tileServerSettings = VRS.serverConfig.get().TileServerLayers;
$.each(this._CustomMapLayerSettings, (idx, customTileServerSettings) => {
tileServerSettings.push(customTileServerSettings);
});
var len = tileServerSettings.length;
for(var i = 0;i < len;++i) {
var tileServerSetting = tileServerSettings[i];
var mapLayerSetting = VRS.arrayHelper.findFirst(this._MapLayerSettings, (r) => r.Name == tileServerSetting.Name);
if(!mapLayerSetting) {
mapLayerSetting = new MapLayerSetting(this._Map, tileServerSetting);
var hookHandles: HookHandles = {
opacityOverrideChangedEventHandle: mapLayerSetting.hookOpacityOverrideChanged(this.mapLayer_opacityChanged, this),
visibilityChangedEventHandle: mapLayerSetting.hookVisibilityChanged(this.mapLayer_visibilityChanged, this)
};
this._HookHandles[mapLayerSetting.Name] = hookHandles;
}
newMapLayerSettings.push(mapLayerSetting);
}
$.each(VRS.arrayHelper.except(this._MapLayerSettings, newMapLayerSettings, (lhs, rhs) => lhs.Name === rhs.Name), (idx, retiredMapLayer) => {
var hookHandles = this._HookHandles[retiredMapLayer.Name];
if(hookHandles) {
retiredMapLayer.unhook(hookHandles.opacityOverrideChangedEventHandle);
retiredMapLayer.unhook(hookHandles.visibilityChangedEventHandle);
delete this._HookHandles[retiredMapLayer.Name];
}
retiredMapLayer.hide();
});
this._MapLayerSettings = newMapLayerSettings;
}
}
/**
* Called when the server configuration changes.
*/
private configurationChanged()
{
this.buildMapLayerSettings();
this.loadAndApplyState();
}
/**
* Called when a map layer changes its opacity override.
* @param mapLayer
*/
private mapLayer_opacityChanged(mapLayer: MapLayerSetting)
{
this.saveState();
}
/**
* Called when a map layer changes its visibility.
* @param mapLayer
*/
private mapLayer_visibilityChanged(mapLayer: MapLayerSetting)
{
this.saveState();
}
}
export var mapLayerManager = new MapLayerManager();
} | the_stack |
import { BinaryReader } from "@core/utils/BinaryReader";
import { Z80CpuState } from "../../cpu/Z80Cpu";
import { MemoryHelper } from "../wa-interop/memory-helpers";
import {
BEEPER_SAMPLE_BUFFER,
COLORIZATION_BUFFER,
PSG_SAMPLE_BUFFER,
RENDERING_TACT_TABLE,
SPECTRUM_MACHINE_STATE_BUFFER,
} from "../wa-interop/memory-map";
import { MachineCreationOptions, MachineState } from "../../../core/abstractions/vm-core-types";
import { Z80MachineCoreBase } from "../core/Z80MachineCoreBase";
import { TzxReader } from "./tzx-file";
import { TapReader } from "./tap-file";
import { IAudioRenderer } from "../audio/IAudioRenderer";
import { IZxSpectrumStateManager } from "./IZxSpectrumStateManager";
import { KeyMapping } from "../core/keyboard";
import { spectrumKeyCodes, spectrumKeyMappings } from "./spectrum-keys";
import { ProgramCounterInfo } from "@state/AppState";
import { getEngineDependencies } from "../core/vm-engine-dependencies";
import { CodeToInject } from "@abstractions/code-runner-service";
/**
* ZX Spectrum common core implementation
*/
export abstract class ZxSpectrumCoreBase extends Z80MachineCoreBase {
// --- Tape emulation
private _defaultTapeSet = new Uint8Array(0);
// --- Beeper emulation
private _beeperRenderer: IAudioRenderer | null = null;
// --- PSG emulation
private _psgRenderer: IAudioRenderer | null = null;
// --- A factory method for audio renderers
private _audioRendererFactory: (sampleRate: number) => IAudioRenderer;
// --- A state manager instance
private _stateManager: IZxSpectrumStateManager;
/**
* Instantiates a core with the specified options
* @param options Options to use with machine creation
*/
constructor(options: MachineCreationOptions) {
super(options);
const deps = getEngineDependencies();
this._audioRendererFactory = deps.audioRendererFactory;
this._stateManager = deps.spectrumStateManager;
}
/**
* Get the type of the keyboard to display
*/
readonly keyboardType: string | null = "sp48";
/**
* Indicates if this model supports the AY-3-8912 PSG chip
*/
get supportsPsg(): boolean {
return false;
}
/**
* Gets the program counter information of the machine
* @param state Current machine state
*/
getProgramCounterInfo(state: SpectrumMachineStateBase): ProgramCounterInfo {
return {
label: "PC",
value: state._pc,
};
}
/**
* Optional import properties for the WebAssembly engine
*/
readonly waImportProps: Record<string, any> = {
saveModeLeft: (length: number) => {
this.storeSavedDataInState(length);
},
};
/**
* Creates the CPU instance
*/
configureMachine(): void {
super.configureMachine();
const deps = getEngineDependencies();
this.setAudioSampleRate(deps.sampleRateGetter());
}
/**
* Sets the audio sample rate to use with sound devices
* @param rate Audio sampe rate to use
*/
setAudioSampleRate(rate: number): void {
this.api.setAudioSampleRate(rate);
}
/**
* Gets the screen data of the ZX Spectrum machine
*/
getScreenData(): Uint32Array {
const state = this.getMachineState() as SpectrumMachineStateBase;
const buffer = this.api.memory.buffer as ArrayBuffer;
const length = state.screenHeight * state.screenWidth;
const screenData = new Uint32Array(
buffer.slice(COLORIZATION_BUFFER, COLORIZATION_BUFFER + 4 * length)
);
return screenData;
}
/**
* Represents the state of the machine, including the CPU, memory, and machine
* devices
*/
getMachineState(): SpectrumMachineStateBase {
// --- Obtain execution engine state
const cpuState = this.cpu.getCpuState();
const engineState = super.getMachineState();
const s = { ...cpuState, ...engineState } as SpectrumMachineStateBase;
// --- Obtain ZX Spectrum specific state
this.api.getMachineState();
let mh = new MemoryHelper(this.api, SPECTRUM_MACHINE_STATE_BUFFER);
// --- Get port state
s.portBit3LastValue = mh.readBool(0);
s.portBit4LastValue = mh.readBool(1);
s.portBit4ChangedFrom0Tacts = mh.readUint32(2);
s.portBit4ChangedFrom1Tacts = mh.readUint32(6);
// --- Get keyboard state
s.keyboardLines = [];
for (let i = 0; i < 8; i++) {
s.keyboardLines[i] = mh.readByte(10 + i);
}
// --- Interrupt state
s.interruptTact = mh.readUint16(18);
s.interruptEndTact = mh.readUint16(20);
// --- Memory state
s.numberOfRoms = mh.readByte(22);
s.ramBanks = mh.readByte(23);
s.memorySelectedRom = mh.readByte(24);
s.memoryPagingEnabled = mh.readBool(25);
s.memorySelectedBank = mh.readByte(26);
s.memoryUseShadowScreen = mh.readBool(27);
s.memoryScreenOffset = mh.readUint16(28);
// --- Screen device state
s.verticalSyncLines = mh.readUint16(30);
s.nonVisibleBorderTopLines = mh.readUint16(32);
s.borderTopLines = mh.readUint16(34);
s.displayLines = mh.readUint16(36);
s.borderBottomLines = mh.readUint16(38);
s.nonVisibleBorderBottomLines = mh.readUint16(40);
s.horizontalBlankingTime = mh.readUint16(42);
s.borderLeftTime = mh.readUint16(44);
s.displayLineTime = mh.readUint16(46);
s.borderRightTime = mh.readUint16(48);
s.nonVisibleBorderRightTime = mh.readUint16(50);
s.pixelDataPrefetchTime = mh.readUint16(52);
s.attributeDataPrefetchTime = mh.readUint16(54);
// --- Get calculated screen attributes
s.firstDisplayLine = mh.readUint32(56);
s.lastDisplayLine = mh.readUint32(60);
s.borderLeftPixels = mh.readUint32(64);
s.borderRightPixels = mh.readUint32(68);
s.displayWidth = mh.readUint32(72);
s.screenLineTime = mh.readUint32(76);
s.rasterLines = mh.readUint32(80);
s.firstDisplayPixelTact = mh.readUint32(84);
s.firstScreenPixelTact = mh.readUint32(88);
s.screenWidth = mh.readUint32(92);
s.screenHeight = mh.readUint32(96);
// --- Get screen state
s.borderColor = mh.readByte(100);
s.flashPhase = mh.readBool(101);
s.pixelByte1 = mh.readByte(102);
s.pixelByte2 = mh.readByte(103);
s.attrByte1 = mh.readByte(104);
s.attrByte2 = mh.readByte(105);
s.flashFrames = mh.readByte(106);
s.renderingTablePtr = mh.readUint32(107);
s.pixelBufferPtr = mh.readUint32(111);
// --- Get beeper state
s.audioSampleRate = mh.readUint32(115);
s.audioSampleLength = mh.readUint32(119);
s.audioLowerGate = mh.readUint32(123);
s.audioUpperGate = mh.readUint32(127);
s.audioGateValue = mh.readUint32(131);
s.audioNextSampleTact = mh.readUint32(135);
s.audioSampleCount = mh.readUint32(139);
s.beeperLastEarBit = mh.readBool(143);
// --- Get tape device state
s.tapeMode = mh.readByte(144);
s.tapeBlocksToPlay = mh.readUint16(145);
s.tapeEof = mh.readBool(147);
s.tapeBufferPtr = mh.readUint32(148);
s.tapeNextBlockPtr = mh.readUint32(152);
s.tapePlayPhase = mh.readByte(156);
s.tapeStartTactL = mh.readUint32(157);
s.tapeStartTactH = mh.readUint32(161);
s.tapeFastLoad = mh.readBool(165);
s.tapeSavePhase = mh.readByte(166);
// --- Engine state
s.ulaIssue = mh.readByte(167);
s.contentionAccumulated = mh.readUint32(168);
s.lastExecutionContentionValue = mh.readUint32(172);
// --- Screen rendering tact
mh = new MemoryHelper(this.api, RENDERING_TACT_TABLE);
const tactStart = 5 * s.lastRenderedFrameTact;
s.renderingPhase = mh.readByte(tactStart);
s.pixelAddr = mh.readUint16(tactStart + 1);
s.attrAddr = mh.readUint16(tactStart + 3);
// --- Done.
return s;
}
/**
* Gets the key mapping used by the machine
*/
getKeyMapping(): KeyMapping {
return spectrumKeyMappings;
}
/**
* Resolves a string key code to a key number
* @param code Key code to resolve
*/
resolveKeyCode(code: string): number | null {
return spectrumKeyCodes[code] ?? null;
}
/**
* Override this method to set the clock multiplier
* @param multiplier Clock multiplier to apply from the next frame
*/
setClockMultiplier(multiplier: number): void {
this.api.setClockMultiplier(multiplier);
}
/**
* Gets the cursor mode of the ZX Spectrum machine
* @returns
*/
getCursorMode(): number {
return this.api.getCursorMode();
}
/**
* Indicates if the virtual machine supports code injection for the specified
* machine mode
* @param mode Optional machine mode
* @returns True, if the model supports the code injection
*/
supportsCodeInjection(mode?: string): boolean {
return true;
}
/**
* Initializes the machine with the specified code
* @param runMode Machine run mode
* @param code Intial code
*/
injectCode(
code: number[],
codeAddress = 0x8000,
startAddress = 0x8000
): void {
for (let i = 0; i < code.length; i++) {
this.writeMemory(codeAddress++, code[i]);
}
let ptr = codeAddress;
while (ptr < 0x10000) {
this.writeMemory(ptr++, 0);
}
// --- Init code execution
this.api.resetCpu(true);
this.api.setPC(startAddress);
}
/**
* Injects the specified code into the ZX Spectrum machine
* @param codeToInject Code to inject into the machine
*/
async injectCodeToRun(codeToInject: CodeToInject): Promise<void> {
for (const segment of codeToInject.segments) {
if (segment.bank !== undefined) {
// TODO: Implement this
} else {
const addr = segment.startAddress;
for (let i = 0; i < segment.emittedCode.length; i++) {
this.writeMemory(addr + i, segment.emittedCode[i]);
}
}
}
// --- Prepare the run mode
if (codeToInject.options.cursork) {
// --- Set the keyboard in "L" mode
this.writeMemory(0x5c3b, this.readMemory(0x5c3b) | 0x08);
}
}
/**
* Prepares the engine for code injection
* @param _model Model to run in the virtual machine
*/
async prepareForInjection(_model: string): Promise<number> {
return 0;
}
/**
* Injects the specified code into the ZX Spectrum machine and runs it
* @param codeToInject Code to inject into the machine
* @param debug Start in debug mode?
*/
async runCode(codeToInject: CodeToInject, debug?: boolean): Promise<void> {
const controller = this.controller;
// --- Stop the running machine
await controller.stop();
// --- Start the machine and run it while it reaches the injection point
let mainExec = await this.prepareForInjection(codeToInject.model);
// --- Inject to code
await this.injectCodeToRun(codeToInject);
// --- Set the continuation point
const startPoint =
codeToInject.entryAddress ?? codeToInject.segments[0].startAddress;
this.api.setPC(startPoint);
// --- Handle subroutine calls
if (codeToInject.subroutine) {
const spValue = this.getMachineState().sp;
this.writeMemory(spValue - 1, mainExec >> 8);
this.writeMemory(spValue - 2, mainExec & 0xff);
this.api.setSP(spValue - 2);
}
await this.beforeRunInjected(codeToInject, debug);
if (debug) {
await controller.startDebug();
} else {
await controller.start();
}
}
/**
* Extracts saved data
* @param length Data length
*/
storeSavedDataInState(length: number): void {
// if (!vmEngine) {
// return;
// }
// const mh = new MemoryHelper(vmEngine.z80Machine.api, TAPE_SAVE_BUFFER);
// const savedData = new Uint8Array(mh.readBytes(0, length));
// rendererProcessStore.dispatch(emulatorSetSavedDataAction(savedData)());
}
// ==========================================================================
// Lifecycle methods
/**
* Read the default tape contents before the first start
*/
async beforeFirstStart(): Promise<void> {
super.beforeFirstStart();
await this.initTapeContents();
}
/**
* Override this method to define an action when the virtual machine has
* started.
* @param debugging Is started in debug mode?
*/
async beforeStarted(debugging: boolean): Promise<void> {
await super.beforeStarted(debugging);
// --- Init audio renderers
const state = this.getMachineState() as SpectrumMachineStateBase;
this._beeperRenderer = this._audioRendererFactory(
state.tactsInFrame / state.audioSampleLength
);
this._beeperRenderer.suspend();
await this._beeperRenderer.initializeAudio();
if (this.supportsPsg) {
this._psgRenderer = this._audioRendererFactory(
state.tactsInFrame / state.audioSampleLength
);
this._psgRenderer.suspend();
await this._psgRenderer.initializeAudio();
}
}
/**
* Stops audio when the machine has paused
* @param isFirstPause Is the machine paused the first time?
*/
async onPaused(isFirstPause: boolean): Promise<void> {
await super.onPaused(isFirstPause);
this.cleanupAudio();
}
/**
* Stops audio when the machine has stopped
*/
async onStopped(): Promise<void> {
await super.onStopped();
this.cleanupAudio();
}
/**
* Takes care that the screen and the audio gets refreshed as a frame
* completes
* @param resultState Machine state on frame completion
*/
async onFrameCompleted(
resultState: SpectrumMachineStateBase,
toWait: number
): Promise<void> {
if (toWait > 0) {
this.api.colorize();
this.controller.signScreenRefreshed();
}
// --- At this point we have not completed the execution yet
// --- Initiate the refresh of the screen
// --- Update load state
const appState = this._stateManager.getState();
const emuState = appState.emulatorPanel;
const spectrumState = appState.spectrumSpecific;
this._stateManager.setLoadMode(resultState.tapeMode === 1);
this.api.setFastLoad(spectrumState.fastLoad);
// --- Obtain beeper samples
let mh = new MemoryHelper(this.api, BEEPER_SAMPLE_BUFFER);
const beeperSamples = mh
.readBytes(0, resultState.audioSampleCount)
.map((smp) => (emuState.muted ? 0 : smp * (emuState.soundLevel ?? 0)));
this._beeperRenderer.storeSamples(beeperSamples);
this._beeperRenderer.resume();
// --- Obtain psg samples
if (this.supportsPsg) {
mh = new MemoryHelper(this.api, PSG_SAMPLE_BUFFER);
const psgSamples = mh
.readWords(0, resultState.audioSampleCount)
.map((smp) =>
emuState.muted ? 0 : (smp / 65535) * (emuState.soundLevel ?? 0)
);
this._psgRenderer.storeSamples(psgSamples);
this._psgRenderer.resume();
}
// --- Check if a tape should be loaded
if (
resultState.tapeMode === 0 &&
!spectrumState.tapeLoaded &&
spectrumState.tapeContents &&
spectrumState.tapeContents.length > 0
) {
// --- The tape is in passive mode, and we have a new one we can load, so let's load it
this._defaultTapeSet = spectrumState.tapeContents;
const binaryReader = new BinaryReader(this._defaultTapeSet);
this.initTape(binaryReader);
this._stateManager.initiateTapeLoading();
}
}
// ==========================================================================
// Helpers
async initTapeContents(message?: string): Promise<void> {
const state = this._stateManager.getState();
// --- Set tape contents
if (
!state.spectrumSpecific.tapeContents ||
state.spectrumSpecific.tapeContents.length === 0
) {
let contents = new Uint8Array(0);
try {
contents = await this.readFromStream("./tapes/Pac-Man.tzx");
} catch (err) {
console.log(`Load error: ${err}`);
}
this._defaultTapeSet = contents;
} else {
this._defaultTapeSet = state.spectrumSpecific.tapeContents;
}
this._stateManager.setTapeContents(this._defaultTapeSet);
const binaryReader = new BinaryReader(this._defaultTapeSet);
this.initTape(binaryReader);
if (message) {
(async () => {
this._stateManager.setPanelMessage(message);
await new Promise((r) => setTimeout(r, 3000));
this._stateManager.setPanelMessage("");
})();
}
}
/**
* Initializes the tape from the specified binary reader
* @param reader Reader to use
*/
private initTape(reader: BinaryReader): boolean {
const tzxReader = new TzxReader(reader);
if (tzxReader.readContents()) {
const blocks = tzxReader.sendTapeFileToEngine(this.api);
this.api.initTape(blocks);
return true;
}
reader.seek(0);
const tapReader = new TapReader(reader);
if (tapReader.readContents()) {
const blocks = tapReader.sendTapeFileToEngine(this.api);
this.api.initTape(blocks);
return true;
}
return false;
}
/**
* Read data from the specified URI
* @param uri URI to read form
*/
async readFromStream(uri: string): Promise<Uint8Array> {
const buffers: Uint8Array[] = [];
const data = await fetch(uri);
let done = false;
const reader = data.body.getReader();
do {
const read = await reader.read();
if (read.value) {
buffers.push(read.value);
}
done = read.done;
} while (!done);
const length = buffers.reduce((a, b) => a + b.length, 0);
const resultArray = new Uint8Array(length);
let offset = 0;
for (let i = 0; i < buffers.length; i++) {
resultArray.set(buffers[i], offset);
offset += buffers[i].length;
}
return resultArray;
}
/**
* Cleans up audio
*/
async cleanupAudio(): Promise<void> {
if (this._beeperRenderer) {
await this._beeperRenderer.closeAudio();
this._beeperRenderer = null;
}
if (this.supportsPsg && this._psgRenderer) {
await this._psgRenderer.closeAudio();
this._psgRenderer = null;
}
}
}
/**
* Represents the state of the ZX Spectrum machine
*/
export interface SpectrumMachineStateBase extends MachineState, Z80CpuState {
// --- Port $fe state
portBit3LastValue: boolean;
portBit4LastValue: boolean;
portBit4ChangedFrom0Tacts: number;
portBit4ChangedFrom1Tacts: number;
// --- Keyboard state
keyboardLines: number[];
// --- Interrupt configuration
interruptTact: number;
interruptEndTact: number;
// --- Memory state
numberOfRoms: number;
ramBanks: number;
memorySelectedRom: number;
memorySelectedBank: number;
memoryPagingEnabled: boolean;
memoryUseShadowScreen: boolean;
memoryScreenOffset: number;
// --- Screen frame configuration
verticalSyncLines: number;
nonVisibleBorderTopLines: number;
borderTopLines: number;
displayLines: number;
borderBottomLines: number;
nonVisibleBorderBottomLines: number;
horizontalBlankingTime: number;
borderLeftTime: number;
displayLineTime: number;
borderRightTime: number;
nonVisibleBorderRightTime: number;
pixelDataPrefetchTime: number;
attributeDataPrefetchTime: number;
// --- Calculated screen data
firstDisplayLine: number;
lastDisplayLine: number;
borderLeftPixels: number;
borderRightPixels: number;
displayWidth: number;
screenLineTime: number;
rasterLines: number;
firstDisplayPixelTact: number;
firstScreenPixelTact: number;
// --- Screen state
borderColor: number;
flashPhase: boolean;
pixelByte1: number;
pixelByte2: number;
attrByte1: number;
attrByte2: number;
flashFrames: number;
renderingTablePtr: number;
pixelBufferPtr: number;
lastRenderedFrameTact: number;
// --- Beeper state
audioSampleRate: number;
audioSampleLength: number;
audioLowerGate: number;
audioUpperGate: number;
audioGateValue: number;
audioNextSampleTact: number;
audioSampleCount: number;
beeperLastEarBit: boolean;
// --- Tape state
tapeMode: number;
tapeBlocksToPlay: number;
tapeEof: boolean;
tapeBufferPtr: number;
tapeNextBlockPtr: number;
tapePlayPhase: number;
tapeStartTactL: number;
tapeStartTactH: number;
tapeFastLoad: boolean;
tapeSavePhase: number;
// --- Engine state
ulaIssue: number;
contentionAccumulated: number;
lastExecutionContentionValue: number;
// --- Sound state
psgSupportsSound: boolean;
psgRegisterIndex: number;
psgClockStep: number;
psgNextClockTact: number;
psgOrphanSamples: number;
psgOrphanSum: number;
// --- Screen rendering tact
renderingPhase: number;
pixelAddr: number;
attrAddr: number;
} | the_stack |
import { Component, ViewChild, ViewChildren, QueryList, Input } from '@angular/core';
import { AlertController, PopoverController, Events } from 'ionic-angular';
import { LoadingService } from '../../../services/loading/loading.service';
import { ToastService } from '../../../services/toast/toast.service';
import 'rxjs/Rx';
//Components
import { DropdownPopoverComponent } from '../../dropdown-popover/dropdown-popover.component';
import { ProfilePopover } from '../../../components/profile-popover/profile-popover.component';
//Services
import { DeviceManagerService, DeviceService } from 'dip-angular2/services';
import { UtilityService } from '../../../services/utility/utility.service';
import { LoggerPlotService } from '../../../services/logger-plot/logger-plot.service';
import { ExportService } from '../../../services/export/export.service';
import { SettingsService } from '../../../services/settings/settings.service';
import { TooltipService } from '../../../services/tooltip/tooltip.service';
import { ScalingService } from '../../../services/scaling/scaling.service';
//Interfaces
import { PlotDataContainer } from '../../../services/logger-plot/logger-plot.service';
import { ScaleParams } from '../../../services/scaling/scaling.service';
import { LoggerXAxisComponent } from '../../logger-xaxis/logger-xaxis.component';
import { ChannelSelectPopover } from '../../channel-select-popover/channel-select-popover.component';
import { LogScalePopover } from '../../log-scale-popover/log-scale-popover.component';
@Component({
templateUrl: 'openlogger-logger.html',
selector: 'openlogger-logger-component'
})
export class OpenLoggerLoggerComponent {
@ViewChild('dropPopMode') modeChild: DropdownPopoverComponent;
@ViewChild('dropPopProfile') profileChild: DropdownPopoverComponent;
@ViewChild('dropPopLogTo') logToChild: DropdownPopoverComponent;
@ViewChild('xaxis') xAxis: LoggerXAxisComponent;
@ViewChildren('dropPopScaling') scalingChildren: QueryList<DropdownPopoverComponent>;
@Input() colorArray: any;
private activeDevice: DeviceService;
public showLoggerSettings: boolean = true;
public showAdvSettings: boolean = false;
public selectedChannels: boolean[] = [];
private defaultDaqParams: DaqLoggerParams = {
maxSampleCount: -1,
startDelay: 0,
sampleFreq: 500000,
storageLocation: 'ram',
logOnBoot: true,
service: '',
apiKey: '',
uri: ''
};
private daqParams: DaqLoggerParams = Object.assign({}, this.defaultDaqParams);
private defaultDaqChannelParams: DaqChannelParams = {
average: 1,
vOffset: 0
};
public daqChans: DaqChannelParams[] = [];
public loggerState: string = 'idle';
public averagingEnabled: boolean = false;
public maxAverage: number = 256;
public startIndex: number = 0;
public count: number = 0;
private daqChanNumbers: number[] = [];
public logToLocations: string[] = ['chart'];
public logAndStream: boolean = false;
public modes: ('continuous' | 'finite')[] = ['continuous', 'finite'];
public selectedMode: 'continuous' | 'finite' = this.modes[0];
public selectedLogLocation: string = this.logToLocations[0];
public storageLocations: string[] = [];
public cloudServices: string[] = ['ThingSpeak'];
public selectedCloudService: string = this.cloudServices[0];
public loggingProfiles: string[] = ['New Profile'];
public selectedLogProfile: string = this.loggingProfiles[0];
private dirtyProfile: boolean = false;
private profileObjectMap: any = {};
public running: boolean = false;
public dataContainers: PlotDataContainer[] = [];
public viewMoved: boolean = false;
private daqChansToRead: number[] = [];
private chartPanSubscriptionRef;
private offsetChangeSubscriptionRef;
private scalingOptions: string[] = ['None'];
private selectedScales: string[];
private unitTransformer: any[] = [];
private filesInStorage: any = {};
private destroyed: boolean = false;
public dataAvailable: boolean = false;
private chanSelectTimer;
public messageQueue: any[] = [];
private nicStatus: string = 'disconnected';
private channelId: number;
private thingSpeakBaseUrl = 'http://api.thingspeak.com/channels/';
private thingSpeakResourcePath = '/bulk_update.json';
constructor(
private devicemanagerService: DeviceManagerService,
private loadingService: LoadingService,
private toastService: ToastService,
private utilityService: UtilityService,
public loggerPlotService: LoggerPlotService,
private exportService: ExportService,
private alertCtrl: AlertController,
private settingsService: SettingsService,
public tooltipService: TooltipService,
private popoverCtrl: PopoverController,
public events: Events,
private scalingService: ScalingService
) {
this.activeDevice = this.devicemanagerService.devices[this.devicemanagerService.activeDeviceIndex];
console.log(this.activeDevice.instruments.logger);
let loading = this.loadingService.displayLoading('Loading device info...');
this.init();
this.loadDeviceInfo()
.then(() => {
loading.dismiss();
if (this.running) {
this.continueStream();
}
this.getProfileFromStorage();
})
.catch((e) => {
console.log(e);
this.toastService.createToast('deviceDroppedConnection', true, undefined, 5000);
loading.dismiss();
});
this.chanUnits = this.daqChans.map(() => 'V');
this.events.subscribe('profile:save', (params) => {
this.saveAndSetProfile(params[0]['profileName'], params[0]['saveChart'], params[0]['saveDaq']);
});
this.events.subscribe('profile:delete', (params) => {
this.deleteProfile(params[0]['profileName']);
});
this.events.subscribe('channels:selected', (params) => {
this.selectChannels(params[0]['channels']);
});
this.events.subscribe('scale:update', (event) => {
let params = event[0]['params'];
let channel = event[0]['channel'];
this.updateScale(channel, params['expression'], params['name'], params['unitDescriptor']);
});
this.events.subscribe('scale:delete', (params) => {
this.deleteScale(params[0]['channel'], params[0]['name']);
});
}
public selectChannels(selectedChans: boolean[]) {
this.selectedChannels = selectedChans;
window.clearTimeout(this.chanSelectTimer);
if (this.selectedChannels.indexOf(true) > -1) {
let currentVal = this.daqParams.sampleFreq;
let newVal = this.validateAndApply(this.daqParams.sampleFreq, 'sampleFreq');
if (currentVal > newVal) {
this.chanSelectTimer = window.setTimeout(() => {
let numChans = this.selectedChannels.lastIndexOf(true) + 1;
let chanObj = this.activeDevice.instruments.logger.daq.chans[0];
let maxAggregate = this.getMaxSampleFreq();
let maxFreq = Math.floor(maxAggregate / numChans) * chanObj.sampleFreqUnits;
this.toastService.createToast('loggerSampleFreqMax', true, Math.round((maxFreq / 1000) * 100) / 100 + ' kS/s', 5000);
}, 1500);
}
}
}
chanUnits: string[] = []; // start w/ 'V' for all the channels
public updateScale(chan: number, expression: string, scaleName: string, units: string) {
this.selectedScales[chan] = scaleName;
this.selectedScales.forEach((chanScale, index) => {
if (chanScale == scaleName) {
this.unitTransformer[index] = expression;
this.events.publish('units:update', { channel: index, units: units });
}
});
// add name to list if new
if (this.scalingOptions.indexOf(scaleName) === -1) {
this.scalingOptions.push(scaleName);
}
// set dropdown selection
setTimeout(() => {
this.scalingChildren.toArray()[chan]._applyActiveSelection(scaleName);
}, 20);
}
public deleteScale(chan: number, scaleName: string) {
this.unitTransformer[chan] = undefined;
// remove name from list
let nameIndex: number = this.scalingOptions.indexOf(scaleName);
if (nameIndex !== -1) {
this.scalingOptions.splice(nameIndex, 1);
}
// update any channels that were set to the delete option
this.selectedScales.forEach((chanScale, index) => {
if (chanScale == scaleName) {
this.selectedScales[index] = this.scalingOptions[0];
this.events.publish('units:update', { channel: index });
}
});
}
ngDoCheck() {
// Check if there are unsaved changes to profile
this.dirtyProfile = false;
if (this.selectedLogProfile && this.selectedLogProfile != this.loggingProfiles[0]) {
let current = this.generateProfileJson(this.profileObjectMap[this.selectedLogProfile].chart, this.profileObjectMap[this.selectedLogProfile].daq);
this.dirtyProfile = JSON.stringify(current) !== JSON.stringify(this.profileObjectMap[this.selectedLogProfile]);
}
}
ngOnDestroy() {
this.settingsService.saveLoggerProfile(this.activeDevice.macAddress, this.selectedLogProfile);
this.clearChart();
this.chartPanSubscriptionRef.unsubscribe();
this.offsetChangeSubscriptionRef.unsubscribe();
this.events.unsubscribe('profile:save');
this.events.unsubscribe('profile:delete');
this.events.unsubscribe('channels:selected');
this.events.unsubscribe('scale:update');
this.events.unsubscribe('scale:delete');
this.running = false;
this.destroyed = true;
}
private init() {
this.chartPanSubscriptionRef = this.loggerPlotService.chartPan.subscribe(
(data) => {
if (this.running) {
this.viewMoved = true;
}
},
(err) => { },
() => { }
);
this.offsetChangeSubscriptionRef = this.loggerPlotService.offsetChange.subscribe(
(data) => {
if (data.axisNum > this.daqChans.length - 1) {
//Digital
return;
}
else {
this.daqChans[data.axisNum].vOffset = data.offset;
}
},
(err) => { },
() => { }
);
for (let i = 0; i < this.activeDevice.instruments.logger.daq.numChans; i++) {
this.daqChans.push(Object.assign({}, this.defaultDaqChannelParams));
}
for (let i = 0; i < this.daqChans.length; i++) {
this.daqChanNumbers.push(i + 1);
this.dataContainers.push({
data: [],
yaxis: i + 1,
lines: {
show: true
},
points: {
show: false
},
seriesOffset: 0
});
}
this.selectedChannels = Array.apply(null, Array(this.daqChans.length)).map(() => false);
// load saved scaling functions
this.scalingService.getAllScalingOptions()
.then((result: ScaleParams[]) => {
result.forEach((option) => {
this.scalingOptions.push(option.name);
});
})
.catch((e) => {
console.log(e);
});
this.selectedScales = Array.apply(null, Array(this.daqChans.length)).map(() => this.scalingOptions[0]);
}
private loadDeviceInfo(): Promise<any> {
return new Promise((resolve, reject) => {
this.getStorageLocations()
.then((data) => {
console.log(data);
this.storageLocations.unshift('ram'); // openlogger doesn't report ram as storage location, but always will have it
if (data && data.device && data.device[0]) {
let fwVer = this.activeDevice.firmwareVersion;
data.device[0].storageLocations.forEach((el, index, arr) => {
if (el !== 'flash') {
this.storageLocations.unshift(el);
this.filesInStorage[el] = [];
}
if (/^sd/g.test(el) && this.logToLocations.indexOf('SD') === -1 &&
((fwVer.major === 0 && fwVer.minor >= 1719) || fwVer.major >= 1)) { // only push SD as a location if the firmware supports it
this.logToLocations.push('SD');
}
});
if (this.logToLocations.indexOf('cloud') === -1 && ((fwVer.major === 0 && fwVer.minor >= 1877) || fwVer.major >= 1)) { // only push cloud as a location if the firmware supports it
this.storageLocations.unshift('cloud'); // openlogger doesn't report cloud as storage location
this.logToLocations.push('cloud');
}
}
if (this.storageLocations.length < 1) {
this.logToLocations = ['chart'];
this.logToSelect('chart');
return new Promise((resolve, reject) => { resolve(); });
}
else {
return new Promise((resolve, reject) => {
this.storageLocations.reduce((accumulator, currentVal, currentIndex) => {
return accumulator
.then((data) => {
return this.listDir(currentVal, '/');
})
.catch((e) => {
return this.listDir(currentVal, '/');
});
}, Promise.resolve())
.then((data) => {
console.log('DONE READING STORAGE LOCATIONS');
resolve();
})
.catch((e) => {
console.log(e);
resolve();
});
});
}
})
.then((data) => {
console.log(data);
return this.getCurrentState();
})
.catch((e) => {
console.log(e);
if (this.storageLocations.length < 1) {
this.logToLocations = ['chart'];
this.logToSelect('chart');
}
return this.getCurrentState();
})
.then((data) => {
console.log(data);
return this.loadProfilesFromDevice();
})
.then((data) => {
console.log(data);
return (this.activeDevice.rootUri === 'local') ? 'local' : this.getNicStatus('wlan0'); // only if this isn't a sim device
})
.then((status) => {
this.nicStatus = status;
resolve();
})
.catch((e) => {
console.log(e);
reject(e);
});
});
}
openChannelSelector(event) {
let popover = this.popoverCtrl.create(ChannelSelectPopover, { selectedChannels: this.selectedChannels, colorArray: this.colorArray }, {
cssClass: 'logChannelsPopover'
});
popover.present({
ev: event
});
}
public scaleSelect(event: string, channel: number) {
let currentScale = this.selectedScales[channel];
this.selectedScales[channel] = event;
if (event === 'None') {
// remove scaling on this channel and reset units
this.unitTransformer[channel] = undefined;
this.events.publish('units:update', { channel: channel });
this.chanUnits[channel] = 'V';
} else {
// apply expression to this channel and update units
this.scalingService.getScalingOption(event)
.then((result) => {
// apply scaling to this channel
this.unitTransformer[channel] = result.expression;
this.events.publish('units:update', { channel: channel, units: result.unitDescriptor });
this.chanUnits[channel] = result.unitDescriptor;
})
.catch(() => {
this.toastService.createToast('loggerScaleLoadErr', true, undefined, 5000);
this.selectedScales[channel] = currentScale;
setTimeout(() => {
this.scalingChildren.toArray()[channel]._applyActiveSelection(currentScale);
}, 20);
return;
});
}
}
openScaleSettings(event: any, chan: number, newScale: boolean) {
let scaleData = { channel: chan };
if (!newScale) {
scaleData['scaleName'] = this.selectedScales[chan];
}
let popover = this.popoverCtrl.create(LogScalePopover, scaleData, {
cssClass: 'logScalePopover'
});
popover.present({
ev: event
});
}
continueStream() {
if (!this.running) { return; }
//Device was in stream mode and should be ready to stream
this.daqChansToRead = this.selectedChannels.reduce((chanArray, isSelected, i) => {
if (isSelected) {
chanArray.push(i + 1);
}
return chanArray;
}, []);
if (this.daqChansToRead !== []) {
this.count = -1000;
}
if (this.selectedLogLocation !== 'chart') {
this.logAndStream = true;
this.bothStartStream();
}
this.readLiveData();
}
fileExists(): Promise<any> {
return new Promise((resolve, reject) => {
this.alertWrapper('File Exists', 'Your log file already exists. Would you like to overwrite or cancel?',
[{
text: 'Cancel',
handler: (data) => {
reject();
}
},
{
text: 'Overwrite',
handler: (data) => {
resolve();
}
}]
);
});
}
private alertWrapper(title: string, subTitle: string, buttons?: { text: string, handler: (data) => void }[]): Promise<any> {
return new Promise((resolve, reject) => {
let alert = this.alertCtrl.create({
title: title,
subTitle: subTitle,
buttons: buttons == undefined ? ['OK'] : <any>buttons
});
alert.onWillDismiss((data) => {
resolve(data);
});
alert.present();
});
}
xAxisValChange(event) {
console.log(event);
this.loggerPlotService.setValPerDivAndUpdate('x', 1, event);
}
yAxisValChange(trueValue, axisNum: number) {
console.log(trueValue);
if (trueValue < this.loggerPlotService.vpdArray[0]) {
trueValue = this.loggerPlotService.vpdArray[0];
}
else if (trueValue > this.loggerPlotService.vpdArray[this.loggerPlotService.vpdArray.length - 1]) {
trueValue = this.loggerPlotService.vpdArray[this.loggerPlotService.vpdArray.length - 1];
}
if (this.loggerPlotService.vpdArray[this.loggerPlotService.vpdIndices[axisNum]] === trueValue) {
console.log('the same');
/* this.chart.timeDivision = trueValue * 10 + 1;
setTimeout(() => {
this.chart.timeDivision = trueValue;
}, 1); */
return;
}
this.loggerPlotService.setValPerDivAndUpdate('y', axisNum + 1, trueValue);
/* this.chart.timeDivision = trueValue;
this.chart.setNearestPresetSecPerDivVal(trueValue);
this.chart.setTimeSettings({
timePerDiv: this.chart.timeDivision,
base: this.chart.base
}, false); */
}
mousewheel(event, input: 'offset' | 'sampleFreq' | 'samples' | 'vpd', axisNum?: number) {
event.preventDefault();
if (input === 'offset') {
this.buttonChangeOffset(axisNum, event.deltaY < 0 ? 'increment' : 'decrement');
return;
}
if (event.deltaY < 0) {
input === 'vpd' ? this.decrementVpd(axisNum) : this.incrementFrequency(input);
}
else {
input === 'vpd' ? this.incrementVpd(axisNum) : this.decrementFrequency(input);
}
}
incrementVpd(axisNum: number) {
if (this.loggerPlotService.vpdIndices[axisNum] > this.loggerPlotService.vpdArray.length - 2) { return; }
this.loggerPlotService.setValPerDivAndUpdate('y', axisNum + 1, this.loggerPlotService.vpdArray[this.loggerPlotService.vpdIndices[axisNum] + 1]);
}
decrementVpd(axisNum: number) {
if (this.loggerPlotService.vpdIndices[axisNum] < 1) { return; }
this.loggerPlotService.setValPerDivAndUpdate('y', axisNum + 1, this.loggerPlotService.vpdArray[this.loggerPlotService.vpdIndices[axisNum] - 1]);
}
buttonChangeOffset(axisNum: number, type: 'increment' | 'decrement') {
this.daqChans[axisNum].vOffset += type === 'increment' ? 0.1 : -0.1;
this.loggerPlotService.setPosition('y', axisNum + 1, this.daqChans[axisNum].vOffset, true);
}
incrementFrequency(type: 'sampleFreq' | 'samples') {
let valString = type === 'sampleFreq' ? this.daqParams.sampleFreq.toString() : this.daqParams.maxSampleCount.toString();
let valNum = parseFloat(valString);
let pow = 0;
while (valNum * Math.pow(1000, pow) < 1) {
pow++;
}
valString = (valNum * Math.pow(1000, pow)).toString();
let leadingNum = parseInt(valString.charAt(0), 10);
let numberMag = valString.split('.')[0].length - 1;
leadingNum++;
if (leadingNum === 10) {
leadingNum = 1;
numberMag++;
}
let newFreq = (leadingNum * Math.pow(10, numberMag)) / Math.pow(1000, pow);
this.validateAndApply(newFreq, type);
}
private getMaxSampleFreq(): number {
let targets = this.activeDevice.instruments.logger.daq.targets;
let max;
if (this.selectedLogLocation === 'chart') {
max = targets.ram.sampleFreqMax;
} else if (this.selectedLogLocation === 'SD') {
max = targets.sd0.sampleFreqMax * 10; // note(andrew): THIS IS A SIMPLE BANDAID FIX THAT NEEDS TO BE REMOVED AFTER THE FIRMWARE HAS BEEN FIXED!!
} else {
max = this.activeDevice.instruments.logger.daq.chans[0].sampleFreqMax;
}
return max;
}
private validateAndApply(newVal: number, type: 'sampleFreq' | 'samples'): number {
if (type === 'sampleFreq') {
let chanObj = this.activeDevice.instruments.logger.daq.chans[0];
let maxAggregate = this.getMaxSampleFreq();
let numChans = this.selectedChannels.lastIndexOf(true) + 1;
let minFreq = chanObj.sampleFreqMin * chanObj.sampleFreqUnits;
let maxFreq = this.selectedChannels.filter((e) => e).length > 1 ? Math.floor(maxAggregate / numChans) : maxAggregate;
maxFreq = maxFreq * chanObj.sampleFreqUnits;
if (newVal < minFreq) {
newVal = minFreq;
}
else if (newVal > maxFreq) {
newVal = maxFreq;
}
this.daqParams.sampleFreq = newVal;
}
else if (type === 'samples') {
// TODO: get maxSampleSize from instrument before setting
// let chanObj = this.activeDevice.instruments.logger[instrument].chans[axisNum];
// let maxSampleSize = axisObj.storageLocation === 'ram' ? chanObj.bufferSizeMax : 2000000000; //2gb fat
if (newVal < 1) {
newVal = 1;
}
// else if (newVal > maxSampleSize) {
// newVal = maxSampleSize;
// }
this.daqParams.maxSampleCount = newVal;
}
return newVal;
}
decrementFrequency(type: 'sampleFreq' | 'samples') {
let valString = type === 'sampleFreq' ? this.daqParams.sampleFreq.toString() : this.daqParams.maxSampleCount.toString();
let valNum = parseFloat(valString);
let pow = 0;
while (valNum * Math.pow(1000, pow) < 1) {
pow++;
}
valString = (valNum * Math.pow(1000, pow)).toString();
let leadingNum = parseInt(valString.charAt(0), 10);
let numberMag = valString.split('.')[0].length - 1;
leadingNum--;
if (leadingNum === 0) {
leadingNum = 9;
numberMag--;
}
let newFreq = (leadingNum * Math.pow(10, numberMag)) / Math.pow(1000, pow);
this.validateAndApply(newFreq, type);
}
setViewToEdge() {
if (this.viewMoved) { return; }
let index = this.selectedChannels.findIndex((e) => e);
if (!this.dataAvailable || index === -1 || this.dataContainers[index].data[0] == undefined || this.dataContainers[index].data[0][0] == undefined) {
//Data was cleared
this.loggerPlotService.setPosition('x', 1, this.loggerPlotService.xAxis.base * 5, true);
return;
}
let rightPos = this.dataContainers[index].data[this.dataContainers[index].data.length - 1][0];
for (let i = 1; i < this.dataContainers.length; i++) {
let len = this.dataContainers[i].data.length - 1;
if (len <= 0) continue;
let tempRightPos = this.dataContainers[i].data[this.dataContainers[i].data.length - 1][0];
rightPos = tempRightPos > rightPos ? tempRightPos : rightPos;
}
let span = this.loggerPlotService.xAxis.base * 10;
let leftPos = rightPos - span;
if (leftPos < 0) { return; }
let newPos = (rightPos + leftPos) / 2;
this.loggerPlotService.setPosition('x', 1, newPos, false);
}
logToSelect(event) {
console.log(event);
if (event === 'chart') {
this.daqParams.storageLocation = 'ram';
} else if (event === 'SD') {
this.daqParams.storageLocation = 'sd0';
} else {
this.daqParams.storageLocation = event;
}
this.selectedLogLocation = event;
}
modeSelect(event: 'finite' | 'continuous') {
console.log(event);
if (event === 'finite') {
this.daqParams.maxSampleCount = 1000;
}
else {
this.daqParams.maxSampleCount = -1;
}
this.selectedMode = event;
}
openProfileSettings(name, event?) {
let popover = this.popoverCtrl.create(ProfilePopover, { profileName: name, profileObj: this.profileObjectMap[name] }, {
cssClass: 'profilePopover'
});
popover.present({
ev: event
});
}
public profileSaveClick(name, event) {
// if new profile open popover, otherwise just save
if (name === 'New Profile') {
this.openProfileSettings('', event);
} else {
this.saveAndSetProfile(name, this.profileObjectMap[name].chart !== undefined, this.profileObjectMap[name].daq !== undefined);
}
}
profileSelect(event) {
console.log(event);
let currentLogProfile = this.selectedLogProfile;
this.selectedLogProfile = event;
if (event === this.loggingProfiles[0]) {
this.openProfileSettings('');
return;
}
if (this.profileObjectMap[event] == undefined) {
this.toastService.createToast('loggerProfileLoadErr', true, undefined, 5000);
console.log('profile not found in profile map');
this.selectedLogProfile = currentLogProfile;
setTimeout(() => {
this.profileChild._applyActiveSelection(this.selectedLogProfile);
}, 20);
return;
}
//Need to copy so further edits do not overwrite profile info
this.parseAndApplyProfileJson(JSON.parse(JSON.stringify(this.profileObjectMap[event])));
}
deleteProfile(profileName) {
this.activeDevice.file.delete('flash', this.settingsService.profileToken + profileName + '.json').subscribe(
(data) => {
console.log(data);
// remove from list of profiles
let nameIndex: number = this.loggingProfiles.indexOf(profileName);
if (nameIndex !== -1) {
this.loggingProfiles.splice(nameIndex, 1);
}
this.selectedLogProfile = this.loggingProfiles[0];
},
(err) => {
console.log(err);
this.toastService.createToast('fileDeleteErr', true, undefined, 5000);
},
() => { }
);
}
saveAndSetProfile(profileName, saveChart, saveDaq) {
console.log(profileName);
this.saveProfile(profileName, saveChart, saveDaq)
.then((data) => {
this.toastService.createToast('loggerSaveSuccess');
})
.catch((e) => {
console.log(e);
this.toastService.createToast('loggerSaveFail');
});
let nameIndex: number = this.loggingProfiles.indexOf(profileName);
if (nameIndex !== -1) {
this.loggingProfiles.splice(nameIndex, 1);
}
this.loggingProfiles.push(profileName);
let profileObj = this.generateProfileJson(saveChart, saveDaq);
let profileObjCopy = JSON.parse(JSON.stringify(profileObj));
this.profileObjectMap[profileName] = profileObjCopy;
setTimeout(() => {
this.selectedLogProfile = profileName;
this.profileChild._applyActiveSelection(this.selectedLogProfile);
}, 20);
}
loadProfilesFromDevice(): Promise<any> {
return new Promise((resolve, reject) => {
this.listDir('flash', '/')
.then((data) => {
console.log(data);
let profileFileNames = [];
for (let i = 0; i < data.file[0].files.length; i++) {
if (data.file[0].files[i].indexOf(this.settingsService.profileToken) !== -1) {
profileFileNames.push(data.file[0].files[i].replace(this.settingsService.profileToken, ''));
}
}
console.log(profileFileNames);
profileFileNames.reduce((accumulator, currentVal, currentIndex) => {
return accumulator
.then((data) => {
console.log(data);
return this.readProfile(currentVal);
})
.catch((e) => {
console.log(e);
return this.readProfile(currentVal);
});
}, Promise.resolve())
.then((data) => {
console.log(data);
resolve(data);
})
.catch((e) => {
reject(e);
});
})
.catch((e) => {
reject(e);
});
});
}
private getProfileFromStorage() {
let profileName = this.settingsService.getLoggerProfile(this.activeDevice.macAddress);
if (profileName !== undefined && profileName !== this.loggingProfiles[0] && this.profileObjectMap[profileName] !== undefined) {
this.selectedLogProfile = profileName;
this.parseAndApplyProfileJson(JSON.parse(JSON.stringify(this.profileObjectMap[profileName])));
setTimeout(() => {
this.profileChild._applyActiveSelection(profileName);
}, 20);
}
}
private readProfile(profileName: string): Promise<any> {
return new Promise((resolve, reject) => {
this.activeDevice.file.read('flash', this.settingsService.profileToken + profileName, 0, -1).subscribe(
(data) => {
console.log(data);
let parsedData;
try {
parsedData = JSON.parse(data.file);
}
catch (e) {
console.log('error parsing json');
resolve(e);
return;
}
let splitArray = profileName.split('.');
if (splitArray.length < 2) {
this.loggingProfiles.push(profileName);
this.profileObjectMap[profileName] = parsedData;
}
else {
splitArray.splice(splitArray.length - 1, 1);
let noExtName = splitArray.join('');
this.loggingProfiles.push(noExtName);
this.profileObjectMap[noExtName] = parsedData;
}
resolve(data);
},
(err) => {
console.log(err);
resolve(err);
},
() => { }
);
});
}
generateProfileJson(saveChart, saveDaq, saveDC = true) {
let saveObj = {};
if (saveChart) {
saveObj['chart'] = {
tpd: this.xAxis.tpdArray[this.xAxis.tpdIndex],
bufferSize: this.xAxis.loggerBufferSize,
channels: []
};
// Save chart data for all channels, not just selected?
for (let i = 0; i < this.daqChans.length; i++) {
let chanObj = {
[(i + 1).toString()]: {
vpd: this.loggerPlotService.vpdArray[this.loggerPlotService.vpdIndices[i]],
vOffset: this.daqChans[i].vOffset
}
};
saveObj['chart']['channels'].push(chanObj);
}
}
if (saveDaq) {
saveObj['daq'] = JSON.parse(JSON.stringify(this.daqParams));
saveObj['daq'].channels = [];
this.daqChans.forEach((channel, index) => {
if (this.selectedChannels[index]) {
let chanObj = {
[(index + 1).toString()]: {
average: channel.average
}
};
saveObj['daq']['channels'].push(chanObj);
}
});
}
if (saveDC) {
let voltages: number[] = this.events.publish('profile:getDC')[0] || ''; // DC Component listens for getDC from the openlogger component since the component doesn't have easy access to the dc supply component.
saveObj['dc'] = voltages;
}
return saveObj;
}
private parseAndApplyProfileJson(loadedObj) {
if (loadedObj.daq !== undefined) {
this.selectedChannels = this.selectedChannels.map(() => false);
this.averagingEnabled = false;
}
for (let instrument in loadedObj) {
if (instrument === 'daq') {
this.daqParams.maxSampleCount = loadedObj[instrument]['maxSampleCount'];
this.daqParams.sampleFreq = loadedObj[instrument]['sampleFreq'];
this.daqParams.startDelay = loadedObj[instrument]['startDelay'];
this.daqParams.storageLocation = loadedObj[instrument]['storageLocation'];
this.daqParams.uri = loadedObj[instrument]['uri'];
// set log to location based on storageLocation
let logTo = loadedObj[instrument]['storageLocation'] === 'ram' ? 'chart' : 'SD';
this.selectedLogLocation = logTo;
this.logToChild._applyActiveSelection(logTo);
// select channels
loadedObj[instrument].channels.forEach((channel) => {
let chanNum = parseInt(Object.keys(channel)[0]);
this.selectedChannels[chanNum - 1] = true;
this.daqChans[chanNum - 1].average = channel[chanNum].average;
if (channel[chanNum].average > 1) {
this.averagingEnabled = true;
}
});
// set mode dropdown
let selection = loadedObj[instrument].maxSampleCount === -1 ? 'continuous' : 'finite';
this.modeChild._applyActiveSelection(selection);
} else if (instrument === 'chart') {
this.xAxis.valChange(loadedObj[instrument]['tpd']);
this.xAxis.loggerBufferSize = loadedObj[instrument]['bufferSize'];
loadedObj[instrument].channels.forEach((channel) => {
let chanNum = parseInt(Object.keys(channel)[0]);
if (this.loggerPlotService.vpdArray.indexOf(channel[chanNum].vpd) !== -1) {
this.loggerPlotService.vpdIndices[chanNum - 1] = this.loggerPlotService.vpdArray.indexOf(channel[chanNum].vpd);
}
this.daqChans[chanNum - 1].vOffset = channel[chanNum].vOffset;
});
} else if (instrument === 'dc') {
this.events.publish('profile:setDC', ...loadedObj[instrument]);
}
}
}
private saveProfile(profileName: string, saveChart: boolean, saveDaq: boolean): Promise<any> {
return new Promise((resolve, reject) => {
let objToSave = this.generateProfileJson(saveChart, saveDaq);
let str = JSON.stringify(objToSave);
let buf = new ArrayBuffer(str.length);
let bufView = new Uint8Array(buf);
for (let i = 0; i < str.length; i++) {
bufView[i] = str.charCodeAt(i);
}
this.activeDevice.file.write('flash', this.settingsService.profileToken + profileName + '.json', buf).subscribe(
(data) => {
console.log(data);
resolve(data);
},
(err) => {
console.log(err);
reject(err);
},
() => { }
);
});
}
private getStorageLocations(): Promise<any> {
return new Promise((resolve, reject) => {
this.activeDevice.storageGetLocations().subscribe(
(data) => {
console.log(data);
resolve(data);
},
(err) => {
console.log(err);
reject(err);
},
() => { }
);
});
}
setActiveSeries(axisNum: number) {
this.loggerPlotService.setActiveSeries(axisNum + 1);
}
formatInputAndUpdate(trueValue: number, type: LoggerInputType, channel?: number) {
console.log(trueValue);
switch (type) {
case 'delay':
this.daqParams.startDelay = trueValue;
break;
case 'offset':
(<DaqChannelParams>this.daqChans[channel]).vOffset = trueValue;
this.loggerPlotService.setPosition('y', channel + 1, trueValue, true);
break;
case 'samples':
trueValue = trueValue < 1 ? 1 : trueValue;
this.daqParams.maxSampleCount = trueValue;
break;
case 'sampleFreq':
this.validateAndApply(trueValue, 'sampleFreq');
break;
default:
break;
}
}
stopLogger() {
this.stop()
.then((data) => {
console.log(data);
this.running = false;
})
.catch((e) => {
console.log(e);
});
}
private clearChart() {
for (let i = 0; i < this.dataContainers.length; i++) {
this.dataContainers[i].data = [];
}
this.loggerPlotService.setData(this.dataContainers, this.viewMoved);
this.dataAvailable = false;
}
private parseReadResponseAndDraw(readResponse) {
let t0 = performance.now();
for (let instrument in readResponse.instruments) {
for (let channel in readResponse.instruments[instrument]) {
let formattedData: number[][] = [];
let channelObj = readResponse.instruments[instrument][channel];
let dt = 1 / (channelObj.actualSampleFreq / 1000000);
let timeVal = channelObj.startIndex * dt;
let chanIndex: number = parseInt(channel) - 1;
for (let i = 0; i < channelObj.data.length; i++) {
let data = (this.unitTransformer[chanIndex]) ? this.unitTransformer[chanIndex](channelObj.data[i]) :
channelObj.data[i];
formattedData.push([timeVal, data]);
timeVal += dt;
}
let dataContainerIndex = 0;
dataContainerIndex += chanIndex;
this.dataContainers[dataContainerIndex].seriesOffset = 0;
this.dataContainers[dataContainerIndex].data = this.dataContainers[dataContainerIndex].data.concat(formattedData);
let overflow = 0;
let containerSize = (this.daqParams.sampleFreq) * this.xAxis.loggerBufferSize;
if ((overflow = this.dataContainers[dataContainerIndex].data.length - containerSize) >= 0) {
this.dataContainers[dataContainerIndex].data = this.dataContainers[dataContainerIndex].data.slice(overflow); // older data is closer to the front of the array, so remove it by the overflow amount
}
}
}
this.setViewToEdge();
this.loggerPlotService.setData(this.dataContainers, this.viewMoved);
this.dataAvailable = true;
let t1 = performance.now();
console.log('time to parse and draw:', t1 - t0);
}
private existingFileFoundAndValidate(loading): { reason: number, existingFiles?: string[] } {
let existingFileFound: boolean = false;
if (this.daqParams.storageLocation !== 'ram' && this.daqParams.storageLocation !== 'cloud' && this.daqParams.uri === '') {
loading.dismiss();
this.toastService.createToast('loggerInvalidFileName', true, undefined, 8000);
return { reason: 1 };
}
if (this.loggerState !== 'idle' && this.loggerState !== 'stopped') {
loading.dismiss();
this.toastService.createToast('loggerInvalidState', true, undefined, 8000);
return { reason: 1 };
}
if (this.selectedLogLocation !== 'SD') {
return { reason: 0 };
}
let regex = new RegExp(this.daqParams.uri + '_[0-9][0-9]*.log');
let matchingFiles = this.filesInStorage[this.daqParams.storageLocation].filter((filename) => regex.test(filename));
if (matchingFiles.length !== 0) {
//File already exists on device display alert
existingFileFound = true;
} else {
this.filesInStorage[this.daqParams.storageLocation].push(`${this.daqParams.uri}_0.log`);
}
return {reason: existingFileFound ? 2 : 0, existingFiles: matchingFiles};
}
startLogger() {
if (this.selectedChannels.indexOf(true) === -1) {
let mode = this.selectedLogLocation === 'chart' ? 'Streaming' : 'Logging';
this.toastService.createToast('loggerNoChannelsError', true, mode, 5000);
return;
}
if (this.selectedLogLocation === 'cloud') {
if (!this.daqParams.apiKey) {
this.toastService.createToast('loggerApiKeyRequired', true, undefined, 5000);
return;
}
if (!this.channelId) {
this.toastService.createToast('loggerChannelIdRequired', true, undefined, 5000);
return;
}
if (this.nicStatus != 'connected') {
this.toastService.createToast('loggerNetworkError', true, undefined, 5000);
return;
}
}
let loading = this.loadingService.displayLoading('Starting data logging...');
this.getCurrentState(true)
.then((data) => {
console.log(data);
let returnData: { reason: number, existingFiles?: string[] } = this.existingFileFoundAndValidate(loading);
if (returnData.reason === 2) {
loading.dismiss();
return this.fileExists()
.then((data) => {
loading = this.loadingService.displayLoading('Starting data logging...');
// delete the existing files
if (returnData.existingFiles && returnData.existingFiles.length > 0) {
return this.deleteFiles("sd0", returnData.existingFiles); // poll the device until not deleting any longer, then run
}
// this.setParametersAndRun(loading);
})
.catch((e) => { });
}
else if (returnData.reason === 0) {
// return this.setParametersAndRun(loading);
return Promise.resolve();
}
})
.then(() => {
return this.waitTillFileIdle();
})
.then(() => this.setParametersAndRun(loading))
.catch((e) => {
console.log(e);
loading.dismiss();
this.toastService.createToast('loggerUnknownRunError', true, undefined, 8000);
});
}
/**
* This method calls into the DIP file.delete method, wrapping the returned
* observable in a promise.
* @param location storage location to delete files from
* @param paths single path or array of paths of files to be deleted
*
* @returns a promise that resolves on file.delete completion, or rejects on error.
*/
private deleteFiles(location: string, paths: string | string[]): Promise<any> {
return new Promise((resolve, reject) => {
this.activeDevice.file.delete(location, paths).subscribe(data => {
resolve(data);
},
err => {
reject(err);
});
});
}
/**
* This method queries the state of the device filesystem. If the state is not
* idle, this method will recursively call itself until the filesystem is idle.
*
* @returns a promise that resolves when file.state is idle, or rejects on error.
*/
private waitTillFileIdle(): Promise<null> {
return new Promise((resolve, reject) => {
this.getFileCurrentState().then(data => {
if (data.file.state == 'idle') {
resolve();
} else {
this.getFileCurrentState()
.then(resolve)
.catch(reject);
}
})
.catch(reject);
});
}
/**
* This method calls file.getCurrentState, and returns the response through
* promise resolution.
*
* @returns a promise that resolves with the filesystem state, or rejects on error.
*/
private getFileCurrentState() {
return new Promise<any>((resolve, reject) => {
this.activeDevice.file.getCurrentState().subscribe(
(data) => {
console.log(data);
resolve(data);
},
(err) => {
reject(err);
}
)
});
}
private setParametersAndRun(loading) {
let daqChanArray = [];
for (let i = 0; i < this.daqChans.length; i++) {
this.count = -1000;
this.startIndex = 0;
if (this.selectedChannels[i]) {
daqChanArray.push(i + 1);
}
}
this.clearChart();
this.setViewToEdge();
this.setParameters('analog', daqChanArray)
.then((data) => {
console.log(data);
return this.run('analog', daqChanArray);
})
.then((data) => {
if (data.log.daq.statusCode !== 0) {
this.toastService.createToast('loggerUnknownRunError', true, undefined, 8000);
this.running = false;
this.stopLogger();
loading.dismiss();
} else {
console.log(data);
this.running = true;
loading.dismiss();
this.daqChansToRead = this.selectedChannels.reduce((chanArray, isSelected, i) => {
if (isSelected) {
chanArray.push(i + 1);
}
return chanArray;
}, []);
if (this.selectedLogLocation !== 'chart' && !this.logAndStream) {
this.getLiveState();
} else {
this.readLiveData();
}
}
})
.catch((e) => {
console.log(e);
this.toastService.createToast('loggerUnknownRunError', true, undefined, 8000);
this.running = false;
this.stopLogger();
loading.dismiss();
});
}
private getLiveState() {
let message;
if ((message = this.messageQueue.shift()) !== undefined) {
message().then(() => {
this.getLiveState(); // try again
});
return;
}
this.getCurrentState()
.then((data) => {
this.parseGetLiveStatePacket('analog', data);
if (this.running) {
setTimeout(() => {
if (this.selectedLogLocation !== 'chart' && this.logAndStream) {
this.continueStream();
}
else {
this.getLiveState();
}
}, 1000);
}
})
.catch((e) => {
if (this.running) {
setTimeout(() => {
this.getLiveState();
}, 1000);
}
});
}
private parseGetLiveStatePacket(instrument: 'digital' | 'analog', data) {
for (let channel in data.log[instrument]) {
if (data.log[instrument][channel][0].stopReason === 'OVERFLOW') {
console.log('OVERFLOW');
this.toastService.createToast('loggerStorageCouldNotKeepUp', true, undefined, 8000);
// Set running to false beforehand so that another getCurrentState does not occur
this.running = false;
this.stopLogger();
}
else if (data.log[instrument][channel][0].state === 'stopped') {
if (instrument === 'analog') {
this.daqChansToRead.splice(this.daqChansToRead.indexOf(parseInt(channel)), 1);
}
if (this.daqChansToRead.length < 1) {
this.toastService.createToast('loggerLogDone');
this.running = false;
}
}
}
}
private readLiveData() {
// if the messageQueue has something in it, run that instead, then pop it off the queue. Call readLiveData again (if running?).
let message;
if ((message = this.messageQueue.shift()) !== undefined) {
message().then(() => {
console.warn('STARTING AGAIN');
this.readLiveData(); // try to read again
});
return;
}
if (this.destroyed) return; // if we are leaving, don't do another read
//Make copies of analogChansToRead so mid-read changes to analogChansToRead don't change the channel array
this.read('daq', this.daqChansToRead.slice())
.then((data) => {
this.parseReadResponseAndDraw(data);
if (this.running) {
if (this.selectedLogLocation !== 'chart' && !this.logAndStream) {
this.getLiveState();
} else {
if (this.activeDevice.transport.getType() === 'local') {
requestAnimationFrame(() => { // note: calling readLiveData without some delay while simulating freezes the UI, so we request the browser keep time for us.
this.readLiveData();
});
} else {
this.readLiveData();
}
}
}
else {
this.viewMoved = false;
}
})
.catch((e) => {
console.log('error reading live data');
console.log(e);
if (this.destroyed) { return; }
else if (e === 'corrupt transfer') {
this.readLiveData();
return;
}
else if (e.message && e.message === 'Data not ready' && this.running) {
console.log('data not ready');
this.readLiveData();
return;
}
else if (e.message && e.message === 'Could not keep up with device') {
this.toastService.createToast('loggerCouldNotKeepUp', false, undefined, 10000);
this.stop()
.then((data) => {
console.log(data);
})
.catch((e) => {
console.log(e);
});
}
else {
this.toastService.createToast('loggerUnknownRunError', true, undefined, 8000);
}
this.getCurrentState()
.then((data) => {
console.log(data);
this.running = false;
this.stopLogger();
})
.catch((e) => {
console.log(e);
this.stopLogger();
});
});
}
toggleLoggerSettings() {
this.showLoggerSettings = !this.showLoggerSettings;
}
toggleAdvSettings() {
this.showAdvSettings = !this.showAdvSettings;
}
exportCanvasAsPng() {
let flotOverlayRef = document.getElementById('loggerChart').childNodes[1];
this.exportService.exportCanvasAsPng(this.loggerPlotService.chart.getCanvas(), flotOverlayRef);
}
exportCsv(fileName: string) {
let analogChanArray = [];
for (let i = 0; i < this.daqChans.length; i++) {
analogChanArray.push(i);
}
this.exportService.exportGenericCsv(fileName, this.dataContainers, analogChanArray, [{
instrument: 'Analog',
seriesNumberOffset: 0,
xUnit: 's',
yUnit: 'V',
channels: analogChanArray
}]);
}
private applyCurrentStateResponse(data: any, onlyCopyState: boolean = false) {
for (let instrument in data.log) {
if (instrument === 'daq') {
let stateData = data.log[instrument];
if (stateData.statusCode == undefined) { return; }
this.loggerState = stateData.state.trim();
this.running = stateData.state === 'running';
this.daqParams.logOnBoot = stateData.logOnBoot;
if (onlyCopyState) {
return;
}
if (stateData.maxSampleCount != undefined) {
this.daqParams.maxSampleCount = stateData.maxSampleCount;
// set mode dropdown
this.selectedMode = stateData.maxSampleCount === -1 ? 'continuous' : 'finite';
this.modeChild._applyActiveSelection(this.selectedMode);
}
if (stateData.actualSampleFreq != undefined) {
this.daqParams.sampleFreq = stateData.actualSampleFreq / 1000000;
}
if (stateData.actualStartDelay != undefined) {
this.daqParams.startDelay = stateData.actualStartDelay / Math.pow(10, 12);
}
if (stateData.storageLocation === 'cloud') {
this.channelId = stateData.uri.replace(this.thingSpeakBaseUrl, '').replace(this.thingSpeakResourcePath, '');
} else if (stateData.uri != undefined) {
if (stateData.uri.lastIndexOf('_') !== -1) {
// remove start index from end of file name
// will also remove .log extension
stateData.uri = stateData.uri.slice(0, stateData.uri.lastIndexOf('_'));
// remove session ID from end of file name if exists
let regex = new RegExp('.+_LOB[0-9]{3}');
if (regex.test(stateData.uri)) {
stateData.uri = stateData.uri.slice(0, stateData.uri.lastIndexOf('_'));
}
} else if (stateData.uri.indexOf('.log') !== -1) {
// Remove .log from end of file
stateData.uri = stateData.uri.slice(0, stateData.uri.indexOf('.log'));
}
this.daqParams.uri = stateData.uri;
}
if (this.storageLocations.length < 1) {
stateData.storageLocation = 'ram';
}
this.daqParams.storageLocation = stateData.storageLocation || this.daqParams.storageLocation;
if (stateData.storageLocation === undefined || stateData.storageLocation === 'ram') {
this.selectedLogLocation = 'chart';
this.logToChild._applyActiveSelection('chart');
} else if (stateData.storageLocation === 'cloud') {
this.selectedLogLocation = 'cloud';
this.logToChild._applyActiveSelection('cloud');
} else {
this.selectedLogLocation = 'SD';
this.logToChild._applyActiveSelection('SD');
}
this.selectedChannels = this.selectedChannels.map(() => false);
this.averagingEnabled = false;
if (stateData.channels != undefined && stateData.channels.length > 0) {
stateData.channels.forEach((channel) => {
let key = Object.keys(channel)[0];
let index = parseInt(key) - 1;
// select channel
this.selectedChannels[index] = true;
this.daqChans[index].average = channel[key].average;
if (channel[key].average > 1) {
this.averagingEnabled = true;
}
});
} else {
// select channel 1 by default
this.selectedChannels[0] = true;
}
if (stateData.actualCount != undefined && stateData.actualCount > 0) {
this.startIndex = stateData.actualCount;
}
}
}
}
logAndStreamChange() {
if (this.logAndStream) {
this.bothStartStream();
}
}
bothStartStream() {
this.clearChart();
this.viewMoved = false;
this.setViewToEdge();
}
setParameters(instrument: 'analog' | 'digital', chans: number[]): Promise<any> {
return new Promise((resolve, reject) => {
let observable;
if (instrument === 'analog') {
if (this.daqChans.length < 1) {
resolve();
return;
}
let uri;
if (this.selectedLogLocation === 'SD') {
uri = this.daqParams.uri + '.log';
} else if (this.selectedLogLocation === 'cloud') {
uri = this.thingSpeakBaseUrl + this.channelId + this.thingSpeakResourcePath;
}
let averages = chans.map((chan) => this.daqChans[chan - 1].average);
let overflows = Array.apply(null, Array(chans.length)).map(() => 'circular');
observable = this.activeDevice.instruments.logger.daq.setParameters(
chans,
this.daqParams.maxSampleCount,
this.daqParams.sampleFreq,
this.daqParams.startDelay,
this.daqParams.storageLocation,
this.daqParams.logOnBoot,
this.selectedCloudService,
this.daqParams.apiKey,
uri,
averages,
overflows
);
}
observable.subscribe(
(data) => {
console.log(data);
resolve(data);
},
(err) => {
console.log(err);
reject(err);
},
() => { }
);
});
}
run(instrument: 'analog' | 'digital', chans: number[]): Promise<any> {
return new Promise((resolve, reject) => {
if (this.daqChans.length < 1) {
resolve();
return;
}
this.activeDevice.instruments.logger.daq.run(instrument, chans).subscribe(
(data) => {
console.log(data);
resolve(data);
},
(err) => {
console.log(err);
reject(err);
},
() => { }
);
});
}
stop(): Promise<any> {
return new Promise((resolve, reject) => {
if (this.daqChans.length < 1) {
resolve();
return;
}
this.activeDevice.instruments.logger.daq.stop().subscribe(
(data) => {
console.log(data);
if (this.daqParams.storageLocation != 'ram') {
this.listDir(this.daqParams.storageLocation, '/')
.catch((err) => {
console.log(err);
});
}
resolve(data);
},
(err) => {
console.log(err);
reject(err);
},
() => { }
);
});
}
read(instrument: 'analog' | 'digital' | 'daq', chans: number[]): Promise<any> {
return new Promise((resolve, reject) => {
if (this.daqChansToRead.length < 1 || this.daqChans.length < 1) {
resolve();
return;
}
let finalObj = {};
this.activeDevice.instruments.logger.daq.read(instrument, chans, this.startIndex, this.count)
.subscribe(
({cmdRespObj, instruments}) => {
let data = {cmdRespObj, instruments};
if (this.startIndex >= 0 && this.startIndex !== cmdRespObj.log.daq.startIndex) {
reject({
message: 'Could not keep up with device',
data: data
});
return;
}
this.updateValuesFromRead(data, instrument, chans, chans.length - 1);
this.deepMergeObj(finalObj, data);
resolve(finalObj);
},
(err) => {
console.log(err);
if (err.payload != undefined) {
let jsonString = String.fromCharCode.apply(null, new Uint8Array(err.payload));
let parsedData;
try {
parsedData = JSON.parse(jsonString);
}
catch (e) {
reject(e);
return;
}
//Check if data is not ready
if (parsedData && parsedData.log && parsedData.log[instrument]) {
if (parsedData.log[instrument].statusCode === 2684354593) {
console.log('data not ready');
reject({
message: 'Data not ready',
data: parsedData
});
return;
}
else if (parsedData.log[instrument].statusCode === 2684354595) {
reject({
message: 'Could not keep up with device',
data: parsedData
})
}
}
}
reject(err);
},
() => { }
);
});
}
private updateValuesFromRead(data, instrument: 'analog' | 'digital' | 'daq', chans: number[], index: number) {
if (data != undefined && data.instruments != undefined && data.instruments[instrument] != undefined && data.instruments[instrument][chans[index]].statusCode === 0) {
if (instrument === 'daq') {
// update the start index w/ what the device gives us
this.startIndex = data.cmdRespObj.log.daq.startIndex;
// increment startIndex by the actual count given
this.startIndex += data.cmdRespObj.log.daq.actualCount;
// reset count. A negative value tells the OpenLogger to give everything it currently has
this.count = -1000;
// if the start index is greater than maxSample count
if (this.daqParams.maxSampleCount > 0 && this.startIndex >= this.daqParams.maxSampleCount) {
// splice the channels to read list, removing everything after the bad index...
this.daqChansToRead.splice(this.daqChansToRead.indexOf(chans[index]), 1);
if (this.daqChansToRead.length < 1) {
this.running = false;
}
}
}
}
}
private deepMergeObj(destObj, sourceObj) {
if (this.isObject(destObj) && this.isObject(sourceObj)) {
Object.keys(sourceObj).forEach((key) => {
if (sourceObj[key].constructor === Array) {
destObj[key] = [];
sourceObj[key].forEach((el, index, arr) => {
if (this.isObject(el)) {
if (destObj[key][index] == undefined) {
destObj[key][index] = {};
}
this.deepMergeObj(destObj[key][index], sourceObj[key][index]);
}
else {
destObj[key][index] = sourceObj[key][index];
}
});
}
else if (this.isObject(sourceObj[key])) {
if (destObj[key] == undefined) {
destObj[key] = {};
}
this.deepMergeObj(destObj[key], sourceObj[key]);
}
else {
destObj[key] = sourceObj[key];
}
});
}
}
private isObject(item) {
return (item && typeof item === 'object' && !Array.isArray(item));
}
listDir(location: string, path: string): Promise<any> {
return new Promise((resolve, reject) => {
this.activeDevice.file.listDir(location, path).subscribe(
(data) => {
this.filesInStorage[location] = data.file[0].files;
console.log(this.filesInStorage);
resolve(data);
},
(err) => {
reject(err);
},
() => { }
);
});
}
getCurrentState(onlyCopyState: boolean = false): Promise<any> {
return new Promise((resolve, reject) => {
if (this.daqChans.length < 1) {
resolve();
return;
}
this.activeDevice.instruments.logger.daq.getCurrentState().subscribe(
(data) => {
if (data.log != undefined && data.log.daq != undefined) {
this.applyCurrentStateResponse(data, onlyCopyState);
}
resolve(data);
},
(err) => {
console.log(err);
reject(err);
},
() => { }
);
});
}
decrementAverage(chanIndex) {
if (this.daqChans[chanIndex].average > 1) {
this.daqChans[chanIndex].average /= 2;
}
}
incrementAverage(chanIndex) {
if (this.daqChans[chanIndex].average < this.maxAverage) {
this.daqChans[chanIndex].average *= 2;
}
}
toggleAveraging(event) {
if (!event.checked) {
this.daqChans.forEach((chan) => {
chan.average = 1;
});
}
}
restoreDefaults() {
let defaultTpd = this.loggerPlotService.tpdArray[this.loggerPlotService.defaultTpdIndex];
this.loggerPlotService.setValPerDivAndUpdate('x', 1, defaultTpd);
this.xAxis.loggerBufferSize = this.xAxis.defaultBufferSize;
this.daqParams = Object.assign({}, this.defaultDaqParams);
this.validateAndApply(this.daqParams.sampleFreq, 'sampleFreq');
this.selectedLogLocation = 'chart';
this.logToChild._applyActiveSelection('chart');
this.selectedLogProfile = this.loggingProfiles[0];
this.profileChild._applyActiveSelection(this.selectedLogProfile);
this.selectedMode = 'continuous';
this.modeChild._applyActiveSelection('continuous');
this.averagingEnabled = false;
this.daqChans.forEach((chan, index) => {
chan.average = this.defaultDaqChannelParams.average;
chan.vOffset = this.defaultDaqChannelParams.vOffset;
let defaultVpd = this.loggerPlotService.vpdArray[this.loggerPlotService.defaultVpdIndices[index]];
this.loggerPlotService.setValPerDivAndUpdate('y', index + 1, defaultVpd);
this.scaleSelect("None", index);
this.scalingChildren.toArray()[index]._applyActiveSelection("None");
});
this.events.publish("restore-defaults");
}
getNicStatus(adapter: string): Promise<any> {
return new Promise((resolve, reject) => {
this.activeDevice.nicGetStatus(adapter).subscribe((data) => {
resolve(data.device[0].status);
},
(err) => {
reject(err);
console.log(err);
},
() => { }
);
});
}
setLogOnBootParams(event) {
let daqChanArray = [];
for (let i = 0; i < this.daqChans.length; i++) {
if (this.selectedChannels[i]) {
daqChanArray.push(i + 1);
}
}
this.setParameters('analog', daqChanArray)
.then((data) => {
if (data && data.log.daq.logOnBoot) {
this.toastService.createToast('loggerLogOnBootEnabled', true, undefined, 5000);
} else {
this.toastService.createToast('loggerLogOnBootDisabled', true, undefined, 5000);
}
})
.catch((err) => {
console.log(err);
this.toastService.createToast('loggerSetParamError', true, undefined, 5000);
});
}
}
export type LoggerInputType = 'delay' | 'offset' | 'samples' | 'sampleFreq';
export interface DaqChannelParams {
average: number,
vOffset: number
}
export interface DaqLoggerParams {
maxSampleCount: number,
startDelay: number,
sampleFreq: number,
storageLocation: string,
logOnBoot: boolean,
service: string,
apiKey: string,
uri: string,
} | the_stack |
import type { Rule, SourceCode, AST, Scope } from "eslint"
import * as eslintUtils from "eslint-utils"
import type {
ArrowFunctionExpression,
CallExpression,
Expression,
FunctionDeclaration,
FunctionExpression,
Identifier,
Literal,
MemberExpression,
Node,
RegExpLiteral,
} from "estree"
import { parseStringLiteral, parseStringTokens } from "../string-literal-parser"
import { baseParseReplacements } from "../replacements-utils"
/**
* Get a parent node
* The AST node used by ESLint always has a `parent`, but since there is no `parent` on Types, use this function.
*/
export function getParent<E extends Node>(node: Node | null): E | null {
if (!node) {
return null
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- ignore
return (node as any).parent
}
/**
* Find the variable of a given name.
*/
export function findVariable(
context: Rule.RuleContext,
node: Identifier,
): Scope.Variable | null {
return eslintUtils.findVariable(getScope(context, node), node)
}
type SimpleVariable = Scope.Variable & {
defs: [
Scope.Definition & { type: "Variable" } & { node: { id: Identifier } },
]
}
/**
* Finds a variable of the form `{var,let,const} identifier ( = <init> )?`.
*
* The returned variable is also guaranteed to have exactly one definition.
*
* @param context
* @param expression
*/
function findSimpleVariable(
context: Rule.RuleContext,
identifier: Identifier,
): SimpleVariable | null {
const variable = findVariable(context, identifier)
if (!variable || variable.defs.length !== 1) {
// we want a variable with 1 definition
return null
}
const def = variable.defs[0]
if (def.type !== "Variable" || def.node.id.type !== "Identifier") {
// we want a simple variable
return null
}
return variable as SimpleVariable
}
/**
* Get the value of a given node if it's a constant of string.
*/
export function getStringIfConstant(
context: Rule.RuleContext,
node: Node,
): string | null {
// Supports `regexp.source` that eslint-utils#getStringIfConstant does not track.
if (
node.type === "BinaryExpression" ||
node.type === "MemberExpression" ||
node.type === "Identifier" ||
node.type === "TemplateLiteral"
) {
const evaluated = getStaticValue(context, node)
return evaluated && String(evaluated.value)
}
return eslintUtils.getStringIfConstant(node, getScope(context, node))
}
type GetStaticValueResult =
| { value: unknown }
| { value: undefined; optional?: true }
/**
* Get the value of a given node if it's a static value.
*/
export function getStaticValue(
context: Rule.RuleContext,
node: Node,
): GetStaticValueResult | null {
// Supports `regexp.source` that eslint-utils#getStaticValue does not track.
if (node.type === "BinaryExpression") {
if (node.operator === "+") {
const left = getStaticValue(context, node.left)
if (left == null) {
return null
}
const right = getStaticValue(context, node.right)
if (right == null) {
return null
}
return {
value:
// eslint-disable-next-line @typescript-eslint/restrict-plus-operands, @typescript-eslint/no-explicit-any -- ignore
(left.value as any) + right.value,
}
}
} else if (node.type === "MemberExpression") {
const propName = getPropertyName(node, context)
if (propName === "source") {
const object = getStaticValue(context, node.object)
if (object && object.value instanceof RegExp) {
return { value: object.value.source }
}
}
} else if (node.type === "TemplateLiteral") {
const expressions: GetStaticValueResult[] = []
for (const expr of node.expressions) {
const exprValue = getStaticValue(context, expr)
if (!exprValue) {
return null
}
expressions.push(exprValue)
}
let value = node.quasis[0].value.cooked
for (let i = 0; i < expressions.length; ++i) {
value += String(expressions[i].value)
value += node.quasis[i + 1].value.cooked!
}
return { value }
} else if (node.type === "Identifier") {
const deRef = dereferenceVariable(context, node)
if (deRef !== node) {
return getStaticValue(context, deRef)
}
}
return eslintUtils.getStaticValue(node, getScope(context, node))
}
/**
* Gets the scope for the current node
*/
export function getScope(
context: Rule.RuleContext,
currentNode: Node,
): Scope.Scope {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- ignore
const scopeManager: Scope.ScopeManager = (context.getSourceCode() as any)
.scopeManager
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- ignore
let node: any = currentNode
for (; node; node = node.parent || null) {
const scope = scopeManager.acquire(node, false)
if (scope) {
if (scope.type === "function-expression-name") {
return scope.childScopes[0]
}
return scope
}
}
return scopeManager.scopes[0]
}
/**
* Find function node
*/
export function findFunction(
context: Rule.RuleContext,
id: Identifier,
): FunctionDeclaration | FunctionExpression | ArrowFunctionExpression | null {
let target = id
const set = new Set<Identifier>()
for (;;) {
if (set.has(target)) {
return null
}
set.add(target)
const calleeVariable = findVariable(context, target)
if (!calleeVariable) {
return null
}
if (calleeVariable.defs.length === 1) {
const def = calleeVariable.defs[0]
if (def.node.type === "FunctionDeclaration") {
return def.node
}
if (
def.type === "Variable" &&
def.parent.kind === "const" &&
def.node.init
) {
if (
def.node.init.type === "FunctionExpression" ||
def.node.init.type === "ArrowFunctionExpression"
) {
return def.node.init
}
if (def.node.init.type === "Identifier") {
target = def.node.init
continue
}
}
}
return null
}
}
export type KnownMethodCall = CallExpression & {
callee: MemberExpression & { object: Expression; property: Identifier }
arguments: Expression[]
}
/**
* Checks whether given node is expected method call
*/
export function isKnownMethodCall(
node: CallExpression,
methods: Record<string, number>,
): node is KnownMethodCall {
const mem = node.callee
if (
mem.type !== "MemberExpression" ||
mem.computed ||
mem.property.type !== "Identifier"
) {
return false
}
const argLength = methods[mem.property.name]
if (node.arguments.length !== argLength) {
return false
}
if (node.arguments.some((arg) => arg.type === "SpreadElement")) {
return false
}
const object = mem.object
if (object.type === "Super") {
return false
}
return true
}
interface BaseElement {
type: string
range: [number, number]
}
export type ReplacementElement =
| CharacterElement
| DollarElement
| ReferenceElement
export interface CharacterElement extends BaseElement {
type: "CharacterElement"
value: string
}
export interface DollarElement extends BaseElement {
type: "DollarElement"
kind: "$" | "&" | "`" | "'"
}
// $1, $<name>
export interface ReferenceElement extends BaseElement {
type: "ReferenceElement"
ref: number | string
refText: string
}
/**
* Parse replacements string
*/
export function parseReplacements(
context: Rule.RuleContext,
node: Literal,
): ReplacementElement[] {
const stringLiteral = parseStringLiteral(context.getSourceCode().text, {
start: node.range![0],
end: node.range![1],
})
const tokens = stringLiteral.tokens.filter((t) => t.value)
return baseParseReplacements(tokens, (start, end) => {
return {
range: [start.range[0], end.range[1]],
}
})
}
/**
* Creates source range from the given offset range of the value of the given
* string literal.
*
* @param sourceCode The ESLint source code instance.
* @param node The string literal to report.
* @returns
*/
export function getStringValueRange(
sourceCode: SourceCode,
node: Literal & { value: string },
startOffset: number,
endOffset: number,
): AST.Range | null {
if (!node.range) {
// no range information
return null
}
if (node.value.length < endOffset) {
return null
}
try {
const raw = sourceCode.text.slice(node.range[0] + 1, node.range[1] - 1)
let valueIndex = 0
let start: number | null = null
for (const t of parseStringTokens(raw)) {
const endIndex = valueIndex + t.value.length
// find start
if (
start == null &&
valueIndex <= startOffset &&
startOffset < endIndex
) {
start = t.range[0]
}
// find end
if (
start != null &&
valueIndex < endOffset &&
endOffset <= endIndex
) {
const end = t.range[1]
const nodeStart = node.range[0] + 1
return [nodeStart + start, nodeStart + end]
}
valueIndex = endIndex
}
} catch {
// ignore
}
return null
}
/**
* Check if the given expression node is regexp literal.
*/
export function isRegexpLiteral(node: Expression): node is RegExpLiteral {
return node.type === "Literal" && "regex" in node
}
/**
* Check if the given expression node is string literal.
*/
export function isStringLiteral(
node: Expression,
): node is Literal & { value: string } {
return node.type === "Literal" && typeof node.value === "string"
}
/**
* Returns the string value of the property name accessed.
*
* This is guaranteed to return `null` for private properties.
*
* @param node
* @returns
*/
export function getPropertyName(
node: MemberExpression,
context?: Rule.RuleContext,
): string | null {
const prop = node.property
if (prop.type === "PrivateIdentifier") {
return null
}
if (!node.computed) {
return (prop as Identifier).name
}
if (context) {
return getStringIfConstant(context, prop)
}
if (isStringLiteral(prop)) {
return prop.value
}
return null
}
/**
* Converts an range into a source location.
*/
export function astRangeToLocation(
sourceCode: SourceCode,
range: AST.Range,
): AST.SourceLocation {
return {
start: sourceCode.getLocFromIndex(range[0]),
end: sourceCode.getLocFromIndex(range[1]),
}
}
/**
* If the given expression is the identifier of an owned variable, then the
* value of the variable will be returned.
*
* Owned means that the variable is readonly and only referenced by this
* expression.
*
* In all other cases, the given expression will be returned as is.
*
* Note: This will recursively dereference owned variables. I.e. of the given
* identifier resolves to a variable `a` that is assigned an owned variable `b`,
* then this will return the value of `b`. Example:
*
* ```js
* const c = 5;
* const b = c;
* const a = b;
*
* foo(a);
* ```
*
* Dereferencing `a` in `foo(a)` will return `5`.
*/
export function dereferenceOwnedVariable(
context: Rule.RuleContext,
expression: Expression,
): Expression {
if (expression.type === "Identifier") {
const variable = findSimpleVariable(context, expression)
if (!variable) {
// we want a variable with 1 definition
return expression
}
const def = variable.defs[0]
const grandParent = getParent(def.parent)
if (grandParent && grandParent.type === "ExportNamedDeclaration") {
// exported variables are not owned because they can be referenced
// by modules that import this module
return expression
}
// we expect there two be exactly 2 references:
// 1. for initializing the variable
// 2. the reference given to this function
if (variable.references.length !== 2) {
return expression
}
const [initRef, thisRef] = variable.references
if (
!(
initRef.init &&
initRef.writeExpr &&
initRef.writeExpr === def.node.init
) ||
thisRef.identifier !== expression
) {
return expression
}
return dereferenceOwnedVariable(context, def.node.init)
}
return expression
}
/**
* If the given expression is the identifier of a variable, then the value of
* the variable will be returned if that value can be statically known.
*
* This method assumes that the value of the variable is immutable. This is
* important because it means that expression that resolve to primitives
* (numbers, string, ...) behave as expected. However, if the value is mutable
* (e.g. arrays and objects), then the object might be mutated. This is because
* objects are passed by reference. So the reference can be statically known
* (the value of the variable) but the value of the object cannot be statically
* known. If the object is immutable (e.g. RegExp and symbols), then they behave
* like primitives.
*/
export function dereferenceVariable(
context: Rule.RuleContext,
expression: Expression,
): Expression {
if (expression.type === "Identifier") {
const variable = findSimpleVariable(context, expression)
if (variable) {
const def = variable.defs[0]
if (def.node.init) {
if (def.parent.kind === "const") {
// const variables are always what they are initialized to
return dereferenceVariable(context, def.node.init)
}
// we might still be able to dereference var and let variables,
// they just have to never re-assigned
const refs = variable.references
const inits = refs.filter((r) => r.init).length
const reads = refs.filter((r) => r.isReadOnly()).length
if (inits === 1 && reads + inits === refs.length) {
// there is only one init and all other references only read
return dereferenceVariable(context, def.node.init)
}
}
}
}
return expression
} | the_stack |
import React, { useState, useEffect, useRef } from 'react'
import { useRouter } from '../../cloud/lib/router'
import { ThemeProvider } from 'styled-components'
import { useGlobalData } from '../../cloud/lib/stores/globalData'
import { getGlobalData } from '../../cloud/api/global'
import { useEffectOnce } from 'react-use'
import nProgress from 'nprogress'
import { combineProviders } from '../../cloud/lib/utils/context'
import { SettingsProvider, useSettings } from '../../cloud/lib/stores/settings'
import { PreferencesProvider } from '../lib/preferences'
import { SearchProvider } from '../../cloud/lib/stores/search'
import { ExternalEntitiesProvider } from '../../cloud/lib/stores/externalEntities'
import { PageDataProvider } from '../../cloud/lib/stores/pageStore'
import { Mixpanel } from 'mixpanel-browser'
import * as intercom from '../../cloud/lib/intercom'
import { intercomAppId } from '../../cloud/lib/consts'
import CodeMirrorStyle from '../../cloud/components/CodeMirrorStyle'
import { GetInitialPropsParameters } from '../../cloud/interfaces/pages'
import ErrorPage from '../../cloud/components/error/ErrorPage'
import { NavProvider } from '../../cloud/lib/stores/nav'
import { useRealtimeConn } from '../../cloud/lib/stores/realtimeConn'
import { selectV2Theme } from '../../design/lib/styled/styleFunctions'
import { V2ToastProvider } from '../../design/lib/stores/toast'
import { V2EmojiProvider } from '../../design/lib/stores/emoji'
import { V2WindowProvider } from '../../design/lib/stores/window'
import { V2ContextMenuProvider } from '../../design/lib/stores/contextMenu'
import { V2ModalProvider } from '../../design/lib/stores/modal'
import { V2DialogProvider } from '../../design/lib/stores/dialog'
import Toast from '../../design/components/organisms/Toast'
import Dialog from '../../design/components/organisms/Dialog/Dialog'
import MobileContextMenu from './molecules/MobileContextMenu'
import { CommentsProvider } from '../../cloud/lib/stores/comments'
import EmojiPicker from '../../design/components/molecules/EmojiPicker'
import CooperatePage from './pages/CooperatePage'
import RootPage from './pages/RootPage'
import CreateTeamPage from './pages/CreateTeamPage'
import ResourceIndex from './pages/ResourcesPage'
import TeamIndex from './pages/TeamIndex'
import { SidebarCollapseProvider } from '../../cloud/lib/stores/sidebarCollapse'
import DocStatusShowPage from './pages/DocStatusShowPage'
import TagsShowPage from './pages/TagsShowPage'
import OpenInvitePage from './pages/OpenInvitePage'
import SharedDocsListPage from './pages/SharedDocsListPage'
import DeleteTeamPage from './pages/TeamDeletePage'
import DeleteAccountPage from './pages/DeleteAccountPage'
import Modal from './organisms/modals/Modal'
import { AppStatusProvider } from '../lib/appStatus'
import WorkspacePage from './pages/WorkspacePage'
import SettingsPage from './pages/SettingsPage'
import MobileGlobalStyle from './MobileGlobalStyle'
import styled from '../../design/lib/styled'
import Spinner from '../../design/components/atoms/Spinner'
import GlobalStyle from '../../design/components/atoms/GlobalStyle'
import { BaseTheme } from '../../design/lib/styled/types'
import { darkTheme } from '../../design/lib/styled/dark'
const CombinedProvider = combineProviders(
SidebarCollapseProvider,
PreferencesProvider,
SettingsProvider,
SearchProvider,
ExternalEntitiesProvider,
CommentsProvider
)
const V2CombinedProvider = combineProviders(
V2ToastProvider,
V2EmojiProvider,
V2WindowProvider,
V2ContextMenuProvider,
V2ModalProvider,
V2DialogProvider,
CommentsProvider,
AppStatusProvider
)
interface PageInfo {
Component: React.ComponentType<any>
pageProps: any
}
interface PageSpec {
Component: React.ComponentType<any>
getInitialProps?: ({
pathname,
search,
signal,
}: GetInitialPropsParameters) => Promise<any>
}
const Router = () => {
const { pathname, search } = useRouter()
const [pageInfo, setPageInfo] = useState<PageInfo | null>(null)
const { connect } = useRealtimeConn()
const previousPathnameRef = useRef<string | null>(null)
const previousSearchRef = useRef<string | null>(null)
const { initGlobalData, initialized, globalData } = useGlobalData()
const { currentUser, realtimeAuth } = globalData
useEffect(() => {
if (realtimeAuth != null) {
connect(process.env.REALTIME_URL as string, realtimeAuth)
}
}, [realtimeAuth, connect])
useEffect(() => {
if (currentUser == null) {
return
}
const mixpanel = (window as any).mixpanel as Mixpanel
if (mixpanel != null) {
mixpanel.identify(currentUser.id)
mixpanel.people.set({
$first_name: currentUser.displayName,
$last_name: '',
$last_login: new Date(),
})
}
if (intercomAppId != null) {
intercom.boot(intercomAppId, {
name: currentUser.displayName,
user_id: currentUser.id,
})
}
}, [currentUser])
useEffectOnce(() => {
if (intercomAppId == null) {
return
}
intercom.load(intercomAppId)
return () => {
intercom.shutdown()
}
})
useEffect(() => {
if (
previousPathnameRef.current === pathname &&
previousSearchRef.current === search
) {
return
}
console.info('navigate to ', pathname, search)
previousPathnameRef.current = pathname
previousSearchRef.current = search
nProgress.start()
const pageSpec = getPageComponent(pathname)
if (pageSpec == null) {
setPageInfo(null)
nProgress.done()
return
}
const abortController = new AbortController()
Promise.all([
initialized ? null : getGlobalData(),
pageSpec.getInitialProps != null
? pageSpec.getInitialProps({
pathname,
search,
signal: abortController.signal,
})
: {},
])
.then(([globalData, pageData]) => {
if (globalData != null) {
initGlobalData(globalData)
}
setPageInfo({
Component: pageSpec.Component,
pageProps: pageData,
})
nProgress.done()
})
.catch((error: Error) => {
if (error.name === 'AbortError') {
console.warn('Navigation aborted')
console.warn(error)
} else {
console.error(error)
if (!initialized) {
initGlobalData({
teams: [],
invites: [],
})
}
setPageInfo({
Component: ErrorPage,
pageProps: {
error,
},
})
nProgress.done()
}
})
intercom.update()
return () => {
abortController.abort()
}
// Determine which page to show and how to fetch it
// How to fetch does exist in get initial props so we need to determine the component
}, [pathname, search, initialized, initGlobalData])
if (!initialized) {
return (
<SettingsProvider>
<V2ThemeProvider theme={darkTheme}>
<LoadingScreen message='Fetching global data...' />
<GlobalStyle />
</V2ThemeProvider>
</SettingsProvider>
)
}
if (pageInfo == null) {
return (
<SettingsProvider>
<V2ThemeProvider theme={darkTheme}>
<LoadingScreen message='Fetching page data...' />
<GlobalStyle />
</V2ThemeProvider>
</SettingsProvider>
)
}
return (
<PageDataProvider
pageProps={pageInfo.pageProps as any}
navigatingBetweenPage={false}
>
<V2CombinedProvider>
<CombinedProvider>
<NavProvider>
<V2ThemeProvider>
{<pageInfo.Component {...pageInfo.pageProps} />}
<GlobalStyle />
<MobileGlobalStyle />
<CodeMirrorStyle />
<Toast />
<MobileContextMenu />
<EmojiPicker />
<Dialog />
<Modal />
</V2ThemeProvider>
</NavProvider>
</CombinedProvider>
</V2CombinedProvider>
</PageDataProvider>
)
}
export default Router
interface LoadingScreenProps {
message?: string
}
const LoadingScreenContainer = styled.div`
background-color: ${({ theme }) => theme.colors.background.primary};
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
color: ${({ theme }) => theme.colors.text.primary};
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
.message {
margin-left: 5px;
}
`
const LoadingScreen = ({ message }: LoadingScreenProps) => {
return (
<LoadingScreenContainer>
<Spinner />
<p className='message'>{message == null ? 'Loading...' : message}</p>
</LoadingScreenContainer>
)
}
const V2ThemeProvider: React.FC<{ theme?: BaseTheme }> = ({
children,
theme,
}) => {
const { settings } = useSettings()
const { pathname } = useRouter()
return (
<ThemeProvider
theme={
theme != null
? theme
: isHomepagePathname(pathname)
? darkTheme
: selectV2Theme(settings['general.theme'])
}
>
{children}
</ThemeProvider>
)
}
function isHomepagePathname(pathname: string) {
if (pathname.startsWith('/integrations/')) {
return true
}
if (pathname.startsWith('/shared/')) {
return true
}
if (pathname.startsWith('/desktop/')) {
return true
}
switch (pathname) {
case '/':
case '/features':
case '/pricing':
case '/integrations':
case '/signin':
case '/signup':
case '/terms':
case '/policy':
case '/gdpr-policy':
case '/shared':
case '/desktop':
return true
default:
return false
}
}
function getPageComponent(pathname: string): PageSpec | null {
if (pathname === '' || pathname === '/') {
return {
Component: RootPage,
}
}
const [, ...splittedPathnames] = pathname.split('/')
if (splittedPathnames.length >= 1 && splittedPathnames[0] === 'cooperate') {
switch (splittedPathnames[1]) {
case 'team':
return {
Component: CreateTeamPage,
}
default:
return {
Component: CooperatePage,
}
}
}
if (splittedPathnames[0] === 'settings') {
return {
Component: SettingsPage,
getInitialProps: SettingsPage.getInitialProps,
}
}
if (
splittedPathnames.length >= 1 &&
splittedPathnames[0] === 'account' &&
splittedPathnames[1] === 'delete'
) {
return {
Component: DeleteAccountPage,
}
}
if (splittedPathnames.length >= 2) {
switch (splittedPathnames[1]) {
case 'shared':
return {
Component: SharedDocsListPage,
getInitialProps: SharedDocsListPage.getInitialProps,
}
case 'shared':
return {
Component: SharedDocsListPage,
getInitialProps: SharedDocsListPage.getInitialProps,
}
case 'delete':
return {
Component: DeleteTeamPage,
getInitialProps: DeleteTeamPage.getInitialProps,
}
case 'invite':
return {
Component: OpenInvitePage,
getInitialProps: OpenInvitePage.getInitialProps,
}
case 'labels':
return {
Component: TagsShowPage,
getInitialProps: TagsShowPage.getInitialProps,
}
case 'status':
return {
Component: DocStatusShowPage,
getInitialProps: DocStatusShowPage.getInitialProps,
}
case 'workspaces':
return {
Component: WorkspacePage,
getInitialProps: WorkspacePage.getInitialProps,
}
default:
return {
Component: ResourceIndex,
getInitialProps: ResourceIndex.getInitialProps,
}
}
}
if (splittedPathnames.length >= 1) {
return {
Component: TeamIndex,
getInitialProps: TeamIndex.getInitialProps,
}
}
return null
} | the_stack |
import path from 'path';
import fs from 'fs-extra';
import { getTestConfiguration } from '../../test-utils/config';
import { Request, Response } from '../../domain/entity';
import { RequestRepository } from '../../domain/repository';
import { getRequestDirectory } from '../../utils/path';
import { RequestRepositoryFile } from './RequestRepositoryFile';
const MEMENTO_CACHE_DIR = path.join(
__dirname,
'../../../.memento-test-cache-request-repository'
);
const OUTPUT_DIRECTORY = `${MEMENTO_CACHE_DIR}/https___pokeapi-co_api_v2`;
function getRequestRepository() {
return new RequestRepositoryFile({
config: getTestConfiguration({
cacheDirectory: MEMENTO_CACHE_DIR,
targetUrl: 'https://pokeapi.co/api/v2',
}),
});
}
beforeEach(() => fs.remove(MEMENTO_CACHE_DIR));
afterAll(() => fs.remove(MEMENTO_CACHE_DIR));
describe('persistResponseForRequest', () => {
describe('JSON support', () => {
const CASES = [
'APPLICATION/JSON',
'application/json',
'application/json; charset=utf-8',
];
CASES.forEach(contentType => {
it(`should persist the ${contentType} response and its meta data`, async () => {
// Given
const requestRepository = getRequestRepository();
const inputRequest = new Request(
'GET',
'/pokemon/pikachu',
{
authorization: 'Bearer token',
},
''
);
const inputResponse = new Response(
200,
{
'content-type': contentType,
},
Buffer.from(JSON.stringify({ id: 'user-1', name: 'John Doe' })),
55
);
// When
await requestRepository.persistResponseForRequest(
inputRequest,
inputResponse
);
const metadataContent = await fs.readJSON(
`${OUTPUT_DIRECTORY}/${inputRequest.id}/metadata.json`
);
const bodyContent = await fs.readJSON(
`${OUTPUT_DIRECTORY}/${inputRequest.id}/body.json`
);
//Then
expect(metadataContent).toEqual({
method: 'GET',
url: '/pokemon/pikachu',
requestBody: '',
status: 200,
requestHeaders: {
authorization: 'Bearer token',
},
responseHeaders: {
'content-type': contentType,
},
responseTime: 55,
});
expect(bodyContent).toEqual({
id: 'user-1',
name: 'John Doe',
});
});
});
});
describe('XML support', () => {
const CASES = [
'APPLICATION/XML',
'application/xml',
'application/xml; charset=utf-8',
'TEXT/XML',
'text/xml',
];
CASES.forEach(contentType => {
it(`should persist the ${contentType} response and its meta data`, async () => {
// Given
const requestRepository = getRequestRepository();
const inputRequest = new Request('GET', '/notes', {}, '');
const inputResponse = new Response(
200,
{
'content-type': contentType,
},
Buffer.from(
'<Note><Author>Jane</Author><Content>Hello world</Content></Note>'
),
55
);
// When
await requestRepository.persistResponseForRequest(
inputRequest,
inputResponse
);
const metadataContent = await fs.readJSON(
`${OUTPUT_DIRECTORY}/${inputRequest.id}/metadata.json`
);
const bodyContent = await fs.readFile(
`${OUTPUT_DIRECTORY}/${inputRequest.id}/body.xml`,
'utf-8'
);
//Then
expect(metadataContent).toEqual({
method: 'GET',
url: '/notes',
requestBody: '',
status: 200,
requestHeaders: {},
responseHeaders: {
'content-type': contentType,
},
responseTime: 55,
});
expect(bodyContent).toEqual(
'<Note><Author>Jane</Author><Content>Hello world</Content></Note>'
);
});
});
});
it('should persist other types as txt with their meta data', async () => {
// Given
const requestRepository = getRequestRepository();
const inputRequest = new Request('GET', '/text', {}, '');
const inputResponse = new Response(
200,
{
'content-type': 'text/plain',
},
Buffer.from('Hello world'),
66
);
// When
await requestRepository.persistResponseForRequest(
inputRequest,
inputResponse
);
const metadataContent = await fs.readJSON(
`${OUTPUT_DIRECTORY}/${inputRequest.id}/metadata.json`
);
const bodyContent = await fs.readFile(
`${OUTPUT_DIRECTORY}/${inputRequest.id}/body.txt`,
'utf-8'
);
//Then
expect(metadataContent).toEqual({
method: 'GET',
status: 200,
url: '/text',
requestBody: '',
requestHeaders: {},
responseHeaders: {
'content-type': 'text/plain',
},
responseTime: 66,
});
expect(bodyContent).toEqual('Hello world');
});
it('should persist no content-type as txt with their meta data', async () => {
// Given
const requestRepository = getRequestRepository();
const inputRequest = new Request('GET', '/text', {}, '');
const inputResponse = new Response(200, {}, Buffer.from('Hello world'), 77);
// When
await requestRepository.persistResponseForRequest(
inputRequest,
inputResponse
);
const metadataContent = await fs.readJSON(
`${OUTPUT_DIRECTORY}/${inputRequest.id}/metadata.json`
);
const bodyContent = await fs.readFile(
`${OUTPUT_DIRECTORY}/${inputRequest.id}/body`,
'utf-8'
);
//Then
expect(metadataContent).toEqual({
method: 'GET',
status: 200,
url: '/text',
requestBody: '',
requestHeaders: {},
responseHeaders: {},
responseTime: 77,
});
expect(bodyContent).toEqual('Hello world');
});
it('should persist very long URLs (fixes #30)', async () => {
// Given
const requestRepository = getRequestRepository();
const inputRequest = new Request(
'GET',
'/really_long_url?with=some&query=parameters[get__really_long_urlget__really_long_urlget__really_long_urlget__really_long_urlget__really_long_urlget__really_long_urlget__really_long_urlget__really_long_urlget__really_long_urlget__really_long_urlget__really_long_urlget__really_long_urlget__really_long_urlget__really_long_urlget__really_long_urlget__really_long_url]',
{},
''
);
const inputResponse = new Response(200, {}, Buffer.from('Hello world'), 77);
// When
await requestRepository.persistResponseForRequest(
inputRequest,
inputResponse
);
const metadataContent = await fs.readJSON(
`${OUTPUT_DIRECTORY}/${inputRequest.id}/metadata.json`
);
const bodyContent = await fs.readFile(
`${OUTPUT_DIRECTORY}/${inputRequest.id}/body`,
'utf-8'
);
//Then
expect(metadataContent).toEqual({
method: 'GET',
status: 200,
url:
'/really_long_url?with=some&query=parameters[get__really_long_urlget__really_long_urlget__really_long_urlget__really_long_urlget__really_long_urlget__really_long_urlget__really_long_urlget__really_long_urlget__really_long_urlget__really_long_urlget__really_long_urlget__really_long_urlget__really_long_urlget__really_long_urlget__really_long_urlget__really_long_url]',
requestBody: '',
requestHeaders: {},
responseHeaders: {},
responseTime: 77,
});
expect(bodyContent).toEqual('Hello world');
});
});
describe('getResponseByRequestId', () => {
let requestRepository: RequestRepository;
beforeEach(async () => {
requestRepository = getRequestRepository();
await requestRepository.persistResponseForRequest(
new Request(
'GET',
'/pokemon/pikachu',
{
authorization: 'Bearer token',
},
''
),
new Response(
200,
{
'content-type': 'application/json',
},
Buffer.from(JSON.stringify({ id: 'user-1', name: 'John Doe' })),
88
)
);
});
it('should deserialize the response', async () => {
// When
const cachedResponse = await requestRepository.getResponseByRequestId(
new Request(
'GET',
'/pokemon/pikachu',
{
authorization: 'Bearer token',
},
''
).id
);
//Then
expect(cachedResponse).toEqual(
new Response(
200,
{
'content-type': 'application/json',
},
Buffer.from(JSON.stringify({ id: 'user-1', name: 'John Doe' })),
88
)
);
});
it('should return null when the request does not exist', async () => {
// Given
const requestId = 'does-not-exist';
// When
const response = await requestRepository.getResponseByRequestId(requestId);
//Then
expect(response).toBeNull();
});
it('should set the responseTime to 0 for older files', async () => {
// Given
const request = new Request(
'GET',
'/pokemon/pikachu',
{
authorization: 'Bearer token',
},
''
);
const directory = getRequestDirectory(
MEMENTO_CACHE_DIR,
'https://pokeapi.co/api/v2',
request
);
const metadataPath = path.join(directory, 'metadata.json');
const metadata = await fs.readJSON(metadataPath);
delete metadata['responseTime'];
await fs.writeJson(metadataPath, metadata);
// When
const response = await requestRepository.getResponseByRequestId(request.id);
// Then
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
expect(response!.responseTimeInMs).toEqual(0);
});
});
describe('getAllRequests', () => {
let requestRepository: RequestRepository;
beforeEach(async () => {
requestRepository = getRequestRepository();
const request1 = new Request(
'post',
'/pokemon',
{
'x-custom-1': 'header-1',
},
JSON.stringify({
name: 'Bulbasaur',
})
);
const response1 = new Response(
201,
{
'content-type': 'application/json',
'x-custom-2': 'header-2',
},
Buffer.from(
JSON.stringify({
id: 'pokemon-1',
name: 'Bulbasaur',
})
),
99
);
const request2 = new Request(
'get',
'/pokemon/mew',
{
'x-custom-3': 'header-3',
},
''
);
const response2 = new Response(
200,
{
'content-type': 'application/json',
'x-custom-4': 'header-4',
},
Buffer.from(
JSON.stringify({
id: 'pokemon-151',
name: 'Mew',
})
),
100
);
await Promise.all([
requestRepository.persistResponseForRequest(request1, response1),
requestRepository.persistResponseForRequest(request2, response2),
]);
});
it('should return the requests', async () => {
// When
const requests = await requestRepository.getAllRequests();
//Then
expect(requests).toEqual([
new Request(
'post',
'/pokemon',
{
'x-custom-1': 'header-1',
},
JSON.stringify({
name: 'Bulbasaur',
})
),
new Request(
'get',
'/pokemon/mew',
{
'x-custom-3': 'header-3',
},
''
),
]);
});
});
describe('getRequestById', () => {
let requestRepository: RequestRepository;
beforeEach(async () => {
requestRepository = getRequestRepository();
const request1 = new Request(
'post',
'/pokemon',
{
'x-custom-1': 'header-1',
},
JSON.stringify({
name: 'Bulbasaur',
})
);
const response1 = new Response(
201,
{
'content-type': 'application/json',
'x-custom-2': 'header-2',
},
Buffer.from(
JSON.stringify({
id: 'pokemon-1',
name: 'Bulbasaur',
})
),
110
);
const request2 = new Request(
'get',
'/pokemon/mew',
{
'x-custom-3': 'header-3',
},
''
);
const response2 = new Response(
200,
{
'content-type': 'application/json',
'x-custom-4': 'header-4',
},
Buffer.from(
JSON.stringify({
id: 'pokemon-151',
name: 'Mew',
})
),
120
);
await Promise.all([
requestRepository.persistResponseForRequest(request1, response1),
requestRepository.persistResponseForRequest(request2, response2),
]);
});
it('should return the request when found', async () => {
// Given
const requestId = 'f8a26f76bdcf7d5b69d03c70c7d689727f1ec283';
// When
const request = await requestRepository.getRequestById(requestId);
//Then
expect(request).toEqual(
new Request(
'post',
'/pokemon',
{
'x-custom-1': 'header-1',
},
JSON.stringify({
name: 'Bulbasaur',
})
)
);
});
it('should return null when not found', async () => {
// Given
const requestId = 'not-found-id';
// When
const request = await requestRepository.getRequestById(requestId);
//Then
expect(request).toEqual(null);
});
});
describe('deleteAll', () => {
let requestRepository: RequestRepository;
beforeEach(async () => {
requestRepository = getRequestRepository();
const request1 = new Request(
'post',
'/pokemon',
{
'x-custom-1': 'header-1',
},
JSON.stringify({
name: 'Bulbasaur',
})
);
const response1 = new Response(
201,
{
'content-type': 'application/json',
'x-custom-2': 'header-2',
},
Buffer.from(
JSON.stringify({
id: 'pokemon-1',
name: 'Bulbasaur',
})
),
130
);
const request2 = new Request(
'get',
'/pokemon/mew',
{
'x-custom-3': 'header-3',
},
''
);
const response2 = new Response(
200,
{
'content-type': 'application/json',
'x-custom-4': 'header-4',
},
Buffer.from(
JSON.stringify({
id: 'pokemon-151',
name: 'Mew',
})
),
140
);
await Promise.all([
requestRepository.persistResponseForRequest(request1, response1),
requestRepository.persistResponseForRequest(request2, response2),
]);
});
it('should delete all requests', async () => {
// Given
const request1Id = 'fb5ca369347c9379a0c4535f1bafacb649320d77';
const request2Id = 'f8a26f76bdcf7d5b69d03c70c7d689727f1ec283';
const [request1Before, request2Before] = await Promise.all([
requestRepository.getRequestById(request1Id),
requestRepository.getRequestById(request2Id),
]);
expect(request1Before).toBeTruthy();
expect(request2Before).toBeTruthy();
// When
await requestRepository.deleteAll();
//Then
const [request1After, request2After] = await Promise.all([
requestRepository.getRequestById(request1Id),
requestRepository.getRequestById(request2Id),
]);
expect(request1After).toBeNull();
expect(request2After).toBeNull();
});
});
describe('deleteByRequestId', () => {
let requestRepository: RequestRepository;
beforeEach(async () => {
requestRepository = getRequestRepository();
const request1 = new Request(
'post',
'/pokemon',
{
'x-custom-1': 'header-1',
},
JSON.stringify({
name: 'Bulbasaur',
})
);
const response1 = new Response(
201,
{
'content-type': 'application/json',
'x-custom-2': 'header-2',
},
Buffer.from(
JSON.stringify({
id: 'pokemon-1',
name: 'Bulbasaur',
})
),
150
);
const request2 = new Request(
'get',
'/pokemon/mew',
{
'x-custom-3': 'header-3',
},
''
);
const response2 = new Response(
200,
{
'content-type': 'application/json',
'x-custom-4': 'header-4',
},
Buffer.from(
JSON.stringify({
id: 'pokemon-151',
name: 'Mew',
})
),
160
);
await Promise.all([
requestRepository.persistResponseForRequest(request1, response1),
requestRepository.persistResponseForRequest(request2, response2),
]);
});
it('should delete the request', async () => {
// Given
const requestId = 'fb5ca369347c9379a0c4535f1bafacb649320d77';
const request1Before = await requestRepository.getRequestById(requestId);
expect(request1Before).toBeTruthy();
// When
await requestRepository.deleteByRequestId(requestId);
const request1After = await requestRepository.getRequestById(requestId);
//Then
expect(request1After).toBeNull();
});
}); | the_stack |
import type { FileCoverageData } from "istanbul-lib-coverage";
import { Stmt, Expr } from "../parser";
import { Location, isToken, Lexeme } from "../lexer";
import { BrsInvalid, BrsType } from "../brsTypes";
import { isStatement } from "../parser/Statement";
/** Keeps track of the number of hits on a given statement or expression. */
interface StatementCoverage {
/** Number of times the interpreter has executed/evaluated this statement. */
hits: number;
/** Combine expressions and statements because we need to log some expressions to get the coverage report. */
statement: Expr.Expression | Stmt.Statement;
}
export class FileCoverage implements Expr.Visitor<BrsType>, Stmt.Visitor<BrsType> {
private statements = new Map<string, StatementCoverage>();
constructor(readonly filePath: string) {}
/**
* Returns the StatementCoverage object for a given statement.
* @param statement statement for which to get coverage.
*/
private get(statement: Expr.Expression | Stmt.Statement) {
let key = this.getStatementKey(statement);
return this.statements.get(key);
}
/**
* Creates a StatementCoverage object for a given statement.
* @param statement statement to add.
*/
private add(statement: Expr.Expression | Stmt.Statement) {
let key = this.getStatementKey(statement);
this.statements.set(key, { hits: 0, statement });
}
/**
* Generates a key for the statement using its location and type.
* @param statement statement for which to generate a key.
*/
getStatementKey(statement: Expr.Expression | Stmt.Statement) {
let { start, end } = statement.location;
let kind = isStatement(statement) ? "stmt" : "expr";
return `${kind}:${statement.type}:${start.line},${start.column}-${end.line},${end.column}`;
}
/**
* Logs a hit to a particular statement, indicating the statement was used.
* @param statement statement for which to log a hit
*/
logHit(statement: Expr.Expression | Stmt.Statement) {
let coverage = this.get(statement);
if (coverage) {
coverage.hits++;
}
}
/**
* Converts the coverage data to a POJO that's more friendly for consumers.
*/
getCoverage(): FileCoverageData {
let coverageSummary: FileCoverageData = {
path: this.filePath,
statementMap: {},
fnMap: {},
branchMap: {},
s: {},
f: {},
b: {},
};
this.statements.forEach(({ statement, hits }, key) => {
if (statement instanceof Stmt.If) {
let locations: Location[] = [];
let branchHits: number[] = [];
// Add the "if" coverage
let thenBranchCoverage = this.get(statement.thenBranch);
if (thenBranchCoverage) {
locations.push({
...statement.location,
end: statement.condition.location.end,
});
branchHits.push(thenBranchCoverage.hits);
}
// the condition is a statement as well as a branch, so put it in the statement map
let ifCondition = this.get(statement.condition);
if (ifCondition) {
coverageSummary.statementMap[`${key}.if`] = statement.condition.location;
coverageSummary.s[`${key}.if`] = ifCondition.hits;
}
// Add the "else if" coverage
statement.elseIfs?.forEach((branch, index) => {
let elseIfCoverage = this.get(branch.condition);
if (elseIfCoverage) {
// the condition is a statement as well as a branch, so put it in the statement map
coverageSummary.statementMap[`${key}.elseif-${index}`] =
branch.condition.location;
coverageSummary.s[`${key}.elseif-${index}`] = elseIfCoverage.hits;
// add to the list of branches
let elseIfBlock = this.get(branch.thenBranch);
if (elseIfBlock) {
// use the tokens as the start for the branch rather than the condition
let start =
statement.tokens.elseIfs?.[index].location.start ||
branch.condition.location.start;
locations.push({ ...branch.condition.location, start });
branchHits.push(elseIfBlock.hits);
}
}
});
// Add the "else" coverage
if (statement.elseBranch) {
let elseCoverage = this.get(statement.elseBranch);
if (elseCoverage) {
// use the tokens as the start rather than the condition
let start =
statement.tokens.else?.location.start ||
statement.elseBranch.location.start;
locations.push({ ...statement.elseBranch.location, start });
branchHits.push(elseCoverage.hits);
}
}
coverageSummary.branchMap[key] = {
loc: statement.location,
type: "if",
locations,
line: statement.location.start.line,
};
coverageSummary.b[key] = branchHits;
} else if (statement instanceof Stmt.Function) {
// Named functions
let functionCoverage = this.get(statement.func.body);
if (functionCoverage) {
coverageSummary.fnMap[key] = {
name: statement.name.text,
loc: statement.location,
decl: {
...statement.func.keyword.location,
end: statement.name.location.end,
},
line: statement.location.start.line,
};
coverageSummary.f[key] = functionCoverage.hits;
}
} else if (statement instanceof Expr.Function) {
// Anonymous functions
let functionCoverage = this.get(statement.body);
if (functionCoverage) {
coverageSummary.fnMap[key] = {
name: "[Function]",
loc: statement.location,
decl: statement.keyword.location,
line: statement.location.start.line,
};
coverageSummary.f[key] = functionCoverage.hits;
}
} else if (
statement instanceof Expr.Binary &&
(statement.token.kind === Lexeme.And || statement.token.kind === Lexeme.Or)
) {
let locations: Location[] = [];
let branchHits: number[] = [];
let leftCoverage = this.get(statement.left);
if (leftCoverage) {
locations.push(statement.left.location);
branchHits.push(leftCoverage.hits);
}
let rightCoverage = this.get(statement.right);
if (rightCoverage) {
locations.push(statement.right.location);
branchHits.push(rightCoverage.hits);
}
coverageSummary.branchMap[key] = {
loc: statement.location,
type: statement.token.kind,
locations,
line: statement.location.start.line,
};
coverageSummary.b[key] = branchHits;
// this is a statement as well as a branch, so put it in the statement map
coverageSummary.statementMap[key] = statement.location;
coverageSummary.s[key] = hits;
} else if (
isStatement(statement) &&
!(statement instanceof Stmt.Block) // blocks are part of other statements, so don't include them
) {
coverageSummary.statementMap[key] = statement.location;
coverageSummary.s[key] = hits;
}
});
return coverageSummary;
}
/**
* STATEMENTS
*/
visitAssignment(statement: Stmt.Assignment) {
this.evaluate(statement.value);
return BrsInvalid.Instance;
}
visitExpression(statement: Stmt.Expression) {
this.evaluate(statement.expression);
return BrsInvalid.Instance;
}
visitExitFor(statement: Stmt.ExitFor): never {
throw new Stmt.ExitForReason(statement.location);
}
visitExitWhile(statement: Stmt.ExitWhile): never {
throw new Stmt.ExitWhileReason(statement.location);
}
visitPrint(statement: Stmt.Print) {
statement.expressions.forEach((exprOrToken) => {
if (!isToken(exprOrToken)) {
this.evaluate(exprOrToken);
}
});
return BrsInvalid.Instance;
}
visitIf(statement: Stmt.If) {
this.evaluate(statement.condition);
this.execute(statement.thenBranch);
statement.elseIfs?.forEach((elseIf) => {
this.evaluate(elseIf.condition);
this.execute(elseIf.thenBranch);
});
if (statement.elseBranch) {
this.execute(statement.elseBranch);
}
return BrsInvalid.Instance;
}
visitBlock(block: Stmt.Block) {
block.statements.forEach((statement) => this.execute(statement));
return BrsInvalid.Instance;
}
visitFor(statement: Stmt.For) {
this.execute(statement.counterDeclaration);
this.evaluate(statement.counterDeclaration.value);
this.evaluate(statement.finalValue);
this.evaluate(statement.increment);
this.execute(statement.body);
return BrsInvalid.Instance;
}
visitForEach(statement: Stmt.ForEach) {
this.evaluate(statement.target);
this.execute(statement.body);
return BrsInvalid.Instance;
}
visitWhile(statement: Stmt.While) {
this.evaluate(statement.condition);
this.execute(statement.body);
return BrsInvalid.Instance;
}
visitNamedFunction(statement: Stmt.Function) {
// don't record the Expr.Function so that we don't double-count named functions.
this.execute(statement.func.body);
return BrsInvalid.Instance;
}
visitReturn(statement: Stmt.Return): never {
if (!statement.value) {
throw new Stmt.ReturnValue(statement.tokens.return.location);
}
let toReturn = this.evaluate(statement.value);
throw new Stmt.ReturnValue(statement.tokens.return.location, toReturn);
}
visitDottedSet(statement: Stmt.DottedSet) {
this.evaluate(statement.obj);
this.evaluate(statement.value);
return BrsInvalid.Instance;
}
visitIndexedSet(statement: Stmt.IndexedSet) {
this.evaluate(statement.obj);
this.evaluate(statement.index);
this.evaluate(statement.value);
return BrsInvalid.Instance;
}
visitIncrement(statement: Stmt.Increment) {
this.evaluate(statement.value);
return BrsInvalid.Instance;
}
visitLibrary(statement: Stmt.Library) {
return BrsInvalid.Instance;
}
visitDim(statement: Stmt.Dim) {
statement.dimensions.forEach((expr) => this.evaluate(expr));
return BrsInvalid.Instance;
}
/**
* EXPRESSIONS
*/
visitBinary(expression: Expr.Binary) {
this.evaluate(expression.left);
this.evaluate(expression.right);
return BrsInvalid.Instance;
}
visitCall(expression: Expr.Call) {
this.evaluate(expression.callee);
expression.args.map(this.evaluate, this);
return BrsInvalid.Instance;
}
visitAnonymousFunction(func: Expr.Function) {
this.execute(func.body);
return BrsInvalid.Instance;
}
visitDottedGet(expression: Expr.DottedGet) {
this.evaluate(expression.obj);
return BrsInvalid.Instance;
}
visitIndexedGet(expression: Expr.IndexedGet) {
this.evaluate(expression.obj);
this.evaluate(expression.index);
return BrsInvalid.Instance;
}
visitGrouping(expression: Expr.Grouping) {
this.evaluate(expression.expression);
return BrsInvalid.Instance;
}
visitLiteral(expression: Expr.Literal) {
return BrsInvalid.Instance;
}
visitArrayLiteral(expression: Expr.ArrayLiteral) {
expression.elements.forEach((expr) => this.evaluate(expr));
return BrsInvalid.Instance;
}
visitAALiteral(expression: Expr.AALiteral) {
expression.elements.forEach((member) => this.evaluate(member.value));
return BrsInvalid.Instance;
}
visitUnary(expression: Expr.Unary) {
this.evaluate(expression.right);
return BrsInvalid.Instance;
}
visitVariable(expression: Expr.Variable) {
return BrsInvalid.Instance;
}
evaluate(this: FileCoverage, expression: Expr.Expression) {
this.add(expression);
return expression.accept<BrsType>(this);
}
execute(this: FileCoverage, statement: Stmt.Statement): BrsType {
this.add(statement);
try {
return statement.accept<BrsType>(this);
} catch (err) {
if (
!(
err instanceof Stmt.ReturnValue ||
err instanceof Stmt.ExitFor ||
err instanceof Stmt.ExitForReason ||
err instanceof Stmt.ExitWhile ||
err instanceof Stmt.ExitWhileReason
)
) {
throw err;
}
}
return BrsInvalid.Instance;
}
} | the_stack |
import * as d3 from 'd3';
import _ from 'lodash';
import { observer } from 'mobx-react';
import React, { FunctionComponent, useEffect, useRef } from 'react';
import { tooSmall } from '~/domain/misc';
import { Line2, utils as gutils, Vec2 } from '~/domain/geometry';
import {
Arrow,
ArrowColor,
ArrowEnding,
ArrowPath,
ArrowPathsMap,
EndingFigure,
InnerEnding,
} from '~/domain/layout/abstract/arrows';
import { colors, sizes } from '~/ui/vars';
import { chunks } from '~/utils/iter-tools';
export interface Props {
arrows: ArrowPathsMap;
}
interface FigureData {
id: string;
isStart: boolean;
figure: EndingFigure;
color: ArrowColor;
coords: Vec2;
direction: Vec2;
}
interface ArrowData {
color: ArrowColor;
points: Array<Vec2>;
handles: [Vec2, Vec2][];
}
type RenderingArrow = [string, ArrowData];
interface FeetData {
id: string;
// NOTE: treat this field as outer connector coords
endingCoords: Vec2;
// NOTE: coords of inner "access point"
innerCoords: Vec2;
colors: Set<ArrowColor>;
}
// NOTE: returns stroke and fill colors
const figureColorProps = (fd: FigureData): [string, string] => {
if (fd.figure === EndingFigure.Circle) {
switch (fd.color) {
case ArrowColor.Neutral:
return [colors.connectorStroke, colors.connectorFill];
case ArrowColor.Red:
return [colors.connectorStrokeRed, colors.connectorFillRed];
case ArrowColor.Green:
return [colors.connectorStrokeGreen, colors.connectorFillGreen];
}
} else if (fd.figure === EndingFigure.Plate) {
switch (fd.color) {
case ArrowColor.Neutral:
return [colors.startPlateStroke, colors.startPlateFill];
case ArrowColor.Red:
return [colors.connectorStrokeRed, colors.connectorFillRed];
case ArrowColor.Green:
return [colors.connectorStrokeGreen, colors.connectorFillGreen];
}
} else if (fd.figure === EndingFigure.Arrow) {
switch (fd.color) {
case ArrowColor.Neutral:
return [colors.connectorStroke, colors.connectorStroke];
case ArrowColor.Red:
return [colors.connectorStrokeRed, colors.connectorStrokeRed];
case ArrowColor.Green:
return [colors.connectorStrokeGreen, colors.connectorStrokeGreen];
}
}
return [colors.arrowStroke, colors.arrowStroke];
};
const arrowLine = (points: Vec2[]): string => {
if (points.length < 2) return '';
if (points.length === 2) {
const [a, b] = points;
return `M ${a.x} ${a.y} L${b.x} ${b.y}`;
}
const first = points[0];
const last = points[points.length - 1];
const r = sizes.arrowRadius;
let line = `M ${first.x} ${first.y}`;
chunks(points, 3, 2).forEach((chunk: Vec2[]) => {
const [a, b, c] = chunk;
let [d, e, angle] = gutils.roundCorner(r, [a, b, c]);
// This case occurs much more rarely than others, so using roundCorner
// one more time is ok since angle computaion is part of entire function
if (angle < Math.PI / 4) {
[d, e, angle] = gutils.roundCorner(r * Math.sin(angle), [a, b, c]);
}
const ab = Vec2.from(b.x - a.x, b.y - a.y);
const bc = Vec2.from(c.x - b.x, c.y - b.y);
const sweep = ab.isClockwise(bc) ? 0 : 1;
line += `
L ${d.x} ${d.y}
A ${r} ${r} 0 0 ${sweep} ${e.x} ${e.y}
`;
});
line += `L ${last.x} ${last.y}`;
return line;
};
const startPlatePath = (d: any) => {
const { x, y } = d.coords;
// prettier-ignore
const r = 3, w = 5, h = 20;
const tr = `a ${r} ${r} 0 0 1 ${r} ${r}`;
const br = `a ${r} ${r} 0 0 1 -${r} ${r}`;
return `
M ${x - 1} ${y - h / 2}
h ${w - r}
${tr}
v ${h - 2 * r}
${br}
h -${w - r}
z
`;
};
const generalExit = (exit: any) => {
exit.remove();
};
const figureFillColor = (fd: FigureData): string => {
const [_, fill] = figureColorProps(fd);
return fill;
};
const figureStrokeColor = (fd: FigureData): string => {
const [stroke, _] = figureColorProps(fd);
return stroke;
};
const startPlatesEnter = (enter: any) => {
return enter
.append('path')
.attr('fill', figureFillColor)
.attr('stroke', figureStrokeColor)
.attr('stroke-width', sizes.linkWidth)
.attr('d', startPlatePath);
};
const startPlatesUpdate = (update: any) => {
// XXX: why d3.select('g path').attr(...) is not working?
return update.each((d: any, i: any, e: any) => {
d3.select(e[i])
.select('path')
.attr('d', startPlatePath)
.attr('stroke', figureStrokeColor as any);
});
};
export const arrowTriangle = (handle: [Vec2, Vec2] | null): string => {
if (handle == null) return '';
const [start, end] = handle;
const width = start.distance(end);
const line = Line2.throughPoints(start, end);
const side = line.normal.mul(width / 2);
const baseA = start.add(side);
const baseB = start.sub(side);
const sweep = gutils.pointSideOfLine(start, end, baseA) > 0 ? 0 : 1;
const r = 2;
const [ar1, ar2] = gutils.roundCorner(r, [start, baseA, end]);
const [br1, br2] = gutils.roundCorner(r, [start, baseB, end]);
const [er1, er2] = gutils.roundCorner(r, [baseA, end, baseB]);
return `
M ${start.x} ${start.y}
L ${ar1.x} ${ar1.y}
A ${r} ${r} 0 0 ${sweep} ${ar2.x} ${ar2.y}
L ${er1.x} ${er1.y}
A ${r} ${r} 0 0 ${sweep} ${er2.x} ${er2.y}
L ${br2.x} ${br2.y}
A ${r} ${r} 0 0 ${sweep} ${br1.x} ${br1.y}
Z
`;
};
const arrowHandleId = (handle: [Vec2, Vec2]): string => {
const [from, to] = handle;
const mid = gutils.linterp2(from, to, 0.5);
// WARN: precision lose here
return `${Math.trunc(mid.x)},${Math.trunc(mid.y)}`;
};
const arrowHandleEnter = (enter: any) => {
return enter
.append('path')
.attr('class', 'handle')
.attr('fill', colors.arrowHandle)
.attr('stroke', 'none')
.attr('d', (handle: [Vec2, Vec2]) => arrowTriangle(handle));
};
const arrowHandleUpdate = (update: any) => {
return update.attr('d', (handle: [Vec2, Vec2]) => arrowTriangle(handle));
};
const arrowStrokeColor = (ad: RenderingArrow) => {
switch (ad[1].color) {
case ArrowColor.Neutral:
return colors.arrowStroke;
case ArrowColor.Red:
return colors.arrowStrokeRed;
case ArrowColor.Green:
return colors.arrowStrokeGreen;
}
return ArrowColor.Neutral;
};
const arrowsEnter = (enter: any) => {
const arrowGroup = enter
.append('g')
.attr('class', (d: RenderingArrow) => d[0]);
arrowGroup
.append('path')
.attr('class', 'line')
.attr('stroke', arrowStrokeColor)
.attr('stroke-width', sizes.linkWidth)
.attr('fill', 'none')
.attr('d', (d: RenderingArrow) => arrowLine(d[1].points));
arrowGroup
.selectAll('path.handle')
.data((d: RenderingArrow) => d[1].handles, arrowHandleId)
.join(arrowHandleEnter, _.identity, generalExit);
return arrowGroup;
};
const arrowsUpdate = (update: any) => {
update
.select('path.line')
.attr('d', (d: RenderingArrow) => arrowLine(d[1].points))
.attr('stroke', arrowStrokeColor);
update
.selectAll('path.handle')
.data((d: RenderingArrow) => d[1].handles, arrowHandleId)
.join(arrowHandleEnter, arrowHandleUpdate, generalExit);
return update;
};
const feetHelpers = {
setPositions(group: any) {
return group
.attr('x1', (d: FeetData) => d.endingCoords.x)
.attr('y1', (d: FeetData) => d.endingCoords.y)
.attr('x2', (d: FeetData) => d.innerCoords.x)
.attr('y2', (d: FeetData) => d.innerCoords.y);
},
innerStrokeColor(d: FeetData) {
const feetColors = d.colors;
if (feetColors.has(ArrowColor.Red)) {
return colors.feetRedStroke;
}
return colors.feetNeutralStroke;
},
innerStrokeStyle(d: FeetData) {
const feetColors = d.colors;
return feetColors.size > 1 ? '5 4' : undefined;
},
};
const feetsEnter = (enter: any) => {
const feetGroup = enter.append('g').attr('class', (d: FeetData) => d.id);
feetGroup
.append('line')
.attr('class', 'outer')
.attr('stroke-width', sizes.feetOuterWidth)
.attr('stroke', colors.feetOuterStroke)
.call(feetHelpers.setPositions);
feetGroup
.append('line')
.attr('class', 'inner')
.attr('stroke', feetHelpers.innerStrokeColor)
.attr('stroke-width', sizes.feetInnerWidth)
.attr('stroke-dasharray', feetHelpers.innerStrokeStyle)
.call(feetHelpers.setPositions);
return feetGroup;
};
const feetsUpdate = (update: any) => {
update.select('line.outer').call(feetHelpers.setPositions);
update
.select('line.inner')
.attr('stroke', feetHelpers.innerStrokeColor)
.attr('stroke-dasharray', feetHelpers.innerStrokeStyle)
.call(feetHelpers.setPositions);
return update;
};
const trianglePropsSet = (group: any) => {
const triangleW = sizes.arrowHandleWidth;
return group
.attr('fill', figureFillColor)
.attr('stroke', figureStrokeColor)
.attr('d', (fd: FigureData) => {
const triangleStart = fd.coords.sub(fd.direction.mul(triangleW));
const triangleEnd = fd.coords;
return arrowTriangle([triangleStart, triangleEnd]);
});
};
const triangleEndingEnter = (enter: any) => {
return enter.append('path').call(trianglePropsSet);
};
const triangleEndingUpdate = (update: any) => {
return update.select('path').call(trianglePropsSet);
};
const connectorPropsSet = (group: any) => {
return group
.attr('cx', (d: any) => d.coords.x)
.attr('cy', (d: any) => d.coords.y)
.attr('r', 7.5)
.attr('stroke', figureStrokeColor)
.attr('stroke-width', sizes.connectorWidth)
.attr('fill', figureFillColor);
};
const connectorsEnter = (enter: any) => {
return enter.append('circle').call(connectorPropsSet);
};
const connectorsUpdate = (update: any) => {
return update.select('circle').call(connectorPropsSet);
};
const figuresEnter = (enter: any) => {
return enter
.append('g')
.attr('class', (d: FigureData) => d.id)
.each((d: FigureData, i: number, group: any) => {
const figureGroup = d3.select(group[i]);
if (d.figure === EndingFigure.Plate) {
figureGroup.call(startPlatesEnter);
} else if (d.figure === EndingFigure.Circle) {
figureGroup.call(connectorsEnter);
} else if (d.figure === EndingFigure.Arrow) {
figureGroup.call(triangleEndingEnter);
} else {
throw new Error(
`enter: rendering of ${d.figure} ending figure is not implemented`,
);
}
});
};
const figuresUpdate = (update: any) => {
return update.each((d: FigureData, i: number, group: any) => {
const figureGroup = d3.select(group[i]);
if (d.figure === EndingFigure.Plate) {
figureGroup.call(startPlatesUpdate);
} else if (d.figure === EndingFigure.Circle) {
figureGroup.call(connectorsUpdate);
} else if (d.figure === EndingFigure.Arrow) {
figureGroup.call(triangleEndingUpdate);
} else {
throw new Error(
`update: rendering of ${d.figure} ending figure is not implemented`,
);
}
});
};
// Handle is created for each segment of arrow whose length >= minArrowLength
const arrowHandlesFromPoints = (points: Vec2[]): [Vec2, Vec2][] => {
if (points.length < 2) return [];
const handles: [Vec2, Vec2][] = [];
chunks(points, 2, 1).forEach(([start, end], i: number, n: number) => {
if (i === n - 1) return;
if (start.distance(end) < sizes.minArrowLength) return;
const mid = start.linterp(end, 0.5);
const direction = end.sub(start).normalize();
if (direction.isZero()) return;
const handleLength = sizes.arrowHandleWidth;
const handleFrom = mid.sub(direction.mul(handleLength / 2));
const handleTo = mid.add(direction.mul(handleLength / 2));
handles.push([handleFrom, handleTo]);
});
return handles;
};
// NOTE: returns directions of first two points and last two points
const calcDirections = (points: Vec2[]): [Vec2, Vec2] => {
if (points.length < 2) return [Vec2.zero(), Vec2.zero()];
const [first, second] = points.slice(0, 2);
// NOTE: reversed, cz direction computed TO start point
const startDir = first.sub(second).normalize();
if (points.length === 2) return [startDir, startDir.clone()];
const [prev, last] = points.slice(-2, points.length);
const endDir = last.sub(prev).normalize();
return [startDir, endDir];
};
const manageArrows = (arrows: ArrowPathsMap, g: SVGGElement) => {
// console.log(`ArrowsRenderer::manageArrows`);
const rootGroup = d3.select(g);
const startFiguresGroup = rootGroup.select('.start-figures');
const endFiguresGroup = rootGroup.select('.end-figures');
const arrowsGroup = rootGroup.select('.arrows');
const feetsGroup = rootGroup.select('.feets');
const startFiguresMap: Map<string, FigureData> = new Map();
const endFiguresMap: Map<string, FigureData> = new Map();
const arrowsToRender: Array<RenderingArrow> = [];
const feetsMap: Map<string, FeetData> = new Map();
arrows.forEach((arrow, arrowId) => {
const startId = arrow.start.endingId;
const endId = `${startId} -> ${arrow.end.endingId}`;
const allPoints = [arrow.start.coords].concat(arrow.points);
const [startDirection, endDirection] = calcDirections(allPoints);
if (!startFiguresMap.has(startId)) {
// TODO: what if there are two arrows with different colors ?
startFiguresMap.set(startId, {
id: startId,
isStart: true,
figure: arrow.start.figure,
color: arrow.color,
coords: arrow.start.coords,
direction: startDirection,
});
}
if (!endFiguresMap.has(endId)) {
endFiguresMap.set(endId, {
id: arrow.end.endingId,
isStart: false,
figure: arrow.end.figure,
color: arrow.color,
coords: arrow.end.coords,
direction: endDirection,
});
}
const arrowHandles = !!arrow.noHandles
? []
: arrowHandlesFromPoints(allPoints);
arrowsToRender.push([
arrow.arrowId,
{
points: allPoints,
handles: arrowHandles,
color: arrow.color,
},
]);
if (arrow.end.innerEndings != null) {
arrow.end.innerEndings.forEach((ending, innerId) => {
const feetId = innerId;
if (feetsMap.has(feetId)) return;
feetsMap.set(feetId, {
id: feetId,
endingCoords: arrow.end.coords,
innerCoords: ending.coords,
colors: ending.colors,
});
});
}
if (arrow.start.innerEndings != null) {
arrow.start.innerEndings.forEach((ending, innerId) => {
const feetId = innerId;
feetsMap.set(feetId, {
id: feetId,
endingCoords: arrow.start.coords,
innerCoords: ending.coords,
colors: ending.colors,
});
});
}
});
const fns = {
arrows: {
enter: arrowsEnter,
update: arrowsUpdate,
},
feets: {
enter: feetsEnter,
update: feetsUpdate,
},
endingFigures: {
enter: figuresEnter,
update: figuresUpdate,
},
common: {
exit: generalExit,
},
};
arrowsGroup
.selectAll('g')
.data(arrowsToRender, (d: any) => d[0])
.join(fns.arrows.enter, fns.arrows.update, fns.common.exit);
feetsGroup
.selectAll('g')
.data([...feetsMap.values()], (d: any) => d.id)
.join(fns.feets.enter, fns.feets.update, fns.common.exit);
startFiguresGroup
.selectAll('g')
.data([...startFiguresMap.values()], (d: any) => d.id)
.join(fns.endingFigures.enter, fns.endingFigures.update, fns.common.exit);
endFiguresGroup
.selectAll('g')
.data([...endFiguresMap.values()], (d: any) => d.id)
.join(fns.endingFigures.enter, fns.endingFigures.update, fns.common.exit);
};
// This component manages multiple arrows to be able to draw them
// properly using d3
export const Component: FunctionComponent<Props> = observer(
function ArrowsRenderer(props: Props) {
const rootRef = useRef<SVGGElement>(null as any);
useEffect(() => {
if (rootRef == null || rootRef.current == null) return;
manageArrows(props.arrows, rootRef.current);
}, [props.arrows, rootRef]);
return (
<g ref={rootRef} className="arrows">
<g className="arrows" />
<g className="feets" />
<g className="start-figures" />
<g className="end-figures" />
</g>
);
},
);
export const ArrowsRenderer = React.memo(Component); | the_stack |
import { GraphQLResolveInfo, GraphQLSchema } from 'graphql'
import { IResolvers } from 'graphql-tools/dist/Interfaces'
import { makePrismaBindingClass, BasePrismaOptions, Options } from 'prisma-lib'
export interface Exists {
user: (where?: UserWhereInput) => Promise<boolean>
tweet: (where?: TweetWhereInput) => Promise<boolean>
}
export interface Node { }
export interface Prisma {
$exists: Exists;
$request: <T = any>(query: string, variables?: { [key: string]: any }) => Promise<T>;
$delegate: Delegate;
$getAbstractResolvers(filterSchema?: GraphQLSchema | string): IResolvers;
/**
* Queries
*/
users: (args?: { where?: UserWhereInput, orderBy?: UserOrderByInput, skip?: Int, after?: String, before?: String, first?: Int, last?: Int }) => Promise<Array<UserNode>>;
tweets: (args?: { where?: TweetWhereInput, orderBy?: TweetOrderByInput, skip?: Int, after?: String, before?: String, first?: Int, last?: Int }) => Promise<Array<TweetNode>>;
user: (where: UserWhereUniqueInput) => User;
tweet: (where: TweetWhereUniqueInput) => Tweet;
usersConnection: (args?: { where?: UserWhereInput, orderBy?: UserOrderByInput, skip?: Int, after?: String, before?: String, first?: Int, last?: Int }) => UserConnection;
tweetsConnection: (args?: { where?: TweetWhereInput, orderBy?: TweetOrderByInput, skip?: Int, after?: String, before?: String, first?: Int, last?: Int }) => TweetConnection;
node: (args: { id: ID_Output }) => Node;
/**
* Mutations
*/
createUser: (data: UserCreateInput) => User;
createTweet: (data: TweetCreateInput) => Tweet;
updateUser: (args: { data: UserUpdateInput, where: UserWhereUniqueInput }) => User;
updateTweet: (args: { data: TweetUpdateInput, where: TweetWhereUniqueInput }) => Tweet;
deleteUser: (where: UserWhereUniqueInput) => User;
deleteTweet: (where: TweetWhereUniqueInput) => Tweet;
upsertUser: (args: { where: UserWhereUniqueInput, create: UserCreateInput, update: UserUpdateInput }) => User;
upsertTweet: (args: { where: TweetWhereUniqueInput, create: TweetCreateInput, update: TweetUpdateInput }) => Tweet;
updateManyUsers: (args: { data: UserUpdateInput, where?: UserWhereInput }) => BatchPayload;
updateManyTweets: (args: { data: TweetUpdateInput, where?: TweetWhereInput }) => BatchPayload;
deleteManyUsers: (where?: UserWhereInput) => BatchPayload;
deleteManyTweets: (where?: TweetWhereInput) => BatchPayload;
}
export interface Delegate {
(
operation: 'query' | 'mutation',
fieldName: string,
args: {
[key: string]: any
},
infoOrQuery?: GraphQLResolveInfo,
options?: Options,
): Promise<any>
query: DelegateQuery
mutation: DelegateMutation
}
export interface DelegateQuery {
users: <T = Promise<Array<UserNode>>>(args?: { where?: UserWhereInput, orderBy?: UserOrderByInput, skip?: Int, after?: String, before?: String, first?: Int, last?: Int, info?: GraphQLResolveInfo, options?: Options }) => T;
tweets: <T = Promise<Array<TweetNode>>>(args?: { where?: TweetWhereInput, orderBy?: TweetOrderByInput, skip?: Int, after?: String, before?: String, first?: Int, last?: Int, info?: GraphQLResolveInfo, options?: Options }) => T;
user: <T = Promise<Partial<UserNode | null>>>(where: UserWhereUniqueInput) => T;
tweet: <T = Promise<Partial<TweetNode | null>>>(where: TweetWhereUniqueInput) => T;
usersConnection: <T = Promise<Partial<UserConnectionNode>>>(args?: { where?: UserWhereInput, orderBy?: UserOrderByInput, skip?: Int, after?: String, before?: String, first?: Int, last?: Int, info?: GraphQLResolveInfo, options?: Options }) => T;
tweetsConnection: <T = Promise<Partial<TweetConnectionNode>>>(args?: { where?: TweetWhereInput, orderBy?: TweetOrderByInput, skip?: Int, after?: String, before?: String, first?: Int, last?: Int, info?: GraphQLResolveInfo, options?: Options }) => T;
node: <T = Promise<Partial<NodeNode | null>>>(args: { id: ID_Output, info?: GraphQLResolveInfo, options?: Options }) => T
}
export interface DelegateMutation {
createUser: <T = Promise<Partial<UserNode>>>(where: UserCreateInput) => T;
createTweet: <T = Promise<Partial<TweetNode>>>(where: TweetCreateInput) => T;
updateUser: <T = Promise<Partial<UserNode | null>>>(args: { data: UserUpdateInput, where: UserWhereUniqueInput, info?: GraphQLResolveInfo, options?: Options }) => T;
updateTweet: <T = Promise<Partial<TweetNode | null>>>(args: { data: TweetUpdateInput, where: TweetWhereUniqueInput, info?: GraphQLResolveInfo, options?: Options }) => T;
deleteUser: <T = Promise<Partial<UserNode | null>>>(where: UserWhereUniqueInput) => T;
deleteTweet: <T = Promise<Partial<TweetNode | null>>>(where: TweetWhereUniqueInput) => T;
upsertUser: <T = Promise<Partial<UserNode>>>(args: { where: UserWhereUniqueInput, create: UserCreateInput, update: UserUpdateInput, info?: GraphQLResolveInfo, options?: Options }) => T;
upsertTweet: <T = Promise<Partial<TweetNode>>>(args: { where: TweetWhereUniqueInput, create: TweetCreateInput, update: TweetUpdateInput, info?: GraphQLResolveInfo, options?: Options }) => T;
updateManyUsers: <T = Promise<Partial<BatchPayloadNode>>>(args: { data: UserUpdateInput, where?: UserWhereInput, info?: GraphQLResolveInfo, options?: Options }) => T;
updateManyTweets: <T = Promise<Partial<BatchPayloadNode>>>(args: { data: TweetUpdateInput, where?: TweetWhereInput, info?: GraphQLResolveInfo, options?: Options }) => T;
deleteManyUsers: <T = Promise<Partial<BatchPayloadNode>>>(where?: UserWhereInput) => T;
deleteManyTweets: <T = Promise<Partial<BatchPayloadNode>>>(where?: TweetWhereInput) => T;
}
export interface BindingConstructor<T> {
new(options?: BasePrismaOptions): T
}
/**
* Types
*/
export type UserOrderByInput = 'id_ASC' |
'id_DESC' |
'password_ASC' |
'password_DESC' |
'username_ASC' |
'username_DESC' |
'displayName_ASC' |
'displayName_DESC' |
'updatedAt_ASC' |
'updatedAt_DESC' |
'createdAt_ASC' |
'createdAt_DESC'
export type TweetOrderByInput = 'id_ASC' |
'id_DESC' |
'text_ASC' |
'text_DESC' |
'upload_ASC' |
'upload_DESC' |
'slug_ASC' |
'slug_DESC' |
'views_ASC' |
'views_DESC' |
'updatedAt_ASC' |
'updatedAt_DESC' |
'createdAt_ASC' |
'createdAt_DESC'
export type MutationType = 'CREATED' |
'UPDATED' |
'DELETED'
export interface TweetCreateWithoutAuthorInput {
text: String
upload?: String
slug?: String
views?: Int
}
export interface UserWhereInput {
AND?: UserWhereInput[] | UserWhereInput
OR?: UserWhereInput[] | UserWhereInput
NOT?: UserWhereInput[] | UserWhereInput
id?: ID_Input
id_not?: ID_Input
id_in?: ID_Input[] | ID_Input
id_not_in?: ID_Input[] | ID_Input
id_lt?: ID_Input
id_lte?: ID_Input
id_gt?: ID_Input
id_gte?: ID_Input
id_contains?: ID_Input
id_not_contains?: ID_Input
id_starts_with?: ID_Input
id_not_starts_with?: ID_Input
id_ends_with?: ID_Input
id_not_ends_with?: ID_Input
password?: String
password_not?: String
password_in?: String[] | String
password_not_in?: String[] | String
password_lt?: String
password_lte?: String
password_gt?: String
password_gte?: String
password_contains?: String
password_not_contains?: String
password_starts_with?: String
password_not_starts_with?: String
password_ends_with?: String
password_not_ends_with?: String
username?: String
username_not?: String
username_in?: String[] | String
username_not_in?: String[] | String
username_lt?: String
username_lte?: String
username_gt?: String
username_gte?: String
username_contains?: String
username_not_contains?: String
username_starts_with?: String
username_not_starts_with?: String
username_ends_with?: String
username_not_ends_with?: String
displayName?: String
displayName_not?: String
displayName_in?: String[] | String
displayName_not_in?: String[] | String
displayName_lt?: String
displayName_lte?: String
displayName_gt?: String
displayName_gte?: String
displayName_contains?: String
displayName_not_contains?: String
displayName_starts_with?: String
displayName_not_starts_with?: String
displayName_ends_with?: String
displayName_not_ends_with?: String
tweets_every?: TweetWhereInput
tweets_some?: TweetWhereInput
tweets_none?: TweetWhereInput
}
export interface TweetUpdateInput {
text?: String
upload?: String
slug?: String
views?: Int
author?: UserUpdateOneWithoutTweetsInput
}
export interface UserCreateWithoutTweetsInput {
password: String
username: String
displayName: String
}
export interface TweetUpsertWithWhereUniqueWithoutAuthorInput {
where: TweetWhereUniqueInput
update: TweetUpdateWithoutAuthorDataInput
create: TweetCreateWithoutAuthorInput
}
export interface UserCreateOneWithoutTweetsInput {
create?: UserCreateWithoutTweetsInput
connect?: UserWhereUniqueInput
}
export interface TweetUpdateWithoutAuthorDataInput {
text?: String
upload?: String
slug?: String
views?: Int
}
export interface TweetWhereInput {
AND?: TweetWhereInput[] | TweetWhereInput
OR?: TweetWhereInput[] | TweetWhereInput
NOT?: TweetWhereInput[] | TweetWhereInput
id?: ID_Input
id_not?: ID_Input
id_in?: ID_Input[] | ID_Input
id_not_in?: ID_Input[] | ID_Input
id_lt?: ID_Input
id_lte?: ID_Input
id_gt?: ID_Input
id_gte?: ID_Input
id_contains?: ID_Input
id_not_contains?: ID_Input
id_starts_with?: ID_Input
id_not_starts_with?: ID_Input
id_ends_with?: ID_Input
id_not_ends_with?: ID_Input
text?: String
text_not?: String
text_in?: String[] | String
text_not_in?: String[] | String
text_lt?: String
text_lte?: String
text_gt?: String
text_gte?: String
text_contains?: String
text_not_contains?: String
text_starts_with?: String
text_not_starts_with?: String
text_ends_with?: String
text_not_ends_with?: String
upload?: String
upload_not?: String
upload_in?: String[] | String
upload_not_in?: String[] | String
upload_lt?: String
upload_lte?: String
upload_gt?: String
upload_gte?: String
upload_contains?: String
upload_not_contains?: String
upload_starts_with?: String
upload_not_starts_with?: String
upload_ends_with?: String
upload_not_ends_with?: String
slug?: String
slug_not?: String
slug_in?: String[] | String
slug_not_in?: String[] | String
slug_lt?: String
slug_lte?: String
slug_gt?: String
slug_gte?: String
slug_contains?: String
slug_not_contains?: String
slug_starts_with?: String
slug_not_starts_with?: String
slug_ends_with?: String
slug_not_ends_with?: String
views?: Int
views_not?: Int
views_in?: Int[] | Int
views_not_in?: Int[] | Int
views_lt?: Int
views_lte?: Int
views_gt?: Int
views_gte?: Int
author?: UserWhereInput
}
export interface TweetUpdateWithWhereUniqueWithoutAuthorInput {
where: TweetWhereUniqueInput
data: TweetUpdateWithoutAuthorDataInput
}
export interface UserWhereUniqueInput {
id?: ID_Input
username?: String
}
export interface UserCreateInput {
password: String
username: String
displayName: String
tweets?: TweetCreateManyWithoutAuthorInput
}
export interface UserSubscriptionWhereInput {
AND?: UserSubscriptionWhereInput[] | UserSubscriptionWhereInput
OR?: UserSubscriptionWhereInput[] | UserSubscriptionWhereInput
NOT?: UserSubscriptionWhereInput[] | UserSubscriptionWhereInput
mutation_in?: MutationType[] | MutationType
updatedFields_contains?: String
updatedFields_contains_every?: String[] | String
updatedFields_contains_some?: String[] | String
node?: UserWhereInput
}
export interface UserUpdateWithoutTweetsDataInput {
password?: String
username?: String
displayName?: String
}
export interface UserUpdateInput {
password?: String
username?: String
displayName?: String
tweets?: TweetUpdateManyWithoutAuthorInput
}
export interface TweetCreateInput {
text: String
upload?: String
slug?: String
views?: Int
author: UserCreateOneWithoutTweetsInput
}
export interface TweetUpdateManyWithoutAuthorInput {
create?: TweetCreateWithoutAuthorInput[] | TweetCreateWithoutAuthorInput
connect?: TweetWhereUniqueInput[] | TweetWhereUniqueInput
disconnect?: TweetWhereUniqueInput[] | TweetWhereUniqueInput
delete?: TweetWhereUniqueInput[] | TweetWhereUniqueInput
update?: TweetUpdateWithWhereUniqueWithoutAuthorInput[] | TweetUpdateWithWhereUniqueWithoutAuthorInput
upsert?: TweetUpsertWithWhereUniqueWithoutAuthorInput[] | TweetUpsertWithWhereUniqueWithoutAuthorInput
}
export interface TweetCreateManyWithoutAuthorInput {
create?: TweetCreateWithoutAuthorInput[] | TweetCreateWithoutAuthorInput
connect?: TweetWhereUniqueInput[] | TweetWhereUniqueInput
}
export interface UserUpdateOneWithoutTweetsInput {
create?: UserCreateWithoutTweetsInput
connect?: UserWhereUniqueInput
delete?: Boolean
update?: UserUpdateWithoutTweetsDataInput
upsert?: UserUpsertWithoutTweetsInput
}
export interface UserUpsertWithoutTweetsInput {
update: UserUpdateWithoutTweetsDataInput
create: UserCreateWithoutTweetsInput
}
export interface TweetWhereUniqueInput {
id?: ID_Input
slug?: String
}
export interface TweetSubscriptionWhereInput {
AND?: TweetSubscriptionWhereInput[] | TweetSubscriptionWhereInput
OR?: TweetSubscriptionWhereInput[] | TweetSubscriptionWhereInput
NOT?: TweetSubscriptionWhereInput[] | TweetSubscriptionWhereInput
mutation_in?: MutationType[] | MutationType
updatedFields_contains?: String
updatedFields_contains_every?: String[] | String
updatedFields_contains_some?: String[] | String
node?: TweetWhereInput
}
/*
* An object with an ID
*/
export interface NodeNode {
id: ID_Output
}
export interface TweetPreviousValuesNode {
id: ID_Output
text: String
upload?: String
slug?: String
views?: Int
}
export interface TweetPreviousValues extends Promise<TweetPreviousValuesNode> {
id: () => Promise<ID_Output>
text: () => Promise<String>
upload: () => Promise<String>
slug: () => Promise<String>
views: () => Promise<Int>
}
export interface BatchPayloadNode {
count: Long
}
export interface BatchPayload extends Promise<BatchPayloadNode> {
count: () => Promise<Long>
}
export interface UserNode extends Node {
id: ID_Output
password: String
username: String
displayName: String
}
export interface User extends Promise<UserNode>, Node {
id: () => Promise<ID_Output>
password: () => Promise<String>
username: () => Promise<String>
displayName: () => Promise<String>
tweets: (args?: { where?: TweetWhereInput, orderBy?: TweetOrderByInput, skip?: Int, after?: String, before?: String, first?: Int, last?: Int }) => Promise<Array<TweetNode>>
}
/*
* Information about pagination in a connection.
*/
export interface PageInfoNode {
hasNextPage: Boolean
hasPreviousPage: Boolean
startCursor?: String
endCursor?: String
}
/*
* Information about pagination in a connection.
*/
export interface PageInfo extends Promise<PageInfoNode> {
hasNextPage: () => Promise<Boolean>
hasPreviousPage: () => Promise<Boolean>
startCursor: () => Promise<String>
endCursor: () => Promise<String>
}
export interface UserSubscriptionPayloadNode {
mutation: MutationType
updatedFields?: String[]
}
export interface UserSubscriptionPayload extends Promise<UserSubscriptionPayloadNode> {
mutation: () => Promise<MutationType>
node: () => User
updatedFields: () => Promise<String[]>
previousValues: () => UserPreviousValues
}
export interface AggregateTweetNode {
count: Int
}
export interface AggregateTweet extends Promise<AggregateTweetNode> {
count: () => Promise<Int>
}
export interface UserPreviousValuesNode {
id: ID_Output
password: String
username: String
displayName: String
}
export interface UserPreviousValues extends Promise<UserPreviousValuesNode> {
id: () => Promise<ID_Output>
password: () => Promise<String>
username: () => Promise<String>
displayName: () => Promise<String>
}
/*
* A connection to a list of items.
*/
export interface UserConnectionNode {
}
/*
* A connection to a list of items.
*/
export interface UserConnection extends Promise<UserConnectionNode> {
pageInfo: () => PageInfo
edges: () => Promise<Array<UserEdgeNode>>
aggregate: () => AggregateUser
}
/*
* An edge in a connection.
*/
export interface TweetEdgeNode {
cursor: String
}
/*
* An edge in a connection.
*/
export interface TweetEdge extends Promise<TweetEdgeNode> {
node: () => Tweet
cursor: () => Promise<String>
}
export interface TweetNode extends Node {
id: ID_Output
text: String
upload?: String
slug?: String
views?: Int
}
export interface Tweet extends Promise<TweetNode>, Node {
id: () => Promise<ID_Output>
text: () => Promise<String>
upload: () => Promise<String>
slug: () => Promise<String>
views: () => Promise<Int>
author: (args?: { where?: UserWhereInput }) => User
}
/*
* A connection to a list of items.
*/
export interface TweetConnectionNode {
}
/*
* A connection to a list of items.
*/
export interface TweetConnection extends Promise<TweetConnectionNode> {
pageInfo: () => PageInfo
edges: () => Promise<Array<TweetEdgeNode>>
aggregate: () => AggregateTweet
}
export interface TweetSubscriptionPayloadNode {
mutation: MutationType
updatedFields?: String[]
}
export interface TweetSubscriptionPayload extends Promise<TweetSubscriptionPayloadNode> {
mutation: () => Promise<MutationType>
node: () => Tweet
updatedFields: () => Promise<String[]>
previousValues: () => TweetPreviousValues
}
/*
* An edge in a connection.
*/
export interface UserEdgeNode {
cursor: String
}
/*
* An edge in a connection.
*/
export interface UserEdge extends Promise<UserEdgeNode> {
node: () => User
cursor: () => Promise<String>
}
export interface AggregateUserNode {
count: Int
}
export interface AggregateUser extends Promise<AggregateUserNode> {
count: () => Promise<Int>
}
/*
The `Long` scalar type represents non-fractional signed whole numeric values.
Long can represent values between -(2^63) and 2^63 - 1.
*/
export type Long = string
/*
The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.
*/
export type Int = number
/*
The `Boolean` scalar type represents `true` or `false`.
*/
export type Boolean = boolean
/*
The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID.
*/
export type ID_Input = string | number
export type ID_Output = string
/*
The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.
*/
export type String = string
/**
* Type Defs
*/
const typeDefs = `type AggregateTweet {
count: Int!
}
type AggregateUser {
count: Int!
}
type BatchPayload {
"""The number of nodes that have been affected by the Batch operation."""
count: Long!
}
"""
The \`Long\` scalar type represents non-fractional signed whole numeric values.
Long can represent values between -(2^63) and 2^63 - 1.
"""
scalar Long
type Mutation {
createUser(data: UserCreateInput!): User!
createTweet(data: TweetCreateInput!): Tweet!
updateUser(data: UserUpdateInput!, where: UserWhereUniqueInput!): User
updateTweet(data: TweetUpdateInput!, where: TweetWhereUniqueInput!): Tweet
deleteUser(where: UserWhereUniqueInput!): User
deleteTweet(where: TweetWhereUniqueInput!): Tweet
upsertUser(where: UserWhereUniqueInput!, create: UserCreateInput!, update: UserUpdateInput!): User!
upsertTweet(where: TweetWhereUniqueInput!, create: TweetCreateInput!, update: TweetUpdateInput!): Tweet!
updateManyUsers(data: UserUpdateInput!, where: UserWhereInput): BatchPayload!
updateManyTweets(data: TweetUpdateInput!, where: TweetWhereInput): BatchPayload!
deleteManyUsers(where: UserWhereInput): BatchPayload!
deleteManyTweets(where: TweetWhereInput): BatchPayload!
}
enum MutationType {
CREATED
UPDATED
DELETED
}
"""An object with an ID"""
interface Node {
"""The id of the object."""
id: ID!
}
"""Information about pagination in a connection."""
type PageInfo {
"""When paginating forwards, are there more items?"""
hasNextPage: Boolean!
"""When paginating backwards, are there more items?"""
hasPreviousPage: Boolean!
"""When paginating backwards, the cursor to continue."""
startCursor: String
"""When paginating forwards, the cursor to continue."""
endCursor: String
}
type Query {
users(where: UserWhereInput, orderBy: UserOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [User]!
tweets(where: TweetWhereInput, orderBy: TweetOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [Tweet]!
user(where: UserWhereUniqueInput!): User
tweet(where: TweetWhereUniqueInput!): Tweet
usersConnection(where: UserWhereInput, orderBy: UserOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): UserConnection!
tweetsConnection(where: TweetWhereInput, orderBy: TweetOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): TweetConnection!
"""Fetches an object given its ID"""
node(
"""The ID of an object"""
id: ID!
): Node
}
type Subscription {
user(where: UserSubscriptionWhereInput): UserSubscriptionPayload
tweet(where: TweetSubscriptionWhereInput): TweetSubscriptionPayload
}
type Tweet implements Node {
id: ID!
text: String!
upload: String
slug: String
views: Int
author(where: UserWhereInput): User!
}
"""A connection to a list of items."""
type TweetConnection {
"""Information to aid in pagination."""
pageInfo: PageInfo!
"""A list of edges."""
edges: [TweetEdge]!
aggregate: AggregateTweet!
}
input TweetCreateInput {
text: String!
upload: String
slug: String
views: Int
author: UserCreateOneWithoutTweetsInput!
}
input TweetCreateManyWithoutAuthorInput {
create: [TweetCreateWithoutAuthorInput!]
connect: [TweetWhereUniqueInput!]
}
input TweetCreateWithoutAuthorInput {
text: String!
upload: String
slug: String
views: Int
}
"""An edge in a connection."""
type TweetEdge {
"""The item at the end of the edge."""
node: Tweet!
"""A cursor for use in pagination."""
cursor: String!
}
enum TweetOrderByInput {
id_ASC
id_DESC
text_ASC
text_DESC
upload_ASC
upload_DESC
slug_ASC
slug_DESC
views_ASC
views_DESC
updatedAt_ASC
updatedAt_DESC
createdAt_ASC
createdAt_DESC
}
type TweetPreviousValues {
id: ID!
text: String!
upload: String
slug: String
views: Int
}
type TweetSubscriptionPayload {
mutation: MutationType!
node: Tweet
updatedFields: [String!]
previousValues: TweetPreviousValues
}
input TweetSubscriptionWhereInput {
"""Logical AND on all given filters."""
AND: [TweetSubscriptionWhereInput!]
"""Logical OR on all given filters."""
OR: [TweetSubscriptionWhereInput!]
"""Logical NOT on all given filters combined by AND."""
NOT: [TweetSubscriptionWhereInput!]
"""
The subscription event gets dispatched when it's listed in mutation_in
"""
mutation_in: [MutationType!]
"""
The subscription event gets only dispatched when one of the updated fields names is included in this list
"""
updatedFields_contains: String
"""
The subscription event gets only dispatched when all of the field names included in this list have been updated
"""
updatedFields_contains_every: [String!]
"""
The subscription event gets only dispatched when some of the field names included in this list have been updated
"""
updatedFields_contains_some: [String!]
node: TweetWhereInput
}
input TweetUpdateInput {
text: String
upload: String
slug: String
views: Int
author: UserUpdateOneWithoutTweetsInput
}
input TweetUpdateManyWithoutAuthorInput {
create: [TweetCreateWithoutAuthorInput!]
connect: [TweetWhereUniqueInput!]
disconnect: [TweetWhereUniqueInput!]
delete: [TweetWhereUniqueInput!]
update: [TweetUpdateWithWhereUniqueWithoutAuthorInput!]
upsert: [TweetUpsertWithWhereUniqueWithoutAuthorInput!]
}
input TweetUpdateWithoutAuthorDataInput {
text: String
upload: String
slug: String
views: Int
}
input TweetUpdateWithWhereUniqueWithoutAuthorInput {
where: TweetWhereUniqueInput!
data: TweetUpdateWithoutAuthorDataInput!
}
input TweetUpsertWithWhereUniqueWithoutAuthorInput {
where: TweetWhereUniqueInput!
update: TweetUpdateWithoutAuthorDataInput!
create: TweetCreateWithoutAuthorInput!
}
input TweetWhereInput {
"""Logical AND on all given filters."""
AND: [TweetWhereInput!]
"""Logical OR on all given filters."""
OR: [TweetWhereInput!]
"""Logical NOT on all given filters combined by AND."""
NOT: [TweetWhereInput!]
id: ID
"""All values that are not equal to given value."""
id_not: ID
"""All values that are contained in given list."""
id_in: [ID!]
"""All values that are not contained in given list."""
id_not_in: [ID!]
"""All values less than the given value."""
id_lt: ID
"""All values less than or equal the given value."""
id_lte: ID
"""All values greater than the given value."""
id_gt: ID
"""All values greater than or equal the given value."""
id_gte: ID
"""All values containing the given string."""
id_contains: ID
"""All values not containing the given string."""
id_not_contains: ID
"""All values starting with the given string."""
id_starts_with: ID
"""All values not starting with the given string."""
id_not_starts_with: ID
"""All values ending with the given string."""
id_ends_with: ID
"""All values not ending with the given string."""
id_not_ends_with: ID
text: String
"""All values that are not equal to given value."""
text_not: String
"""All values that are contained in given list."""
text_in: [String!]
"""All values that are not contained in given list."""
text_not_in: [String!]
"""All values less than the given value."""
text_lt: String
"""All values less than or equal the given value."""
text_lte: String
"""All values greater than the given value."""
text_gt: String
"""All values greater than or equal the given value."""
text_gte: String
"""All values containing the given string."""
text_contains: String
"""All values not containing the given string."""
text_not_contains: String
"""All values starting with the given string."""
text_starts_with: String
"""All values not starting with the given string."""
text_not_starts_with: String
"""All values ending with the given string."""
text_ends_with: String
"""All values not ending with the given string."""
text_not_ends_with: String
upload: String
"""All values that are not equal to given value."""
upload_not: String
"""All values that are contained in given list."""
upload_in: [String!]
"""All values that are not contained in given list."""
upload_not_in: [String!]
"""All values less than the given value."""
upload_lt: String
"""All values less than or equal the given value."""
upload_lte: String
"""All values greater than the given value."""
upload_gt: String
"""All values greater than or equal the given value."""
upload_gte: String
"""All values containing the given string."""
upload_contains: String
"""All values not containing the given string."""
upload_not_contains: String
"""All values starting with the given string."""
upload_starts_with: String
"""All values not starting with the given string."""
upload_not_starts_with: String
"""All values ending with the given string."""
upload_ends_with: String
"""All values not ending with the given string."""
upload_not_ends_with: String
slug: String
"""All values that are not equal to given value."""
slug_not: String
"""All values that are contained in given list."""
slug_in: [String!]
"""All values that are not contained in given list."""
slug_not_in: [String!]
"""All values less than the given value."""
slug_lt: String
"""All values less than or equal the given value."""
slug_lte: String
"""All values greater than the given value."""
slug_gt: String
"""All values greater than or equal the given value."""
slug_gte: String
"""All values containing the given string."""
slug_contains: String
"""All values not containing the given string."""
slug_not_contains: String
"""All values starting with the given string."""
slug_starts_with: String
"""All values not starting with the given string."""
slug_not_starts_with: String
"""All values ending with the given string."""
slug_ends_with: String
"""All values not ending with the given string."""
slug_not_ends_with: String
views: Int
"""All values that are not equal to given value."""
views_not: Int
"""All values that are contained in given list."""
views_in: [Int!]
"""All values that are not contained in given list."""
views_not_in: [Int!]
"""All values less than the given value."""
views_lt: Int
"""All values less than or equal the given value."""
views_lte: Int
"""All values greater than the given value."""
views_gt: Int
"""All values greater than or equal the given value."""
views_gte: Int
author: UserWhereInput
}
input TweetWhereUniqueInput {
id: ID
slug: String
}
type User implements Node {
id: ID!
password: String!
username: String!
displayName: String!
tweets(where: TweetWhereInput, orderBy: TweetOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [Tweet!]
}
"""A connection to a list of items."""
type UserConnection {
"""Information to aid in pagination."""
pageInfo: PageInfo!
"""A list of edges."""
edges: [UserEdge]!
aggregate: AggregateUser!
}
input UserCreateInput {
password: String!
username: String!
displayName: String!
tweets: TweetCreateManyWithoutAuthorInput
}
input UserCreateOneWithoutTweetsInput {
create: UserCreateWithoutTweetsInput
connect: UserWhereUniqueInput
}
input UserCreateWithoutTweetsInput {
password: String!
username: String!
displayName: String!
}
"""An edge in a connection."""
type UserEdge {
"""The item at the end of the edge."""
node: User!
"""A cursor for use in pagination."""
cursor: String!
}
enum UserOrderByInput {
id_ASC
id_DESC
password_ASC
password_DESC
username_ASC
username_DESC
displayName_ASC
displayName_DESC
updatedAt_ASC
updatedAt_DESC
createdAt_ASC
createdAt_DESC
}
type UserPreviousValues {
id: ID!
password: String!
username: String!
displayName: String!
}
type UserSubscriptionPayload {
mutation: MutationType!
node: User
updatedFields: [String!]
previousValues: UserPreviousValues
}
input UserSubscriptionWhereInput {
"""Logical AND on all given filters."""
AND: [UserSubscriptionWhereInput!]
"""Logical OR on all given filters."""
OR: [UserSubscriptionWhereInput!]
"""Logical NOT on all given filters combined by AND."""
NOT: [UserSubscriptionWhereInput!]
"""
The subscription event gets dispatched when it's listed in mutation_in
"""
mutation_in: [MutationType!]
"""
The subscription event gets only dispatched when one of the updated fields names is included in this list
"""
updatedFields_contains: String
"""
The subscription event gets only dispatched when all of the field names included in this list have been updated
"""
updatedFields_contains_every: [String!]
"""
The subscription event gets only dispatched when some of the field names included in this list have been updated
"""
updatedFields_contains_some: [String!]
node: UserWhereInput
}
input UserUpdateInput {
password: String
username: String
displayName: String
tweets: TweetUpdateManyWithoutAuthorInput
}
input UserUpdateOneWithoutTweetsInput {
create: UserCreateWithoutTweetsInput
connect: UserWhereUniqueInput
delete: Boolean
update: UserUpdateWithoutTweetsDataInput
upsert: UserUpsertWithoutTweetsInput
}
input UserUpdateWithoutTweetsDataInput {
password: String
username: String
displayName: String
}
input UserUpsertWithoutTweetsInput {
update: UserUpdateWithoutTweetsDataInput!
create: UserCreateWithoutTweetsInput!
}
input UserWhereInput {
"""Logical AND on all given filters."""
AND: [UserWhereInput!]
"""Logical OR on all given filters."""
OR: [UserWhereInput!]
"""Logical NOT on all given filters combined by AND."""
NOT: [UserWhereInput!]
id: ID
"""All values that are not equal to given value."""
id_not: ID
"""All values that are contained in given list."""
id_in: [ID!]
"""All values that are not contained in given list."""
id_not_in: [ID!]
"""All values less than the given value."""
id_lt: ID
"""All values less than or equal the given value."""
id_lte: ID
"""All values greater than the given value."""
id_gt: ID
"""All values greater than or equal the given value."""
id_gte: ID
"""All values containing the given string."""
id_contains: ID
"""All values not containing the given string."""
id_not_contains: ID
"""All values starting with the given string."""
id_starts_with: ID
"""All values not starting with the given string."""
id_not_starts_with: ID
"""All values ending with the given string."""
id_ends_with: ID
"""All values not ending with the given string."""
id_not_ends_with: ID
password: String
"""All values that are not equal to given value."""
password_not: String
"""All values that are contained in given list."""
password_in: [String!]
"""All values that are not contained in given list."""
password_not_in: [String!]
"""All values less than the given value."""
password_lt: String
"""All values less than or equal the given value."""
password_lte: String
"""All values greater than the given value."""
password_gt: String
"""All values greater than or equal the given value."""
password_gte: String
"""All values containing the given string."""
password_contains: String
"""All values not containing the given string."""
password_not_contains: String
"""All values starting with the given string."""
password_starts_with: String
"""All values not starting with the given string."""
password_not_starts_with: String
"""All values ending with the given string."""
password_ends_with: String
"""All values not ending with the given string."""
password_not_ends_with: String
username: String
"""All values that are not equal to given value."""
username_not: String
"""All values that are contained in given list."""
username_in: [String!]
"""All values that are not contained in given list."""
username_not_in: [String!]
"""All values less than the given value."""
username_lt: String
"""All values less than or equal the given value."""
username_lte: String
"""All values greater than the given value."""
username_gt: String
"""All values greater than or equal the given value."""
username_gte: String
"""All values containing the given string."""
username_contains: String
"""All values not containing the given string."""
username_not_contains: String
"""All values starting with the given string."""
username_starts_with: String
"""All values not starting with the given string."""
username_not_starts_with: String
"""All values ending with the given string."""
username_ends_with: String
"""All values not ending with the given string."""
username_not_ends_with: String
displayName: String
"""All values that are not equal to given value."""
displayName_not: String
"""All values that are contained in given list."""
displayName_in: [String!]
"""All values that are not contained in given list."""
displayName_not_in: [String!]
"""All values less than the given value."""
displayName_lt: String
"""All values less than or equal the given value."""
displayName_lte: String
"""All values greater than the given value."""
displayName_gt: String
"""All values greater than or equal the given value."""
displayName_gte: String
"""All values containing the given string."""
displayName_contains: String
"""All values not containing the given string."""
displayName_not_contains: String
"""All values starting with the given string."""
displayName_starts_with: String
"""All values not starting with the given string."""
displayName_not_starts_with: String
"""All values ending with the given string."""
displayName_ends_with: String
"""All values not ending with the given string."""
displayName_not_ends_with: String
tweets_every: TweetWhereInput
tweets_some: TweetWhereInput
tweets_none: TweetWhereInput
}
input UserWhereUniqueInput {
id: ID
username: String
}
`
export const Prisma = makePrismaBindingClass<BindingConstructor<Prisma>>({ typeDefs, endpoint: 'https://eu1.prisma.sh/nestjs/prisma-nest/dev' })
export const prisma = new Prisma() | the_stack |
import { CloudErrorMapper, BaseResourceMapper } from "@azure/ms-rest-azure-js";
import * as msRest from "@azure/ms-rest-js";
export const CloudError = CloudErrorMapper;
export const BaseResource = BaseResourceMapper;
export const LocalizableString: msRest.CompositeMapper = {
serializedName: "LocalizableString",
type: {
name: "Composite",
className: "LocalizableString",
modelProperties: {
value: {
required: true,
serializedName: "value",
type: {
name: "String"
}
},
localizedValue: {
serializedName: "localizedValue",
type: {
name: "String"
}
}
}
}
};
export const MetricAvailability: msRest.CompositeMapper = {
serializedName: "MetricAvailability",
type: {
name: "Composite",
className: "MetricAvailability",
modelProperties: {
timeGrain: {
serializedName: "timeGrain",
type: {
name: "TimeSpan"
}
},
retention: {
serializedName: "retention",
type: {
name: "TimeSpan"
}
}
}
}
};
export const MetricDefinition: msRest.CompositeMapper = {
serializedName: "MetricDefinition",
type: {
name: "Composite",
className: "MetricDefinition",
modelProperties: {
isDimensionRequired: {
serializedName: "isDimensionRequired",
type: {
name: "Boolean"
}
},
resourceId: {
serializedName: "resourceId",
type: {
name: "String"
}
},
namespace: {
serializedName: "namespace",
type: {
name: "String"
}
},
name: {
serializedName: "name",
type: {
name: "Composite",
className: "LocalizableString"
}
},
unit: {
serializedName: "unit",
type: {
name: "Enum",
allowedValues: [
"Count",
"Bytes",
"Seconds",
"CountPerSecond",
"BytesPerSecond",
"Percent",
"MilliSeconds",
"ByteSeconds",
"Unspecified",
"Cores",
"MilliCores",
"NanoCores",
"BitsPerSecond"
]
}
},
primaryAggregationType: {
serializedName: "primaryAggregationType",
type: {
name: "Enum",
allowedValues: [
"None",
"Average",
"Count",
"Minimum",
"Maximum",
"Total"
]
}
},
supportedAggregationTypes: {
serializedName: "supportedAggregationTypes",
type: {
name: "Sequence",
element: {
type: {
name: "Enum",
allowedValues: [
"None",
"Average",
"Count",
"Minimum",
"Maximum",
"Total"
]
}
}
}
},
metricAvailabilities: {
serializedName: "metricAvailabilities",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "MetricAvailability"
}
}
}
},
id: {
serializedName: "id",
type: {
name: "String"
}
},
dimensions: {
serializedName: "dimensions",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "LocalizableString"
}
}
}
}
}
}
};
export const ErrorResponse: msRest.CompositeMapper = {
serializedName: "ErrorResponse",
type: {
name: "Composite",
className: "ErrorResponse",
modelProperties: {
code: {
serializedName: "code",
type: {
name: "String"
}
},
message: {
serializedName: "message",
type: {
name: "String"
}
}
}
}
};
export const MetricValue: msRest.CompositeMapper = {
serializedName: "MetricValue",
type: {
name: "Composite",
className: "MetricValue",
modelProperties: {
timeStamp: {
required: true,
serializedName: "timeStamp",
type: {
name: "DateTime"
}
},
average: {
serializedName: "average",
type: {
name: "Number"
}
},
minimum: {
serializedName: "minimum",
type: {
name: "Number"
}
},
maximum: {
serializedName: "maximum",
type: {
name: "Number"
}
},
total: {
serializedName: "total",
type: {
name: "Number"
}
},
count: {
serializedName: "count",
type: {
name: "Number"
}
}
}
}
};
export const MetadataValue: msRest.CompositeMapper = {
serializedName: "MetadataValue",
type: {
name: "Composite",
className: "MetadataValue",
modelProperties: {
name: {
serializedName: "name",
type: {
name: "Composite",
className: "LocalizableString"
}
},
value: {
serializedName: "value",
type: {
name: "String"
}
}
}
}
};
export const TimeSeriesElement: msRest.CompositeMapper = {
serializedName: "TimeSeriesElement",
type: {
name: "Composite",
className: "TimeSeriesElement",
modelProperties: {
metadatavalues: {
serializedName: "metadatavalues",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "MetadataValue"
}
}
}
},
data: {
serializedName: "data",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "MetricValue"
}
}
}
}
}
}
};
export const Metric: msRest.CompositeMapper = {
serializedName: "Metric",
type: {
name: "Composite",
className: "Metric",
modelProperties: {
id: {
required: true,
serializedName: "id",
type: {
name: "String"
}
},
type: {
required: true,
serializedName: "type",
type: {
name: "String"
}
},
name: {
required: true,
serializedName: "name",
type: {
name: "Composite",
className: "LocalizableString"
}
},
unit: {
required: true,
serializedName: "unit",
type: {
name: "Enum",
allowedValues: [
"Count",
"Bytes",
"Seconds",
"CountPerSecond",
"BytesPerSecond",
"Percent",
"MilliSeconds",
"ByteSeconds",
"Unspecified",
"Cores",
"MilliCores",
"NanoCores",
"BitsPerSecond"
]
}
},
timeseries: {
required: true,
serializedName: "timeseries",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "TimeSeriesElement"
}
}
}
}
}
}
};
export const Response: msRest.CompositeMapper = {
serializedName: "Response",
type: {
name: "Composite",
className: "Response",
modelProperties: {
cost: {
serializedName: "cost",
constraints: {
InclusiveMinimum: 0
},
type: {
name: "Number"
}
},
timespan: {
required: true,
serializedName: "timespan",
type: {
name: "String"
}
},
interval: {
serializedName: "interval",
type: {
name: "TimeSpan"
}
},
namespace: {
serializedName: "namespace",
type: {
name: "String"
}
},
resourceregion: {
serializedName: "resourceregion",
type: {
name: "String"
}
},
value: {
required: true,
serializedName: "value",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "Metric"
}
}
}
}
}
}
};
export const ProxyOnlyResource: msRest.CompositeMapper = {
serializedName: "ProxyOnlyResource",
type: {
name: "Composite",
className: "ProxyOnlyResource",
modelProperties: {
id: {
readOnly: true,
serializedName: "id",
type: {
name: "String"
}
},
name: {
readOnly: true,
serializedName: "name",
type: {
name: "String"
}
},
type: {
readOnly: true,
serializedName: "type",
type: {
name: "String"
}
}
}
}
};
export const RetentionPolicy: msRest.CompositeMapper = {
serializedName: "RetentionPolicy",
type: {
name: "Composite",
className: "RetentionPolicy",
modelProperties: {
enabled: {
required: true,
serializedName: "enabled",
type: {
name: "Boolean"
}
},
days: {
required: true,
serializedName: "days",
constraints: {
InclusiveMinimum: 0
},
type: {
name: "Number"
}
}
}
}
};
export const MetricSettings: msRest.CompositeMapper = {
serializedName: "MetricSettings",
type: {
name: "Composite",
className: "MetricSettings",
modelProperties: {
timeGrain: {
serializedName: "timeGrain",
type: {
name: "TimeSpan"
}
},
category: {
serializedName: "category",
type: {
name: "String"
}
},
enabled: {
required: true,
serializedName: "enabled",
type: {
name: "Boolean"
}
},
retentionPolicy: {
serializedName: "retentionPolicy",
type: {
name: "Composite",
className: "RetentionPolicy"
}
}
}
}
};
export const LogSettings: msRest.CompositeMapper = {
serializedName: "LogSettings",
type: {
name: "Composite",
className: "LogSettings",
modelProperties: {
category: {
serializedName: "category",
type: {
name: "String"
}
},
enabled: {
required: true,
serializedName: "enabled",
type: {
name: "Boolean"
}
},
retentionPolicy: {
serializedName: "retentionPolicy",
type: {
name: "Composite",
className: "RetentionPolicy"
}
}
}
}
};
export const DiagnosticSettingsResource: msRest.CompositeMapper = {
serializedName: "DiagnosticSettingsResource",
type: {
name: "Composite",
className: "DiagnosticSettingsResource",
modelProperties: {
...ProxyOnlyResource.type.modelProperties,
storageAccountId: {
serializedName: "properties.storageAccountId",
type: {
name: "String"
}
},
serviceBusRuleId: {
serializedName: "properties.serviceBusRuleId",
type: {
name: "String"
}
},
eventHubAuthorizationRuleId: {
serializedName: "properties.eventHubAuthorizationRuleId",
type: {
name: "String"
}
},
eventHubName: {
serializedName: "properties.eventHubName",
type: {
name: "String"
}
},
metrics: {
serializedName: "properties.metrics",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "MetricSettings"
}
}
}
},
logs: {
serializedName: "properties.logs",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "LogSettings"
}
}
}
},
workspaceId: {
serializedName: "properties.workspaceId",
type: {
name: "String"
}
},
logAnalyticsDestinationType: {
serializedName: "properties.logAnalyticsDestinationType",
type: {
name: "String"
}
}
}
}
};
export const DiagnosticSettingsResourceCollection: msRest.CompositeMapper = {
serializedName: "DiagnosticSettingsResourceCollection",
type: {
name: "Composite",
className: "DiagnosticSettingsResourceCollection",
modelProperties: {
value: {
serializedName: "value",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "DiagnosticSettingsResource"
}
}
}
}
}
}
};
export const DiagnosticSettingsCategoryResource: msRest.CompositeMapper = {
serializedName: "DiagnosticSettingsCategoryResource",
type: {
name: "Composite",
className: "DiagnosticSettingsCategoryResource",
modelProperties: {
...ProxyOnlyResource.type.modelProperties,
categoryType: {
nullable: false,
serializedName: "properties.categoryType",
type: {
name: "Enum",
allowedValues: [
"Metrics",
"Logs"
]
}
}
}
}
};
export const DiagnosticSettingsCategoryResourceCollection: msRest.CompositeMapper = {
serializedName: "DiagnosticSettingsCategoryResourceCollection",
type: {
name: "Composite",
className: "DiagnosticSettingsCategoryResourceCollection",
modelProperties: {
value: {
serializedName: "value",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "DiagnosticSettingsCategoryResource"
}
}
}
}
}
}
};
export const OperationDisplay: msRest.CompositeMapper = {
serializedName: "Operation_display",
type: {
name: "Composite",
className: "OperationDisplay",
modelProperties: {
provider: {
serializedName: "provider",
type: {
name: "String"
}
},
resource: {
serializedName: "resource",
type: {
name: "String"
}
},
operation: {
serializedName: "operation",
type: {
name: "String"
}
}
}
}
};
export const Operation: msRest.CompositeMapper = {
serializedName: "Operation",
type: {
name: "Composite",
className: "Operation",
modelProperties: {
name: {
serializedName: "name",
type: {
name: "String"
}
},
display: {
serializedName: "display",
type: {
name: "Composite",
className: "OperationDisplay"
}
}
}
}
};
export const OperationListResult: msRest.CompositeMapper = {
serializedName: "OperationListResult",
type: {
name: "Composite",
className: "OperationListResult",
modelProperties: {
value: {
serializedName: "value",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "Operation"
}
}
}
},
nextLink: {
serializedName: "nextLink",
type: {
name: "String"
}
}
}
}
};
export const MetricDefinitionCollection: msRest.CompositeMapper = {
serializedName: "MetricDefinitionCollection",
type: {
name: "Composite",
className: "MetricDefinitionCollection",
modelProperties: {
value: {
required: true,
serializedName: "",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "MetricDefinition"
}
}
}
}
}
}
};
export const EventCategoryCollection: msRest.CompositeMapper = {
serializedName: "EventCategoryCollection",
type: {
name: "Composite",
className: "EventCategoryCollection",
modelProperties: {
value: {
required: true,
serializedName: "",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "LocalizableString"
}
}
}
}
}
}
}; | the_stack |
import { Common } from '../common';
import { Constants } from '../constants';
import { Capivara } from '../index';
import { CPAttr } from './directive/cp-attr';
import { CPBlur } from './directive/cp-blur';
import { CPChange } from './directive/cp-change';
import { CPClass } from './directive/cp-class';
import { CPClick } from './directive/cp-click';
import { CPDisabled } from './directive/cp-disabled';
import { CPElse } from './directive/cp-else';
import { CPElseIf } from './directive/cp-else-if';
import { CPFocus } from './directive/cp-focus';
import { CPHide } from './directive/cp-hide';
import { CPIf } from './directive/cp-if';
import { CPInit } from './directive/cp-init';
import { CPKey } from './directive/cp-key';
import { CPModel } from './directive/cp-model';
import { CPMouse } from './directive/cp-mouse';
import { CPRepeat } from './directive/cp-repeat';
import { CPShow } from './directive/cp-show';
import { CPStyle } from './directive/cp-style';
export class MapDom {
/**
* Elemento principal que está aplicado o escopo
*/
private readonly element: HTMLElement;
private directives = {
/**
* Mapa de atributos com os elementos que os observam.
*/
cpModelsElements: {},
/**
* Array com os cp-repeat
*/
cpIfs: [],
cpModels: [],
repeats: [],
cpShows: [],
cpElses: [],
cpElseIfs: [],
cpStyles: [],
cpClasses: [],
cpClicks: [],
cpInits: [],
cpKeys: [],
cpAttrs: [],
cpDisables: [],
cpFocus: [],
cpHide: [],
cpBlur: [],
cpMouse: [],
cpChange: [],
};
private readonly regexInterpolation;
/**
* @description variavel boleana que define se o HTML está renderizado na página.
*/
private renderedView: boolean;
constructor(_element: HTMLElement) {
this.element = _element;
this.regexInterpolation = new RegExp(/({{).*?(}})/g);
this.setRenderedView(false);
if (this.element) { this.$addScope(); }
}
/**
* @method void Percorre os elementos filhos do elemento principal criando os binds.
*/
public $addScope() {
this.createDirectives(this.element);
const recursiveBind = (element) => {
Array.from(element.children).forEach((child: any) => {
child[Constants.SCOPE_ATTRIBUTE_NAME] = Common.getScope(this.element);
this.createDirectives(child);
if (child.children) { recursiveBind(child); }
});
};
recursiveBind(this.element);
this.$directivesInit();
}
private setRenderedView(value: boolean) {
this.renderedView = value;
}
public $directivesInit() {
Common.getScope(this.element).$on('$onInit', () => {
Object.keys(this.directives).forEach((key) => {
const directives = this.directives[key];
if (Array.isArray(directives)) {
directives.forEach((directive) => directive.create());
}
});
this.$viewInit();
});
}
private $viewInit() {
this.setRenderedView(true);
if (this.element['$instance']) {
const ctrl = Common.getScope(this.element).scope[this.element['$instance'].config.controllerAs];
if (ctrl && ctrl['$onViewInit']) {
ctrl['$onViewInit']();
}
}
}
/**
* @method void Cria uma nova instancia de bind de acordo com o atributo declarado no elemento child.
* @param child Elemento que utiliza algum tipo de bind.
*/
public createDirectives(child) {
if (child.hasAttribute(Constants.MODEL_ATTRIBUTE_NAME)) { this.createCPModel(child); }
if (child.hasAttribute(Constants.IF_ATTRIBUTE_NAME)) { this.createCPIf(child); }
if (child.hasAttribute(Constants.CLICK_ATTRIBUTE_NAME) || child.hasAttribute(Constants.DBLCLICK_ATTRIBUTE_NAME)) { this.createCPClick(child); }
if (child.hasAttribute(Constants.REPEAT_ATTRIBUTE_NAME)) { this.createCPRepeat(child); }
if (child.hasAttribute(Constants.SHOW_ATTRIBUTE_NAME)) { this.createCPShow(child); }
if (child.hasAttribute(Constants.ELSE_ATTRIBUTE_NAME)) { this.createCPElse(child); }
if (child.hasAttribute(Constants.ELSE_IF_ATTRIBUTE_NAME)) { this.createCPElseIf(child); }
if (child.hasAttribute(Constants.INIT_ATTRIBUTE_NAME)) { this.createCPInit(child); }
if (child.hasAttribute(Constants.STYLE_ATTRIBUTE_NAME)) { this.createCPStyle(child); }
if (child.hasAttribute(Constants.CLASS_ATTRIBUTE_NAME)) { this.createCPClass(child); }
if (child.hasAttributeStartingWith(Constants.KEY_ATTRIBUTE_NAME)) { this.createCPKey(child); }
if (child.hasAttributeStartingWith(Constants.ATTR_ATTRIBUTE_NAME)) { this.createCPAttr(child); }
if (child.hasAttribute(Constants.DISABLE_ATTRIBUTE_NAME)) { this.createCPDisabled(child); }
if (child.hasAttribute(Constants.FOCUS_ATTRIBUTE_NAME)) { this.createCPFocus(child); }
if (child.hasAttribute(Constants.HIDE_ATTRIBUTE_NAME)) { this.createCPHide(child); }
if (child.hasAttribute(Constants.BLUR_ATTRIBUTE_NAME)) { this.createCPBlur(child); }
if (child.hasAttributeStartingWith(Constants.MOUSE_ATTRIBUTE_NAME)) { this.createCPmouse(child); }
if (child.hasAttribute(Constants.CHANGE_ATTRIBUTE_NAME)) { this.createCPChange(child); }
}
public reloadElementChildes(element, initialScope) {
if (element.children) {
Array.from(element.children).forEach((child: any) => {
const childScope = Common.getScope(child);
if (childScope && childScope.mapDom && childScope.id !== initialScope.id) {
childScope.mapDom.reloadDirectives();
}
this.reloadElementChildes(child, initialScope);
});
}
}
public reloadDirectives() {
// Update input values
Object.keys(this.directives.cpModelsElements)
.forEach((key) => this.directives.cpModelsElements[key].forEach((bind) => bind.applyModelInValue()));
// Update cp repeats
this.directives.repeats.forEach((repeat) => repeat.applyLoop());
// Update cp show
this.directives.cpShows.forEach((cpShow) => cpShow.init());
// Update cp if
this.directives.cpIfs.forEach((cpIf) => cpIf.init());
// Update cp else-if
this.directives.cpElseIfs.forEach((cpElseIf) => cpElseIf.init());
// Update cp else
this.directives.cpElses.forEach((cpElse) => cpElse.init());
// Update cp style
this.directives.cpStyles.forEach((cpStyle) => cpStyle.init());
// Update cp class
this.directives.cpClasses.forEach((cpClass) => cpClass.init());
// Update cp key
this.directives.cpKeys.forEach((cpKey) => cpKey.init());
// Update cp disable
this.directives.cpDisables.forEach((cpDisable) => cpDisable.init());
// Update cp focus
this.directives.cpFocus.forEach((cpFocus) => cpFocus.init());
// Update cp hide
this.directives.cpHide.forEach((cpHide) => cpHide.init());
// Update cp blur
this.directives.cpBlur.forEach((cpBlur) => cpBlur.init());
// Update cp Mouse
this.directives.cpMouse.forEach((cpMouse) => cpMouse.init());
// Update cp change
this.directives.cpChange.forEach((cpChange) => cpChange.init());
// Update cp attr
this.directives.cpAttrs.forEach((cpAttr) => cpAttr.init());
}
/**
* @method void Atualiza os valores dos elementos HTML de acordo com o atributo que está sendo observado.
*/
public reload() {
if (!this.renderedView) { return; }
this.reloadDirectives();
this.reloadElementChildes(this.element, Common.getScope(this.element));
this.processInterpolation();
}
/**
* @description Percorre os elementos para processar os interpolations.
* @param element
*/
public processInterpolation() {
this.getNodeTexts().forEach((nodeTextReference) => this.interpolation(nodeTextReference));
}
public getNodeTexts(): any {
let n;
const a = [],
walk = document.createTreeWalker(this.element, NodeFilter.SHOW_TEXT, null, false);
while (n = walk.nextNode()) { a.push(n); }
return a;
}
public getInterpolationValue(content, childNode) {
try {
return Common.evalInMultiContext(childNode, content.trim().startsWith(':') ? content.trim().slice(1) : content, undefined) + '';
} catch (e) {
return '';
}
}
/**
* @description Função que modifica o texto da interpolação pelo determinado valor.
* @param childNode
*/
public interpolation(childNode) {
if (!Common.parentHasIgnore(childNode)) {
childNode.originalValue = childNode.originalValue || childNode.nodeValue;
childNode.$immutableInterpolation = childNode.$immutableInterpolation || false;
if (childNode.$immutableInterpolation) { return; }
let nodeModified = childNode.originalValue, str = childNode.originalValue;
str = Capivara.replaceAll(str, Constants.START_INTERPOLATION, '{{');
str = Capivara.replaceAll(str, Constants.END_INTERPOLATION, '}}');
(str.match(this.regexInterpolation) || []).forEach((key) => {
const content = key.replace('{{', '').replace('}}', '');
if (!childNode.$immutableInterpolation) {
try {
const evalValue = this.getInterpolationValue(content, childNode);
key = Capivara.replaceAll(key, '{{', Constants.START_INTERPOLATION);
key = Capivara.replaceAll(key, '}}', Constants.END_INTERPOLATION);
nodeModified = nodeModified.replace(key, evalValue);
childNode.nodeValue = nodeModified;
} catch (e) { }
}
if (content.trim().startsWith(':') && !childNode.$immutableInterpolation) {
childNode.$immutableInterpolation = true;
}
});
childNode.nodeValue = childNode.nodeValue.replace(this.regexInterpolation, '');
}
}
/**
* @method void Retorna um mapa de atributos e elementos escutando alterações desse atributo.
*/
public getCpModels() {
return this.directives.cpModels;
}
/**
* @method void Adiciona um tipo de bind em um mapa, esse bind possui um elemento HTML que será atualizado quando o valor do atributo for alterado.
* @param capivaraBind Tipo de bind que será monitorado.
*/
public addCpModels(capivaraBind) {
this.directives.cpModelsElements[capivaraBind.attribute] = this.directives.cpModelsElements[capivaraBind.attribute] || [];
this.directives.cpModelsElements[capivaraBind.attribute].push(capivaraBind);
}
/**
*
* @param child Elemento que está sendo criado o bind de model
*/
public createCPModel(child) {
this.directives.cpModels.push(new CPModel(child, this));
}
/**
*
* @param child Elemento que está sendo criado o bind de click
*/
public createCPClick(child) {
this.directives.cpClicks.push(new CPClick(child, this));
}
/**
*
* @param child Elemento que está sendo criado o bind de show
*/
public createCPShow(child) {
this.directives.cpShows.push(new CPShow(child, this));
}
/**
*
* @param child Elemento que está sendo criado o bind do if
*/
public createCPIf(child) {
this.directives.cpIfs.push(new CPIf(child, this));
}
/**
*
* @param child Elemento que está sendo criado o bind do else
*/
public createCPElse(child) {
this.directives.cpElses.push(new CPElse(child, this));
}
/**
*
* @param child Elemento que está sendo criado o bind do else if
*/
public createCPElseIf(child) {
this.directives.cpElseIfs.push(new CPElseIf(child, this));
}
/**
*
* @param child Elemento que está sendo criado o bind de repeat.
*/
public createCPRepeat(child) {
this.directives.repeats.push(new CPRepeat(child, this));
}
/**
*
* @param child Elemento que está sendo criado o bind do init.
*/
public createCPInit(child) {
this.directives.cpInits.push(new CPInit(child, this));
}
/**
*
* @param child Elemento que está sendo criado o bind do style.
*/
public createCPStyle(child) {
this.directives.cpStyles.push(new CPStyle(child, this));
}
/**
*
* @param child Elemento que está sendo criado o bind do class.
*/
public createCPClass(child) {
this.directives.cpClasses.push(new CPClass(child, this));
}
/**
*
* @param child Elemento que está sendo criado o bind do key.
*/
public createCPKey(child) {
this.directives.cpKeys.push(new CPKey(child, this));
}
/**
* @param child Elemento que está criando a bind do attr.
*/
public createCPAttr(child) {
this.directives.cpAttrs.push(new CPAttr(child, this));
}
/**
* @param child Elemento que está sendo criado o bind do disable.
*/
public createCPDisabled(child) {
this.directives.cpDisables.push(new CPDisabled(child, this));
}
/**
* @param child Elemento que está sendo criado o bind do focus.
*/
public createCPFocus(child) {
this.directives.cpFocus.push(new CPFocus(child, this));
}
/**
* @param child Elemento que está sendo criado o bind do hide.
*/
public createCPHide(child) {
this.directives.cpHide.push(new CPHide(child, this));
}
/**
* @param child Elemento que está sendo criado o bind do blur.
*/
public createCPBlur(child) {
this.directives.cpBlur.push(new CPBlur(child, this));
}
/**
* @param child Elemento que está sendo criado o bind do dbTitle.
*/
public createCPmouse(child) {
this.directives.cpMouse.push(new CPMouse(child, this));
}
/**
* @param child Elemento que está sendo criado o bind do placeholder.
*/
public createCPChange(child) {
this.directives.cpChange.push(new CPChange(child, this));
}
} | the_stack |
import { FilenamePipe } from '../../shared/pipes/filename.pipe';
import { ComposeMailActions, ComposeMailActionTypes } from '../actions';
import {
ComposeMailState,
Draft,
PGP_MIME_DEFAULT_ATTACHMENT_FILE_NAME,
PGP_MIME_DEFAULT_CONTENT,
PGPEncryptionType,
} from '../datatypes';
import { Attachment, MailFolderType } from '../models';
import { getCryptoRandom } from '../services';
/**
* 1. Force Making Draft Mail that contains general text content and `encrypted.asc` as an attachment
* 2. Remove the other attachment because `encrypted.asc` already contains all of attachment and content
* 3. Set all of flags, so that it would be really composed after passed
* @param draftMail
* @param pgpMimeAttachment
* @private
*/
function updateDraftMailForPGPMimeMessage(
draftMail: Draft,
oldAttachment: Attachment,
newAttachment: Attachment,
): Draft {
const newDraftMail = { ...draftMail };
newDraftMail.draft.content = PGP_MIME_DEFAULT_CONTENT;
newDraftMail.draft.content_plain = PGP_MIME_DEFAULT_CONTENT;
newDraftMail.draft.is_encrypted = false;
newDraftMail.draft.is_subject_encrypted = false;
newDraftMail.draft.is_autocrypt_encrypted = false;
newDraftMail.draft.encryption_type = PGPEncryptionType.PGP_MIME;
newDraftMail.draft.attachments = [{ ...newAttachment, is_inline: true }];
newDraftMail.attachments = [{ ...newAttachment, is_inline: true }];
newDraftMail.isProcessingAttachments = false;
newDraftMail.encryptedContent = undefined;
newDraftMail.pgpMimeContent = undefined;
newDraftMail.isPGPMimeMessage = true;
newDraftMail.signContent = undefined;
return newDraftMail;
}
export function reducer(
// eslint-disable-next-line unicorn/no-object-as-default-parameter
state: ComposeMailState = { drafts: {}, usersKeys: new Map() },
action: ComposeMailActions,
): ComposeMailState {
switch (action.type) {
case ComposeMailActionTypes.SEND_MAIL:
case ComposeMailActionTypes.CREATE_MAIL: {
state.drafts[action.payload.id] = {
...state.drafts[action.payload.id],
isSaving: true,
inProgress: true,
shouldSend: false,
shouldSave: false,
isSent: false,
};
return { ...state, drafts: { ...state.drafts } };
}
case ComposeMailActionTypes.CREATE_MAIL_SUCCESS: {
const oldDraft = state.drafts[action.payload.draft.id];
const draftMail = action.payload.response;
if (action.payload.draft.draft.forward_attachments_of_message) {
oldDraft.attachments = draftMail.attachments.map((attachment: any) => {
attachment.progress = 100;
if (!attachment.name) {
attachment.name = FilenamePipe.tranformToFilename(attachment.document);
}
attachment.draftId = oldDraft.id;
attachment.attachmentId = performance.now() + Math.floor(getCryptoRandom() * 1000);
return attachment;
});
}
draftMail.is_html = oldDraft.draft.is_html;
state.drafts[action.payload.draft.id] = {
...oldDraft,
inProgress: false,
isSent: false,
draft: draftMail,
isSaving: false,
};
return { ...state, drafts: { ...state.drafts } };
}
case ComposeMailActionTypes.SEND_MAIL_SUCCESS: {
delete state.drafts[action.payload.id];
return { ...state, drafts: { ...state.drafts } };
}
case ComposeMailActionTypes.SEND_MAIL_FAILURE: {
state.drafts[action.payload.id] = {
...state.drafts[action.payload.id],
draft: { ...state.drafts[action.payload.id].draft, send: false, folder: MailFolderType.DRAFT },
inProgress: false,
isSent: false,
};
return { ...state, drafts: { ...state.drafts } };
}
case ComposeMailActionTypes.UPDATE_LOCAL_DRAFT: {
state.drafts[action.payload.id] = { ...state.drafts[action.payload.id], ...action.payload, inProgress: true };
return { ...state, drafts: { ...state.drafts } };
}
case ComposeMailActionTypes.GET_USERS_KEYS: {
if (action.payload.draftId && action.payload.draft) {
state.drafts[action.payload.draftId] = {
...state.drafts[action.payload.draftId],
...action.payload.draft,
// inProgress: true,
getUserKeyInProgress: true,
};
}
const { usersKeys, drafts } = state;
action.payload.emails.forEach((email: string) => {
usersKeys.set(email, { key: null, isFetching: true });
});
return { ...state, drafts: { ...drafts }, usersKeys };
}
case ComposeMailActionTypes.GET_USERS_KEYS_SUCCESS: {
const { usersKeys, drafts } = state;
if (action.payload.draftId) {
// TODO - should be check
drafts[action.payload.draftId] = {
...drafts[action.payload.draftId],
getUserKeyInProgress: false,
usersKeys: !action.payload.isBlind ? action.payload.data : drafts[action.payload.draftId].usersKeys,
};
}
// Saving on global user keys
if (!action.payload.isBlind && action.payload.data && action.payload.data.keys) {
action.payload.data.keys.forEach((key: any) => {
usersKeys.set(key.email, {
key:
usersKeys.has(key.email) && usersKeys.get(key.email).key && usersKeys.get(key.email).key.length > 0
? [...usersKeys.get(key.email).key, key]
: [key],
isFetching: false,
});
});
}
return {
...state,
drafts: { ...drafts },
usersKeys,
};
}
case ComposeMailActionTypes.UPDATE_PGP_ENCRYPTED_CONTENT: {
if (action.payload.draftId) {
state.drafts[action.payload.draftId] = {
...state.drafts[action.payload.draftId],
isPGPInProgress: action.payload.isPGPInProgress,
encryptedContent: action.payload.encryptedContent,
};
}
return {
...state,
drafts: { ...state.drafts },
};
}
case ComposeMailActionTypes.UPDATE_PGP_MIME_ENCRYPTED: {
if (action.payload.draftId) {
state.drafts[action.payload.draftId] = {
...state.drafts[action.payload.draftId],
isPGPMimeInProgress: action.payload.isPGPMimeInProgress,
pgpMimeContent: action.payload.encryptedContent,
};
}
return {
...state,
drafts: { ...state.drafts },
};
}
case ComposeMailActionTypes.UPDATE_PGP_SSH_KEYS: {
if (action.payload.draftId) {
state.drafts[action.payload.draftId] = {
...state.drafts[action.payload.draftId],
// isSshInProgress: action.payload.isSshInProgress,
};
if (action.payload.keys) {
state.drafts[action.payload.draftId].draft = {
...state.drafts[action.payload.draftId].draft,
encryption: {
...state.drafts[action.payload.draftId].draft.encryption,
// private_key: action.payload.keys.private_key,
// public_key: action.payload.keys.public_key,
},
};
}
}
return {
...state,
drafts: { ...state.drafts },
};
}
case ComposeMailActionTypes.UPDATE_SIGN_CONTENT: {
if (action.payload.draftId) {
state.drafts[action.payload.draftId] = {
...state.drafts[action.payload.draftId],
signContent: action.payload.signContent,
};
}
return {
...state,
drafts: { ...state.drafts },
};
}
case ComposeMailActionTypes.CLOSE_MAILBOX: {
if (action.payload && state.drafts[action.payload.id]) {
state.drafts[action.payload.id] = { ...state.drafts[action.payload.id], isClosed: true };
return { ...state, drafts: { ...state.drafts } };
}
return state;
}
case ComposeMailActionTypes.CLEAR_DRAFT: {
delete state.drafts[action.payload.id];
return { ...state, drafts: { ...state.drafts } };
}
case ComposeMailActionTypes.START_ATTACHMENT_ENCRYPTION: {
for (const [index, attachment] of state.drafts[action.payload.draftId].attachments.entries()) {
if (attachment.attachmentId === action.payload.attachmentId) {
state.drafts[action.payload.draftId].attachments[index] = {
...state.drafts[action.payload.draftId].attachments[index],
inProgress: true,
};
state.drafts[action.payload.draftId] = {
...state.drafts[action.payload.draftId],
isProcessingAttachments: true,
};
}
}
return { ...state, drafts: { ...state.drafts } };
}
case ComposeMailActionTypes.UPLOAD_ATTACHMENT: {
if (action.payload.id) {
for (const [index, attachment] of state.drafts[action.payload.draftId].attachments.entries()) {
if (attachment.attachmentId === action.payload.attachmentId) {
state.drafts[action.payload.draftId].attachments[index] = {
...state.drafts[action.payload.draftId].attachments[index],
inProgress: true,
};
state.drafts[action.payload.draftId] = {
...state.drafts[action.payload.draftId],
isProcessingAttachments: true,
};
}
}
} else {
state.drafts[action.payload.draftId].attachments = [
...state.drafts[action.payload.draftId].attachments,
{ ...action.payload, inProgress: true },
];
state.drafts[action.payload.draftId] = {
...state.drafts[action.payload.draftId],
isProcessingAttachments: true,
};
}
return { ...state, drafts: { ...state.drafts } };
}
case ComposeMailActionTypes.UPLOAD_ATTACHMENT_PROGRESS: {
for (const [index, attachment] of state.drafts[action.payload.draftId].attachments.entries()) {
if (attachment.attachmentId === action.payload.attachmentId) {
state.drafts[action.payload.draftId].attachments[index] = {
...state.drafts[action.payload.draftId].attachments[index],
progress: action.payload.progress,
};
}
}
return { ...state, drafts: { ...state.drafts } };
}
case ComposeMailActionTypes.UPLOAD_ATTACHMENT_REQUEST: {
for (const [index, attachment] of state.drafts[action.payload.draftId].attachments.entries()) {
if (attachment.attachmentId === action.payload.attachmentId) {
state.drafts[action.payload.draftId].attachments[index] = {
...state.drafts[action.payload.draftId].attachments[index],
request: action.payload.request,
};
}
}
return { ...state, drafts: { ...state.drafts } };
}
case ComposeMailActionTypes.UPLOAD_ATTACHMENT_SUCCESS: {
const { data, isPGPMimeMessage, response } = action.payload;
for (const [index, attachment] of state.drafts[data.draftId].attachments.entries()) {
if (attachment.attachmentId === data.attachmentId) {
state.drafts[data.draftId].attachments[index] = {
...state.drafts[data.draftId].attachments[index],
id: response.id,
document: response.document,
content_id: response.content_id,
inProgress: false,
request: null,
};
}
}
const isProcessingAttachments = !!state.drafts[data.draftId].attachments.some(
attachment => attachment.inProgress,
);
state.drafts[data.draftId] = { ...state.drafts[data.draftId], isProcessingAttachments };
if (isPGPMimeMessage && data.name === PGP_MIME_DEFAULT_ATTACHMENT_FILE_NAME) {
// PGP/MIME message process
state.drafts[data.draftId] = updateDraftMailForPGPMimeMessage(state.drafts[data.draftId], data, response);
}
return { ...state, drafts: { ...state.drafts } };
}
case ComposeMailActionTypes.UPLOAD_ATTACHMENT_FAILURE: {
state.drafts[action.payload.draftId].attachments = state.drafts[action.payload.draftId].attachments.filter(
attachment => attachment.attachmentId !== action.payload.attachmentId,
);
const isProcessingAttachments = !!state.drafts[action.payload.draftId].attachments.some(
attachment => attachment.inProgress,
);
state.drafts[action.payload.draftId] = { ...state.drafts[action.payload.draftId], isProcessingAttachments };
return { ...state, drafts: { ...state.drafts } };
}
case ComposeMailActionTypes.DELETE_ATTACHMENT: {
for (const [index, attachment] of state.drafts[action.payload.draftId].attachments.entries()) {
if (attachment.attachmentId === action.payload.attachmentId) {
state.drafts[action.payload.draftId].attachments[index] = {
...state.drafts[action.payload.draftId].attachments[index],
isRemoved: true,
inProgress: true,
};
}
}
state.drafts[action.payload.draftId] = { ...state.drafts[action.payload.draftId], isProcessingAttachments: true };
return { ...state, drafts: { ...state.drafts } };
}
case ComposeMailActionTypes.DELETE_ATTACHMENT_SUCCESS: {
state.drafts[action.payload.draftId].attachments = state.drafts[action.payload.draftId].attachments.filter(
attachment => {
if (attachment.attachmentId === action.payload.attachmentId) {
if (!attachment.id) {
attachment.request.unsubscribe();
}
return false;
}
return true;
},
);
const isProcessingAttachments = !!state.drafts[action.payload.draftId].attachments.some(
attachment => attachment.inProgress,
);
state.drafts[action.payload.draftId] = { ...state.drafts[action.payload.draftId], isProcessingAttachments };
return { ...state, drafts: { ...state.drafts } };
}
case ComposeMailActionTypes.DELETE_ATTACHMENT_FAILURE: {
for (const [index, attachment] of state.drafts[action.payload.draftId].attachments.entries()) {
if (attachment.attachmentId === action.payload.attachmentId) {
state.drafts[action.payload.draftId].attachments[index] = {
...state.drafts[action.payload.draftId].attachments[index],
isRemoved: false,
inProgress: false,
};
}
}
const isProcessingAttachments = !!state.drafts[action.payload.draftId].attachments.some(
attachment => attachment.inProgress,
);
state.drafts[action.payload.draftId] = { ...state.drafts[action.payload.draftId], isProcessingAttachments };
return { ...state, drafts: { ...state.drafts } };
}
case ComposeMailActionTypes.NEW_DRAFT: {
state.drafts[action.payload.id] = action.payload;
return { ...state, drafts: { ...state.drafts } };
}
case ComposeMailActionTypes.UPDATE_DRAFT_ATTACHMENT: {
for (const [index, attachment] of state.drafts[action.payload.draftId].attachments.entries()) {
if (attachment.attachmentId === action.payload.attachment.attachmentId) {
state.drafts[action.payload.draftId].attachments[index] = {
...state.drafts[action.payload.draftId].attachments[index],
...action.payload.attachment,
};
}
}
return { ...state, drafts: { ...state.drafts } };
}
case ComposeMailActionTypes.MATCH_CONTACT_USER_KEYS: {
const { usersKeys } = state;
if (action.payload.contactKeyAdd) {
const key = action.payload;
usersKeys.set(key.email, {
key:
usersKeys.has(key.email) && usersKeys.get(key.email).key && usersKeys.get(key.email).key.length > 0
? [...usersKeys.get(key.email).key, { email: key.email, public_key: key.public_key }]
: [{ email: key.email, public_key: key.public_key }],
isFetching: false,
});
// eslint-disable-next-line no-empty
} else if (action.payload.contactKeyUpdate) {
// eslint-disable-next-line no-empty
} else if (action.payload.contactKeyRemove) {
} else if (action.payload.contactAdd) {
// setting encryption type
const { email, enabledEncryption, encryptionType } = action.payload;
if (usersKeys.has(email) && usersKeys.get(email).key && usersKeys.get(email).key.length > 0) {
usersKeys.set(email, {
...usersKeys.get(email),
pgpEncryptionType: enabledEncryption ? encryptionType : null,
});
}
}
return { ...state, usersKeys };
}
default: {
return state;
}
}
} | the_stack |
import got from 'got'
import range from 'lodash.range'
import nock from 'nock'
import { Method } from '../../methods'
import Batch, {
chunkCommands,
MAX_COMMANDS_PER_BATCH,
mergeBatchPayloads,
prepareCommandsQueries
} from './batch'
describe('Client `chunkCommands` method', () => {
it('should chunk named commands', () => {
const chunkSize = 2
const commands = {
a: { method: Method.CRM_DEAL_GET },
b: { method: Method.CRM_LEAD_GET },
c: { method: Method.CRM_DEAL_LIST },
d: { method: Method.CRM_LEAD_LIST },
e: { method: Method.CRM_STATUS_LIST }
}
expect(chunkCommands(commands, chunkSize)).toMatchSnapshot()
})
it('should chunk array of commands', () => {
const chunkSize = 2
const commands = [
{ method: Method.CRM_DEAL_GET },
{ method: Method.CRM_LEAD_GET },
{ method: Method.CRM_DEAL_LIST },
{ method: Method.CRM_LEAD_LIST },
{ method: Method.CRM_STATUS_LIST }
] as const
expect(chunkCommands(commands, chunkSize)).toMatchSnapshot()
})
it('should by default chunk with a size of `MAX_COMMANDS_PER_BATCH`', () => {
const commandsSets = 2
const commands = range(0, MAX_COMMANDS_PER_BATCH * commandsSets).map(() => ({ method: Method.CRM_DEAL_GET }))
const chunked = chunkCommands(commands)
expect(chunked.length).toBe(commandsSets)
expect(chunked[0].length).toBe(MAX_COMMANDS_PER_BATCH)
})
})
describe('Client `prepareCommandsQueries` method', () => {
it('should transform dict of the commands into the query object', () => {
const testDealId = 11111
const commands = {
one: {
method: Method.CRM_DEAL_GET,
params: { ID: testDealId }
},
two: {
method: Method.CRM_DEAL_LIST,
params: {
filter: { '>PROBABILITY': 50 },
order: { STAGE_ID: 'ASC' },
select: ['ID', 'TITLE'],
start: 200
}
}
}
expect(prepareCommandsQueries(commands)).toMatchSnapshot()
})
it('should work with numbered commands', () => {
const commands = {
0: { method: Method.CRM_DEAL_GET },
1: { method: Method.CRM_DEAL_LIST }
}
expect(prepareCommandsQueries(commands)).toMatchSnapshot()
})
it('should work with array of commands', () => {
const commands = [
{ method: Method.CRM_DEAL_GET },
{ method: Method.CRM_DEAL_LIST }
] as const
expect(prepareCommandsQueries(commands)).toMatchSnapshot()
})
it('should return empty query object when no commands provided', () => {
expect(prepareCommandsQueries({})).toMatchSnapshot()
})
})
describe('Client `mergeBatchPayloads` method', () => {
it('should merge named payloads', () => {
const batch1 = {
result: {
result: {
a: [{ ID: '1' }, { ID: '2' }],
b: [{ ID: '3' }, { ID: '4' }]
},
result_error: [],
result_total: { a: 8, b: 8 },
result_next: { a: 2, b: 4 },
result_time: {
a: {
start: 1567196891.008149,
finish: 1567196891.022234,
duration: 0.014085054397583008,
processing: 0.013998985290527344,
date_start: '2019-08-30T23:28:11+03:00',
date_finish: '2019-08-30T23:28:11+03:00'
},
b: {
start: 1567196891.022316,
finish: 1567196891.03225,
duration: 0.009933948516845703,
processing: 0.009846210479736328,
date_start: '2019-08-30T23:28:11+03:00',
date_finish: '2019-08-30T23:28:11+03:00'
}
}
},
time: {
start: 1567196890.959017,
finish: 1567196891.223739,
duration: 0.2647218704223633,
processing: 0.21567082405090332,
date_start: '2019-08-30T23:28:10+03:00',
date_finish: '2019-08-30T23:28:11+03:00'
}
}
const batch2 = {
result: {
result: {
c: [{ ID: '5' }, { ID: '6' }],
d: [{ ID: '7' }, { ID: '8' }]
},
result_error: [],
result_total: { c: 8, d: 8 },
result_next: { c: 6, d: 8 },
result_time: {
c: {
start: 1567196891.032315,
finish: 1567196891.035297,
duration: 0.002981901168823242,
processing: 0.002897024154663086,
date_start: '2019-08-30T23:28:11+03:00',
date_finish: '2019-08-30T23:28:11+03:00'
},
d: {
start: 1567196891.03536,
finish: 1567196891.039936,
duration: 0.004575967788696289,
processing: 0.00450897216796875,
date_start: '2019-08-30T23:28:11+03:00',
date_finish: '2019-08-30T23:28:11+03:00'
}
}
},
time: {
start: 1567196890.959517,
finish: 1567196891.225739,
duration: 0.2647218704223683,
processing: 0.21567082405090832,
date_start: '2019-08-30T23:28:12+03:00',
date_finish: '2019-08-30T23:28:13+03:00'
}
}
expect(mergeBatchPayloads([batch1, batch2])).toMatchSnapshot()
})
it('should merge array payloads', () => {
const batch1 = {
result: {
result: [
[{ ID: '1' }, { ID: '2' }],
[{ ID: '3' }, { ID: '4' }]
],
result_error: [],
result_total: [8, 8],
result_next: [2, 4],
result_time: [{
start: 1567196891.008149,
finish: 1567196891.022234,
duration: 0.014085054397583008,
processing: 0.013998985290527344,
date_start: '2019-08-30T23:28:11+03:00',
date_finish: '2019-08-30T23:28:11+03:00'
}, {
start: 1567196891.022316,
finish: 1567196891.03225,
duration: 0.009933948516845703,
processing: 0.009846210479736328,
date_start: '2019-08-30T23:28:11+03:00',
date_finish: '2019-08-30T23:28:11+03:00'
}]
},
time: {
start: 1567196890.959017,
finish: 1567196891.223739,
duration: 0.2647218704223633,
processing: 0.21567082405090332,
date_start: '2019-08-30T23:28:10+03:00',
date_finish: '2019-08-30T23:28:11+03:00'
}
}
const batch2 = {
result: {
result: [
[{ ID: '5' }, { ID: '6' }],
[{ ID: '7' }, { ID: '8' }]
],
result_error: [],
result_total: [8, 8],
result_next: [6, 8],
result_time: [{
start: 1567196891.032315,
finish: 1567196891.035297,
duration: 0.002981901168823242,
processing: 0.002897024154663086,
date_start: '2019-08-30T23:28:11+03:00',
date_finish: '2019-08-30T23:28:11+03:00'
}, {
start: 1567196891.03536,
finish: 1567196891.039936,
duration: 0.004575967788696289,
processing: 0.00450897216796875,
date_start: '2019-08-30T23:28:11+03:00',
date_finish: '2019-08-30T23:28:11+03:00'
}]
},
time: {
start: 1567196890.959517,
finish: 1567196891.225739,
duration: 0.2647218704223683,
processing: 0.21567082405090832,
date_start: '2019-08-30T23:28:12+03:00',
date_finish: '2019-08-30T23:28:13+03:00'
}
}
expect(mergeBatchPayloads([batch1, batch2])).toMatchSnapshot()
})
})
const TEST_URI = 'https://test.com/rest'
const batch = Batch({
get: got.extend({ prefixUrl: TEST_URI, responseType: 'json' }).get
})
const RESPONSE_200 = 200
describe('Client `batch` method', () => {
it('should form a proper request', async () => {
const payload = { result: { result: { one: 'done', two: 'done' }, result_error: [] } }
const dealId = 999
const commands = {
one: { method: Method.CRM_DEAL_GET, params: { ID: dealId } },
two: { method: Method.CRM_DEAL_LIST }
}
const scope = nock(TEST_URI)
// @todo We'd want to use `query` object here as it is much more readable, but nock for some reason
// fails to match request when it contains `cmd[someName]`. The issue definitely connected
// to the `[]`, since it does not appear when only one bracket present
.get(
`/${Method.BATCH}?cmd%5Bone%5D=${commands.one.method}%3FID%3D${dealId}&cmd%5Btwo%5D=${commands.two.method}`
)
.reply(RESPONSE_200, payload)
await batch(commands)
expect(scope.done()).toBe(undefined)
})
it('should form a proper request with numbered commands', async () => {
const payload = { result: { result: ['done1', 'done2'], result_error: [] } }
const dealId = 999
const commands = {
0: { method: Method.CRM_DEAL_GET, params: { ID: dealId } },
1: { method: Method.CRM_DEAL_LIST }
} as const
const scope = nock(TEST_URI)
// @todo We'd want to use `query` object here as it is much more readable, but nock for some reason
// fails to match request when it contains `cmd[someName]`. The issue definitely
// connected to the `[]` since it does not appear when only one bracket present
.get(`/${Method.BATCH}?cmd%5B0%5D=${commands[0].method}%3FID%3D${dealId}&cmd%5B1%5D=${commands[1].method}`)
.reply(RESPONSE_200, payload)
await batch(commands)
expect(scope.done()).toBe(undefined)
})
it('should form a proper request with array of commands', async () => {
const payload = { result: { result: ['done1', 'done2'], result_error: [] } }
const dealId = 999
const commands = [
{ method: Method.CRM_DEAL_GET, params: { ID: dealId } },
{ method: Method.CRM_DEAL_LIST }
] as const
const scope = nock(TEST_URI)
// @todo We'd want to use `query` object here as it is much more readable, but nock for some reason
// fails to match request when it contains `cmd[someName]`. The issue definitely
// connected to the `[]` since it does not appear when only one bracket present
.get(`/${Method.BATCH}?cmd%5B0%5D=${commands[0].method}%3FID%3D${dealId}&cmd%5B1%5D=${commands[1].method}`)
.reply(RESPONSE_200, payload)
await batch(commands)
expect(scope.done()).toBe(undefined)
})
it('should form a proper requests with more than max allowed commands per batch', async () => {
const maxCommandsPerBatch = 1
const payload = { result: { result: { one: 'done', two: 'done' }, result_error: [] } }
const dealId = 999
const commands = {
one: { method: Method.CRM_DEAL_GET, params: { ID: dealId } },
two: { method: Method.CRM_DEAL_LIST }
}
const scope = nock(TEST_URI)
// @todo We'd want to use `query` object here as it is much more readable, but nock for some reason
// fails to match request when it contains `cmd[someName]`. The issue definitely connected
// to the `[]`, since it does not appear when only one bracket present
.get(
`/${Method.BATCH}?cmd%5Bone%5D=${commands.one.method}%3FID%3D${dealId}`
)
.reply(RESPONSE_200, payload)
.get(
`/${Method.BATCH}?cmd%5Btwo%5D=${commands.two.method}`
)
.reply(RESPONSE_200, payload)
await batch(commands, maxCommandsPerBatch)
expect(scope.done()).toBe(undefined)
})
it('should form a proper request with more than allowed max numbered commands', async () => {
const maxCommandsPerBatch = 1
const payload = { result: { result: ['done1', 'done2'], result_error: [] } }
const dealId = 999
const commands = {
0: { method: Method.CRM_DEAL_GET, params: { ID: dealId } },
1: { method: Method.CRM_DEAL_LIST }
} as const
const scope = nock(TEST_URI)
// @todo We'd want to use `query` object here as it is much more readable, but nock for some reason
// fails to match request when it contains `cmd[someName]`. The issue definitely
// connected to the `[]` since it does not appear when only one bracket present
.get(`/${Method.BATCH}?cmd%5B0%5D=${commands[0].method}%3FID%3D${dealId}`)
.reply(RESPONSE_200, payload)
.get(`/${Method.BATCH}?cmd%5B1%5D=${commands[1].method}`)
.reply(RESPONSE_200, payload)
await batch(commands, maxCommandsPerBatch)
expect(scope.done()).toBe(undefined)
})
it('should form a proper request with more than max allowed array of commands', async () => {
const maxCommandsPerBatch = 1
const payload = { result: { result: ['done1', 'done2'], result_error: [] } }
const dealId = 999
const commands = [
{ method: Method.CRM_DEAL_GET, params: { ID: dealId } },
{ method: Method.CRM_DEAL_LIST }
] as const
const scope = nock(TEST_URI)
// @todo We'd want to use `query` object here as it is much more readable, but nock for some reason
// fails to match request when it contains `cmd[someName]`. The issue definitely
// connected to the `[]` since it does not appear when only one bracket present
.get(`/${Method.BATCH}?cmd%5B0%5D=${commands[0].method}%3FID%3D${dealId}`)
.reply(RESPONSE_200, payload)
.get(`/${Method.BATCH}?cmd%5B0%5D=${commands[1].method}`)
.reply(RESPONSE_200, payload)
await batch(commands, maxCommandsPerBatch)
expect(scope.done()).toBe(undefined)
})
it('should return body as payload', async () => {
const commands = {
0: { method: Method.CRM_DEAL_GET },
1: { method: Method.CRM_DEAL_LIST }
}
const payload = {
result: {
result: ['done'],
result_error: [],
result_next: [],
result_time: [],
result_total: []
},
time: {}
}
nock(TEST_URI)
// @todo We'd want to use `query` object here as it is much more readable, but nock for some reason
// fails to match request when it contains `cmd[someName]`. The issue definitely connected
// to the `[]`, since it does not appear when only one bracket present
.get(`/${Method.BATCH}?cmd%5B0%5D=${commands[0].method}&cmd%5B1%5D=${commands[1].method}`)
.reply(RESPONSE_200, payload)
expect(await batch(commands)).toEqual(payload)
})
// @todo Test this also for named and numbered commands
it('should merge payloads when more then max allowed commands provided', async () => {
const maxAllowedCommands = 1
const commands = {
0: { method: Method.CRM_DEAL_GET },
1: { method: Method.CRM_DEAL_LIST }
}
const payload1 = {
result: {
result: ['done1'],
result_error: [],
result_next: [1],
result_time: [],
result_total: [2]
},
time: {}
}
const payload2 = {
result: {
result: ['done2'],
result_error: [],
result_next: [2],
result_time: [],
result_total: [2]
},
time: {}
}
nock(TEST_URI)
// @todo We'd want to use `query` object here as it is much more readable, but nock for some reason
// fails to match request when it contains `cmd[someName]`. The issue definitely connected
// to the `[]`, since it does not appear when only one bracket present
.get(`/${Method.BATCH}?cmd%5B0%5D=${commands[0].method}`)
.reply(RESPONSE_200, payload1)
.get(`/${Method.BATCH}?cmd%5B1%5D=${commands[1].method}`)
.reply(RESPONSE_200, payload2)
expect(await batch(commands, maxAllowedCommands)).toMatchSnapshot()
})
it.todo('should cast payload to the <P>')
it('should throw when getting errors in payload', () => {
const payload = {
result: {
result: { one: 'done', two: 'done' },
result_error: {
one: 'Expected error from numbered `batch` one',
two: 'Expected error from numbered `batch` two'
}
}
}
const commands = {
one: { method: Method.CRM_DEAL_GET },
two: { method: Method.CRM_DEAL_LIST }
}
nock(TEST_URI)
// @todo We'd want to use `query` object here as it is much more readable, but nock for some reason
// fails to match request when it contains `cmd[someName]`. The issue definitely connected
// to the `[]`, since it does not appear when only one bracket present
.get(`/${Method.BATCH}?cmd%5Bone%5D=${commands.one.method}&cmd%5Btwo%5D=${commands.two.method}`)
.reply(RESPONSE_200, payload)
return expect(batch(commands)).rejects.toMatchSnapshot()
})
it('should throw when getting errors in numbered commands payload', () => {
const payload = {
result: {
result: ['done'],
result_error: ['Expected error from numbered `batch` 0', 'Expected error from numbered `batch` 1']
}
}
const commands = {
0: { method: Method.CRM_DEAL_GET },
1: { method: Method.CRM_DEAL_LIST }
}
nock(TEST_URI)
// @todo We'd want to use `query` object here as it is much more readable, but nock for some reason
// fails to match request when it contains `cmd[someName]`. The issue definitely connected
// to the `[]`, since it does not appear when only one bracket present
.get(`/${Method.BATCH}?cmd%5B0%5D=${commands[0].method}&cmd%5B1%5D=${commands[1].method}`)
.reply(RESPONSE_200, payload)
return expect(batch(commands)).rejects.toMatchSnapshot()
})
it('should throw when getting errors in array of commands payload', () => {
const payload = {
result: {
result: ['done'],
result_error: ['Expected error from array of command `batch` 0', 'Expected error from array of command `batch` 1']
}
}
const commands = [
{ method: Method.CRM_DEAL_GET },
{ method: Method.CRM_DEAL_LIST }
] as const
nock(TEST_URI)
// @todo We'd want to use `query` object here as it is much more readable, but nock for some reason
// fails to match request when it contains `cmd[someName]`. The issue definitely connected
// to the `[]`, since it does not appear when only one bracket present
.get(`/${Method.BATCH}?cmd%5B0%5D=${commands[0].method}&cmd%5B1%5D=${commands[1].method}`)
.reply(RESPONSE_200, payload)
return expect(batch(commands)).rejects.toMatchSnapshot()
})
}) | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";
import * as Models from "../models";
import * as Mappers from "../models/organizationMappers";
import * as Parameters from "../models/parameters";
import { ConfluentManagementClientContext } from "../confluentManagementClientContext";
/** Class representing a Organization. */
export class Organization {
private readonly client: ConfluentManagementClientContext;
/**
* Create a Organization.
* @param {ConfluentManagementClientContext} client Reference to the service client.
*/
constructor(client: ConfluentManagementClientContext) {
this.client = client;
}
/**
* @summary List all organizations under the specified subscription.
* @param [options] The optional parameters
* @returns Promise<Models.OrganizationListBySubscriptionResponse>
*/
listBySubscription(options?: msRest.RequestOptionsBase): Promise<Models.OrganizationListBySubscriptionResponse>;
/**
* @param callback The callback
*/
listBySubscription(callback: msRest.ServiceCallback<Models.OrganizationResourceListResult>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
listBySubscription(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OrganizationResourceListResult>): void;
listBySubscription(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OrganizationResourceListResult>, callback?: msRest.ServiceCallback<Models.OrganizationResourceListResult>): Promise<Models.OrganizationListBySubscriptionResponse> {
return this.client.sendOperationRequest(
{
options
},
listBySubscriptionOperationSpec,
callback) as Promise<Models.OrganizationListBySubscriptionResponse>;
}
/**
* @summary List all Organizations under the specified resource group.
* @param resourceGroupName Resource group name
* @param [options] The optional parameters
* @returns Promise<Models.OrganizationListByResourceGroupResponse>
*/
listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.OrganizationListByResourceGroupResponse>;
/**
* @param resourceGroupName Resource group name
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.OrganizationResourceListResult>): void;
/**
* @param resourceGroupName Resource group name
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OrganizationResourceListResult>): void;
listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OrganizationResourceListResult>, callback?: msRest.ServiceCallback<Models.OrganizationResourceListResult>): Promise<Models.OrganizationListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
options
},
listByResourceGroupOperationSpec,
callback) as Promise<Models.OrganizationListByResourceGroupResponse>;
}
/**
* @summary Get the properties of a specific Organization resource.
* @param resourceGroupName Resource group name
* @param organizationName Organization resource name
* @param [options] The optional parameters
* @returns Promise<Models.OrganizationGetResponse>
*/
get(resourceGroupName: string, organizationName: string, options?: msRest.RequestOptionsBase): Promise<Models.OrganizationGetResponse>;
/**
* @param resourceGroupName Resource group name
* @param organizationName Organization resource name
* @param callback The callback
*/
get(resourceGroupName: string, organizationName: string, callback: msRest.ServiceCallback<Models.OrganizationResource>): void;
/**
* @param resourceGroupName Resource group name
* @param organizationName Organization resource name
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, organizationName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OrganizationResource>): void;
get(resourceGroupName: string, organizationName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OrganizationResource>, callback?: msRest.ServiceCallback<Models.OrganizationResource>): Promise<Models.OrganizationGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
organizationName,
options
},
getOperationSpec,
callback) as Promise<Models.OrganizationGetResponse>;
}
/**
* @summary Create Organization resource
* @param resourceGroupName Resource group name
* @param organizationName Organization resource name
* @param [options] The optional parameters
* @returns Promise<Models.OrganizationCreateResponse>
*/
create(resourceGroupName: string, organizationName: string, options?: Models.OrganizationCreateOptionalParams): Promise<Models.OrganizationCreateResponse> {
return this.beginCreate(resourceGroupName,organizationName,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.OrganizationCreateResponse>;
}
/**
* @summary Update Organization resource
* @param resourceGroupName Resource group name
* @param organizationName Organization resource name
* @param [options] The optional parameters
* @returns Promise<Models.OrganizationUpdateResponse>
*/
update(resourceGroupName: string, organizationName: string, options?: Models.OrganizationUpdateOptionalParams): Promise<Models.OrganizationUpdateResponse>;
/**
* @param resourceGroupName Resource group name
* @param organizationName Organization resource name
* @param callback The callback
*/
update(resourceGroupName: string, organizationName: string, callback: msRest.ServiceCallback<Models.OrganizationResource>): void;
/**
* @param resourceGroupName Resource group name
* @param organizationName Organization resource name
* @param options The optional parameters
* @param callback The callback
*/
update(resourceGroupName: string, organizationName: string, options: Models.OrganizationUpdateOptionalParams, callback: msRest.ServiceCallback<Models.OrganizationResource>): void;
update(resourceGroupName: string, organizationName: string, options?: Models.OrganizationUpdateOptionalParams | msRest.ServiceCallback<Models.OrganizationResource>, callback?: msRest.ServiceCallback<Models.OrganizationResource>): Promise<Models.OrganizationUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
organizationName,
options
},
updateOperationSpec,
callback) as Promise<Models.OrganizationUpdateResponse>;
}
/**
* @summary Delete Organization resource
* @param resourceGroupName Resource group name
* @param organizationName Organization resource name
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(resourceGroupName: string, organizationName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> {
return this.beginDeleteMethod(resourceGroupName,organizationName,options)
.then(lroPoller => lroPoller.pollUntilFinished());
}
/**
* @summary Create Organization resource
* @param resourceGroupName Resource group name
* @param organizationName Organization resource name
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginCreate(resourceGroupName: string, organizationName: string, options?: Models.OrganizationBeginCreateOptionalParams): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
organizationName,
options
},
beginCreateOperationSpec,
options);
}
/**
* @summary Delete Organization resource
* @param resourceGroupName Resource group name
* @param organizationName Organization resource name
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginDeleteMethod(resourceGroupName: string, organizationName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
organizationName,
options
},
beginDeleteMethodOperationSpec,
options);
}
/**
* @summary List all organizations under the specified subscription.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.OrganizationListBySubscriptionNextResponse>
*/
listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.OrganizationListBySubscriptionNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listBySubscriptionNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.OrganizationResourceListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listBySubscriptionNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OrganizationResourceListResult>): void;
listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OrganizationResourceListResult>, callback?: msRest.ServiceCallback<Models.OrganizationResourceListResult>): Promise<Models.OrganizationListBySubscriptionNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listBySubscriptionNextOperationSpec,
callback) as Promise<Models.OrganizationListBySubscriptionNextResponse>;
}
/**
* @summary List all Organizations under the specified resource group.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.OrganizationListByResourceGroupNextResponse>
*/
listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.OrganizationListByResourceGroupNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.OrganizationResourceListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OrganizationResourceListResult>): void;
listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OrganizationResourceListResult>, callback?: msRest.ServiceCallback<Models.OrganizationResourceListResult>): Promise<Models.OrganizationListByResourceGroupNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByResourceGroupNextOperationSpec,
callback) as Promise<Models.OrganizationListByResourceGroupNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listBySubscriptionOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.Confluent/organizations",
urlParameters: [
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.OrganizationResourceListResult
},
default: {
bodyMapper: Mappers.ResourceProviderDefaultErrorResponse
}
},
serializer
};
const listByResourceGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Confluent/organizations",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.OrganizationResourceListResult
},
default: {
bodyMapper: Mappers.ResourceProviderDefaultErrorResponse
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Confluent/organizations/{organizationName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.organizationName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.OrganizationResource
},
default: {
bodyMapper: Mappers.ResourceProviderDefaultErrorResponse
}
},
serializer
};
const updateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Confluent/organizations/{organizationName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.organizationName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: [
"options",
"body"
],
mapper: Mappers.OrganizationResourceUpdate
},
responses: {
200: {
bodyMapper: Mappers.OrganizationResource
},
default: {
bodyMapper: Mappers.ResourceProviderDefaultErrorResponse
}
},
serializer
};
const beginCreateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Confluent/organizations/{organizationName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.organizationName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: [
"options",
"body"
],
mapper: Mappers.OrganizationResource
},
responses: {
200: {
bodyMapper: Mappers.OrganizationResource
},
201: {
bodyMapper: Mappers.OrganizationResource
},
default: {
bodyMapper: Mappers.ResourceProviderDefaultErrorResponse
}
},
serializer
};
const beginDeleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Confluent/organizations/{organizationName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.organizationName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {},
202: {},
204: {},
default: {
bodyMapper: Mappers.ResourceProviderDefaultErrorResponse
}
},
serializer
};
const listBySubscriptionNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.OrganizationResourceListResult
},
default: {
bodyMapper: Mappers.ResourceProviderDefaultErrorResponse
}
},
serializer
};
const listByResourceGroupNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.OrganizationResourceListResult
},
default: {
bodyMapper: Mappers.ResourceProviderDefaultErrorResponse
}
},
serializer
}; | the_stack |
import React, { Component } from 'react';
import { render } from 'react-dom';
import Button from '../src/Button';
import RadioButtonGroup from '../../RadioButtonGroup';
import DropDownButton from '../../DropdownButton';
import SplitButton from '../../SplitButton';
import CheckBox from '../../CheckBox';
import '../../CheckBox/style/index.scss';
import '../../RadioButtonGroup/style/index.scss';
import '../../DropdownButton/style/index.scss';
import '../../SplitButton/style/index.scss';
import '../style/index.scss';
import 'typeface-roboto';
const icon = (
<svg style={{ width: 24, height: 24 }}>
<path
fill="#000000"
d="M12,4A4,4 0 0,1 16,8A4,4 0 0,1 12,12A4,4 0 0,1 8,8A4,4 0 0,1 12,4M12,14C16.42,14 20,15.79 20,18V20H4V18C4,15.79 7.58,14 12,14Z"
/>
</svg>
);
const widthOptions = ['auto', 100, 200, 300].map(value => {
return { value, label: typeof value == 'number' ? value + 'px' : value };
});
const themeOptions = ['light', 'default'].map(value => {
return { value, label: value };
});
const alignOptions = ['center', 'start', 'end'].map(value => {
return { value, label: value };
});
const verticalAlignOptions = ['middle', 'top', 'bottom'].map(value => {
return { value, label: value };
});
const iconPositionOptions = ['start', 'end', 'top', 'bottom'].map(value => {
return { value, label: value };
});
const PREVIEW_ICON = (
<svg
fill="#000000"
height="24"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M0 0h24v24H0z" fill="none" />
<path d="M11.5 9C10.12 9 9 10.12 9 11.5s1.12 2.5 2.5 2.5 2.5-1.12 2.5-2.5S12.88 9 11.5 9zM20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-3.21 14.21l-2.91-2.91c-.69.44-1.51.7-2.39.7C9.01 16 7 13.99 7 11.5S9.01 7 11.5 7 16 9.01 16 11.5c0 .88-.26 1.69-.7 2.39l2.91 2.9-1.42 1.42z" />
</svg>
);
const items = [
{
label: 'New',
icon: PREVIEW_ICON,
cellStyle: { color: 'red' },
},
{
label: 'Options',
disabled: true,
},
{
label: 'Format',
},
{ label: 'Save' },
'-',
{ label: 'Export as' },
{ label: 'Document' },
];
let pressedIndex = 0;
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
widthValue: '300',
heightValue: '300',
iconPosition: 'top',
align: 'start',
theme: 'default',
verticalAlign: 'middle',
showIcon: true,
disabled: false,
};
}
render() {
const style = {};
const { widthValue, heightValue } = this.state;
if (widthValue != 'auto') {
style.width = widthValue;
}
if (heightValue != 'auto') {
style.height = heightValue;
}
return (
<div style={{ fontFamily: 'Roboto', fontSize: 14, margin: 50 }}>
<div style={{ margin: 20 }}>
<div style={{ marginBottom: 30 }}>
Button theme:
<RadioButtonGroup
style={{ marginLeft: 20 }}
orientation="horizontal"
radioOptions={themeOptions}
radioValue={this.state.theme}
onChange={({ checkedItemValue: theme }) =>
this.setState({ theme })
}
/>{' '}
|{' '}
<input
type="checkbox"
checked={this.state.disabled}
onChange={ev => this.setState({ disabled: ev.target.checked })}
/>
disabled
</div>
<Button
icon={icon}
tagName="div"
theme={this.state.theme}
pressed
onClick={() => {
console.log('click', Date.now());
}}
>
simple text button
</Button>
<Button
disabled={this.state.disabled}
icon={icon}
tagName="div"
theme={this.state.theme}
pressed={false}
>
simple text button
</Button>
<Button
disabled={this.state.disabled}
icon={icon}
tagName="div"
theme={'light'}
pressed
>
simple text button
</Button>
<Button icon={icon} tagName="div" theme={'light'}>
simple text button
</Button>
</div>
<div style={{ margin: 30 }}>
<h3>DropDownButton</h3>
<DropDownButton renderMenuWhenCollapsed items={items}>
Hello
</DropDownButton>
</div>
<div style={{ margin: 30 }}>
<h3>SplitButton</h3>
<SplitButton
dropdownButtonProps={{ children: 'hello world' }}
items={items}
>
Hello
</SplitButton>
</div>
<div style={{ fontFamily: 'Roboto', fontSize: 14 }}>
<Button tagName="div">simple text button</Button>
<Button
align={this.state.align}
verticalAlign={this.state.verticalAlign}
icon={
this.state.showIcon ? (
<img
src="https://facebook.github.io/react/img/logo.svg"
height="30"
width="30"
/>
) : null
}
iconPosition={this.state.iconPosition}
style={style}
>
Export as React Component
</Button>
<div style={{ marginTop: 20 }}>
Button width:
<RadioButtonGroup
style={{ marginLeft: 20 }}
orientation="horizontal"
radioOptions={widthOptions}
radioValue={this.state.widthValue}
onChange={({ checkedItemValue: widthValue }) =>
this.setState({ widthValue })
}
/>
</div>
<div style={{ marginTop: 20 }}>
Button height:
<RadioButtonGroup
style={{ marginLeft: 20 }}
orientation="horizontal"
radioOptions={widthOptions}
radioValue={this.state.heightValue}
onChange={({ checkedItemValue: heightValue }) =>
this.setState({ heightValue })
}
/>
</div>
<div style={{ marginTop: 20 }}>
Align:
<RadioButtonGroup
style={{ marginLeft: 20 }}
orientation="horizontal"
radioOptions={alignOptions}
radioValue={this.state.align}
onChange={({ checkedItemValue: align }) =>
this.setState({ align })
}
/>
</div>
<div style={{ marginTop: 20 }}>
Vertical align:
<RadioButtonGroup
style={{ marginLeft: 20 }}
orientation="horizontal"
radioOptions={verticalAlignOptions}
radioValue={this.state.verticalAlign}
onChange={({ checkedItemValue: verticalAlign }) =>
this.setState({ verticalAlign })
}
/>
</div>
<div style={{ marginTop: 20 }}>
<CheckBox
checked={this.state.showIcon}
onChange={showIcon => {
this.setState({
showIcon,
});
}}
>
Show icon
</CheckBox>
</div>
<div style={{ marginTop: 20 }}>
Icon position:
<RadioButtonGroup
style={{ marginLeft: 20 }}
orientation="horizontal"
radioOptions={iconPositionOptions}
radioValue={this.state.iconPosition}
onChange={({ checkedItemValue: iconPosition }) =>
this.setState({ iconPosition })
}
/>
</div>
</div>
</div>
);
}
}
class App1 extends Component {
render() {
return (
<div className="App" style={{ padding: 10 }}>
<App />
<Button
overflow
activeStyle={{ background: 'blue' }}
onClick={() => console.log('blue active button')}
>
hello
</Button>
<Button type="big" onClick={() => console.log('big button')}>
Save as
</Button>
<Button href="#test">world</Button>
<Button>primary no theme</Button>
<Button disabled={true}>primary disabled</Button>
<Button defaultPressed={true}>toggle button</Button>
<Button disabled={true}>disabled</Button>
<Button ellipsis style={{ width: 100 }}>
ellipsis ellipsis ellipsis ellipsis ellipsis ellipsis
</Button>
<Button style={{ width: 100 }} align={'start'}>
left
</Button>
<Button style={{ width: 100 }} align={'end'}>
right
</Button>
<Button style={{ width: 100 }} rtl align={'start'}>
rtl
</Button>
<h1>Vertical align</h1>
<Button
style={{ height: 200, width: 650 }}
icon={() => 'x'}
iconPosition="top"
>
A long line here
</Button>
<h1>icons</h1>
<Button icon={icon} style={{ width: 100 }}>
icon default very long text
</Button>
<Button icon={icon} iconPosition="start">
icon start default
</Button>
<Button icon={icon} iconPosition="end">
icon end default
</Button>
<Button style={{ minWidth: 400 }} icon={icon} iconPosition="left">
icon left default
</Button>
<Button icon={icon} iconPosition="right">
icon right default
</Button>
<Button icon={icon} tagName="div" iconPosition="top">
icon top default
</Button>
<Button icon={icon} iconPosition="bottom">
icon bottom default
</Button>
<h1>icons with ellipsis</h1>
<Button icon={icon} style={{ width: 70 }} iconPosition="bottom">
icon bottom default
</Button>
</div>
);
}
}
render(<App1 />, document.getElementById('content')); | the_stack |
import {AttribValue, NumericAttribValue, PolyDictionary} from '../../types/GlobalTypes';
import {Vector2} from 'three/src/math/Vector2';
import {Vector3} from 'three/src/math/Vector3';
import {Vector4} from 'three/src/math/Vector4';
import {Object3D} from 'three/src/core/Object3D';
import {Mesh} from 'three/src/objects/Mesh';
import {Color} from 'three/src/math/Color';
import {BufferGeometry} from 'three/src/core/BufferGeometry';
import {AnimationClip} from 'three/src/animation/AnimationClip';
import {Material} from 'three/src/materials/Material';
import {SkinnedMesh} from 'three/src/objects/SkinnedMesh';
import {Bone} from 'three/src/objects/Bone';
import {CoreGeometry} from './Geometry';
import {GroupString} from './Group';
import {CoreAttribute} from './Attribute';
import {CoreConstant, AttribType, AttribSize} from './Constant';
import {CorePoint} from './Point';
import {CoreMaterial, ShaderMaterialWithCustomMaterials} from './Material';
import {CoreString} from '../String';
import {CoreEntity} from './Entity';
import {CoreType} from '../Type';
import {ObjectUtils} from '../ObjectUtils';
const PTNUM = 'ptnum';
const NAME_ATTR = 'name';
const ATTRIBUTES = 'attributes';
interface Object3DWithAnimations extends Object3D {
animations: AnimationClip[];
}
interface MaterialWithColor extends Material {
color: Color;
}
// interface SkinnedMeshWithisSkinnedMesh extends SkinnedMesh {
// readonly isSkinnedMesh: boolean;
// }
export class CoreObject extends CoreEntity {
constructor(private _object: Object3D, index: number) {
super(index);
if (this._object.userData[ATTRIBUTES] == null) {
this._object.userData[ATTRIBUTES] = {};
}
}
// set_index(i: number) {
// this._index = i;
// }
object() {
return this._object;
}
geometry(): BufferGeometry | null {
return (this._object as Mesh).geometry as BufferGeometry | null;
}
coreGeometry(): CoreGeometry | null {
const geo = this.geometry();
if (geo) {
return new CoreGeometry(geo);
} else {
return null;
}
// const geo = this.geometry()
// if (geo) {
// return new CoreGeometry(geo)
// } else {
// return null
// }
}
points() {
return this.coreGeometry()?.points() || [];
}
pointsFromGroup(group: GroupString): CorePoint[] {
if (group) {
const indices = CoreString.indices(group);
if (indices) {
const points = this.points();
return indices.map((i) => points[i]);
} else {
return [];
}
} else {
return this.points();
}
}
static isInGroup(groupString: string, object: Object3D) {
const group = groupString.trim();
if (group.length == 0) {
return true;
}
const elements = group.split('=');
const attribNameWithPrefix = elements[0];
if (attribNameWithPrefix[0] == '@') {
const attribName = attribNameWithPrefix.substr(1);
const expectedAttribValue = elements[1];
const currentAttribValue = this.attribValue(object, attribName);
return expectedAttribValue == currentAttribValue;
}
return false;
}
computeVertexNormals() {
this.coreGeometry()?.computeVertexNormals();
}
private static _convert_array_to_vector(value: number[]) {
switch (value.length) {
case 1:
return value[0];
case 2:
return new Vector2(value[0], value[1]);
case 3:
return new Vector3(value[0], value[1], value[2]);
case 4:
return new Vector4(value[0], value[1], value[2], value[3]);
}
}
static addAttribute(object: Object3D, attrib_name: string, value: AttribValue) {
if (CoreType.isArray(value)) {
const converted_value = this._convert_array_to_vector(value);
if (!converted_value) {
const message = `attribute_value invalid`;
console.error(message, value);
throw new Error(message);
}
}
// let data: ParamInitValueSerialized;
// if (value != null && !CoreType.isNumber(value) && !CoreType.isArray(value) && !CoreType.isString(value)) {
// data = (value as Vector3).toArray() as Number3;
// } else {
// data = value;
// }
const data = value;
const user_data = object.userData;
user_data[ATTRIBUTES] = user_data[ATTRIBUTES] || {};
user_data[ATTRIBUTES][attrib_name] = data;
}
addAttribute(name: string, value: AttribValue) {
CoreObject.addAttribute(this._object, name, value);
}
addNumericAttrib(name: string, value: NumericAttribValue) {
this.addAttribute(name, value);
}
setAttribValue(name: string, value: AttribValue) {
this.addAttribute(name, value);
}
addNumericVertexAttrib(name: string, size: number, default_value: NumericAttribValue) {
if (default_value == null) {
default_value = CoreAttribute.default_value(size);
}
this.coreGeometry()?.addNumericAttrib(name, size, default_value);
}
attributeNames(): string[] {
// TODO: to remove
return Object.keys(this._object.userData[ATTRIBUTES]);
}
attribNames(): string[] {
return this.attributeNames();
}
hasAttrib(name: string): boolean {
return this.attributeNames().includes(name);
}
renameAttrib(old_name: string, new_name: string) {
const current_value = this.attribValue(old_name);
if (current_value != null) {
this.addAttribute(new_name, current_value);
this.deleteAttribute(old_name);
} else {
console.warn(`attribute ${old_name} not found`);
}
}
deleteAttribute(name: string) {
delete this._object.userData[ATTRIBUTES][name];
}
static attribValue(
object: Object3D,
name: string,
index: number = 0,
target?: Vector2 | Vector3 | Vector4
): AttribValue | undefined {
if (name === PTNUM) {
return index;
}
if (object.userData && object.userData[ATTRIBUTES]) {
const val = object.userData[ATTRIBUTES][name] as AttribValue;
if (val == null) {
if (name == NAME_ATTR) {
return object.name;
}
} else {
if (CoreType.isArray(val) && target) {
target.fromArray(val);
return target;
}
}
return val;
}
if (name == NAME_ATTR) {
return object.name;
}
}
static stringAttribValue(object: Object3D, name: string, index: number = 0): string | undefined {
const str = this.attribValue(object, name, index);
if (str != null) {
if (CoreType.isString(str)) {
return str;
} else {
return `${str}`;
}
}
}
attribValue(name: string, target?: Vector2 | Vector3 | Vector4): AttribValue | undefined {
return CoreObject.attribValue(this._object, name, this._index, target);
}
stringAttribValue(name: string) {
return CoreObject.stringAttribValue(this._object, name, this._index);
}
name(): string {
return this.attribValue(NAME_ATTR) as string;
}
humanType(): string {
return CoreConstant.CONSTRUCTOR_NAMES_BY_CONSTRUCTOR_NAME[this._object.constructor.name];
}
attribTypes() {
const h: PolyDictionary<AttribType> = {};
for (let attrib_name of this.attribNames()) {
const type = this.attribType(attrib_name);
if (type != null) {
h[attrib_name] = type;
}
}
return h;
}
attribType(name: string) {
const val = this.attribValue(name);
if (CoreType.isString(val)) {
return AttribType.STRING;
} else {
return AttribType.NUMERIC;
}
}
attribSizes() {
const h: PolyDictionary<AttribSize> = {};
for (let attrib_name of this.attribNames()) {
const size = this.attribSize(attrib_name);
if (size != null) {
h[attrib_name] = size;
}
}
return h;
}
attribSize(name: string): AttribSize | null {
const val = this.attribValue(name);
if (val == null) {
return null;
}
return CoreAttribute.attribSizeFromValue(val);
}
clone() {
return CoreObject.clone(this._object);
}
static clone(src_object: Object3D) {
const new_object = src_object.clone();
var sourceLookup = new Map<Object3D, Object3D>();
var cloneLookup = new Map<Object3D, Object3D>();
CoreObject.parallelTraverse(src_object, new_object, function (sourceNode: Object3D, clonedNode: Object3D) {
sourceLookup.set(clonedNode, sourceNode);
cloneLookup.set(sourceNode, clonedNode);
});
new_object.traverse(function (node) {
const src_node = sourceLookup.get(node) as SkinnedMesh;
const mesh_node = node as Mesh;
if (mesh_node.geometry) {
const src_node_geometry = src_node.geometry as BufferGeometry;
mesh_node.geometry = CoreGeometry.clone(src_node_geometry);
const mesh_node_geometry = mesh_node.geometry as BufferGeometry;
if (mesh_node_geometry.userData) {
mesh_node_geometry.userData = ObjectUtils.cloneDeep(src_node_geometry.userData);
}
}
if (mesh_node.material) {
mesh_node.material = src_node.material;
CoreMaterial.applyCustomMaterials(node, mesh_node.material as ShaderMaterialWithCustomMaterials);
// prevents crashes for linesegments with shader material such as the line dashed instance
// TODO: test
const material_with_color = mesh_node.material as MaterialWithColor;
if (material_with_color.color == null) {
material_with_color.color = new Color(1, 1, 1);
}
}
if (src_object.userData) {
node.userData = ObjectUtils.cloneDeep(src_node.userData);
}
const src_node_with_animations = (<unknown>src_node) as Object3DWithAnimations;
if (src_node_with_animations.animations) {
(node as Object3DWithAnimations).animations = src_node_with_animations.animations.map((animation) =>
animation.clone()
);
}
const skinned_node = node as SkinnedMesh;
if (skinned_node.isSkinnedMesh) {
var clonedMesh = skinned_node;
var sourceMesh = src_node;
var sourceBones = sourceMesh.skeleton.bones;
clonedMesh.skeleton = sourceMesh.skeleton.clone();
clonedMesh.bindMatrix.copy(sourceMesh.bindMatrix);
const new_bones = sourceBones.map(function (bone) {
return cloneLookup.get(bone);
}) as Bone[];
clonedMesh.skeleton.bones = new_bones;
clonedMesh.bind(clonedMesh.skeleton, clonedMesh.bindMatrix);
}
});
return new_object;
}
static parallelTraverse(a: Object3D, b: Object3D, callback: (a: Object3D, b: Object3D) => void) {
callback(a, b);
for (var i = 0; i < a.children.length; i++) {
this.parallelTraverse(a.children[i], b.children[i], callback);
}
}
} | the_stack |
import * as ts from '@terascope/utils';
import { FieldType } from '@terascope/types';
import crypto from 'crypto';
import PhoneValidator from 'awesome-phonenumber';
import { format as dateFormat, parse } from 'date-fns';
import { ReplaceLiteralConfig, ReplaceRegexConfig, ExtractFieldConfig } from './interfaces';
import {
isString,
isValidDate,
isNumber,
isArray,
isNumberTuple
} from '../validations/field-validator';
import { Repository, InputType } from '../interfaces';
export const repository: Repository = {
toString: {
fn: toString,
config: {},
output_type: FieldType.String,
primary_input_type: InputType.String
},
toBoolean: {
fn: toBoolean,
config: {},
output_type: FieldType.Boolean,
primary_input_type: InputType.Any
},
toUpperCase: {
fn: toUpperCase,
config: {},
output_type: FieldType.String,
primary_input_type: InputType.String
},
toLowerCase: {
fn: toLowerCase,
config: {},
output_type: FieldType.String,
primary_input_type: InputType.String
},
trim: {
fn: trim,
config: {
char: { type: FieldType.String }
},
output_type: FieldType.String,
primary_input_type: InputType.String
},
truncate: {
fn: truncate,
config: {
size: { type: FieldType.Number }
},
output_type: FieldType.String,
primary_input_type: InputType.String
},
toISDN: {
fn: toISDN,
config: {},
output_type: FieldType.String,
primary_input_type: InputType.String
},
toNumber: {
fn: toNumber,
config: {
booleanLike: { type: FieldType.Boolean }
},
output_type: FieldType.Number,
primary_input_type: InputType.String
},
decodeBase64: {
fn: decodeBase64,
config: {},
output_type: FieldType.String,
primary_input_type: InputType.String
},
encodeBase64: {
fn: encodeBase64,
config: {},
output_type: FieldType.String,
primary_input_type: InputType.String
},
decodeURL: {
fn: decodeURL,
config: {},
output_type: FieldType.String,
primary_input_type: InputType.String
},
encodeURL: {
fn: encodeURL,
config: {},
output_type: FieldType.String,
primary_input_type: InputType.String
},
decodeHex: {
fn: decodeHex,
config: {},
output_type: FieldType.String,
primary_input_type: InputType.String
},
encodeHex: {
fn: encodeHex,
config: {},
output_type: FieldType.String,
primary_input_type: InputType.String
},
encodeMD5: {
fn: encodeMD5,
config: {},
output_type: FieldType.String,
primary_input_type: InputType.String
},
encodeSHA: {
fn: encodeSHA,
config: {
hash: { type: FieldType.String },
digest: { type: FieldType.String }
},
output_type: FieldType.String,
primary_input_type: InputType.String
},
encodeSHA1: {
fn: encodeSHA1,
config: {},
output_type: FieldType.String,
primary_input_type: InputType.String
},
parseJSON: {
fn: parseJSON,
config: {},
output_type: FieldType.Any,
primary_input_type: InputType.String
},
toJSON: {
fn: toJSON,
config: {
pretty: { type: FieldType.Boolean }
},
output_type: FieldType.String,
primary_input_type: InputType.Any
},
toGeoPoint: {
fn: toGeoPoint,
config: {},
output_type: FieldType.GeoPoint,
primary_input_type: InputType.String
},
// this will be overridden
extract: {
fn: extract,
config: {
regex: { type: FieldType.String },
isMultiValue: { type: FieldType.Boolean },
jexlExp: { type: FieldType.String },
start: { type: FieldType.String },
end: { type: FieldType.String }
},
output_type: FieldType.Any,
primary_input_type: InputType.String
},
replaceRegex: {
fn: replaceRegex,
config: {
regex: { type: FieldType.String },
replace: { type: FieldType.String },
global: { type: FieldType.String },
ignore_case: { type: FieldType.Boolean }
},
output_type: FieldType.String,
primary_input_type: InputType.String
},
replaceLiteral: {
fn: replaceLiteral,
config: {
search: {
type: FieldType.String
},
replace: {
type: FieldType.String
}
},
output_type: FieldType.String,
primary_input_type: InputType.String
},
toUnixTime: {
fn: toUnixTime,
config: {},
output_type: FieldType.Number,
primary_input_type: InputType.String
},
toISO8601: {
fn: toISO8601,
config: {
resolution: {
type: FieldType.String,
description: 'may be set to seconds | milliseconds'
}
},
output_type: FieldType.String,
primary_input_type: InputType.String
},
formatDate: {
fn: formatDate,
config: {
format: { type: FieldType.String },
resolution: { type: FieldType.String, description: 'may be set to seconds | milliseconds' },
},
output_type: FieldType.String,
primary_input_type: InputType.String
},
parseDate: {
fn: parseDate,
config: {
format: { type: FieldType.String },
},
output_type: FieldType.Date,
primary_input_type: InputType.String
},
trimStart: {
fn: trimStart,
config: {
char: { type: FieldType.String }
},
output_type: FieldType.String,
primary_input_type: InputType.String
},
trimEnd: {
fn: trimEnd,
config: {
char: { type: FieldType.String }
},
output_type: FieldType.String,
primary_input_type: InputType.String
},
toCamelCase: {
fn: toCamelCase,
config: {},
output_type: FieldType.String,
primary_input_type: InputType.String
},
toKebabCase: {
fn: toKebabCase,
config: {},
output_type: FieldType.String,
primary_input_type: InputType.String
},
toPascalCase: {
fn: toPascalCase,
config: {},
output_type: FieldType.String,
primary_input_type: InputType.String
},
toSnakeCase: {
fn: toSnakeCase,
config: {},
output_type: FieldType.String,
primary_input_type: InputType.String
},
toTitleCase: {
fn: toTitleCase,
config: {},
output_type: FieldType.String,
primary_input_type: InputType.String
},
setField: {
fn: setField,
config: {
value: {
type: FieldType.Any
}
},
output_type: FieldType.Any,
primary_input_type: InputType.String
},
setDefault: {
fn: setDefault,
config: {
value: {
type: FieldType.Any
}
},
output_type: FieldType.Any,
primary_input_type: InputType.String
},
map: {
fn: map,
config: {
fn: {
type: FieldType.String
},
options: {
type: FieldType.Object
}
},
output_type: FieldType.Any,
primary_input_type: InputType.Array
},
splitString: {
fn: splitString,
config: {},
output_type: FieldType.String,
primary_input_type: InputType.String
}
};
type StringInput = string | string[] | null | undefined;
/**
* This function is used to set a value if input is null or undefined,
* otherwise the input value is returned
*
* @example
*
* const results = FieldTransform.setDefault(undefined, {}, { value: 'someValue' });
* results === 'someValue';
*
* @param {*} input
* @param {{ value: any }} args value is what will be given when input is null/undefined
* @returns {*}
*/
export function setDefault(input: unknown, _parentContext: unknown, args: { value: any }): any {
if (ts.isNil(input)) {
if (ts.isNil(args.value)) throw new Error('Parameter value cannot be set to undefined or null');
return args.value;
}
return input;
}
/**
* This function is used to map an array of values with any FieldTransform method
*
* @example
*
* const array = ['hello', 'world', 'goodbye'];
* const results = FieldTransform.map(array, array, { fn: 'truncate', options: { size: 3 } }
* results === ['hel', 'wor', 'goo']
*
* @param {any[]} input an array of any value
* @param {{fn:string; options?:any}} args fn any FieldTransform function name,
* options is an object with any additional parameters needed
* @returns {any[] | null} returns the mapped values, return null if input is null/undefined
*/
export function map(
input: any[], parentContext: any[], args: { fn: string; options?: any }
): any[]|null {
if (ts.isNil(input)) return null;
if (!isArray(input)) throw new Error(`Input must be an array, received ${ts.getTypeOf(input)}`);
const { fn, options } = args;
const repoConfig = repository[fn];
if (!repoConfig) throw new Error(`No function ${fn} was found in the field transform repository`);
return input.map((data) => repoConfig.fn(data, parentContext, options));
}
// TODO: this is currently a hack for directives, this will evolve, do not use it for other purposes
/**
* This function is not meant to be used programmatically
* please use `RecordTransform.setField` instead
*
* @param {*} _input This value will be discarded
* @param {{ value: any }} args value will be used to set field
* @returns
*/
export function setField(_input: unknown, _parentContext: unknown, args: { value: any }): any {
const { value } = args;
return value;
}
/**
* Converts values to strings
* if given an array it will convert everything in the array excluding null/undefined values
*
* @example
*
* FieldTransform.toString(true); // 'true';
* FieldTransform.toString([true, undefined, false]); // ['true', 'false'];
*
* @param {*} input
* @returns {String | null} returns null if input is null/undefined
*/
export function toString(input: unknown, _parentContext?: unknown): string|string[]|null {
if (ts.isNil(input)) return null;
if (isArray(input)) return input.filter(ts.isNotNil).map(ts.toString);
return ts.toString(input);
}
/**
* Converts values to booleans
* if given an array it will convert everything in the array excluding null/undefined values
*
* @example
*
* FieldTransform.toBoolean('0'); // false
* FieldTransform.toBoolean(['foo', 'false', null]); // [true, false];
*
* @param {*} input
* @returns {Boolean | null} returns null if input is null/undefined
*/
export function toBoolean(input: unknown, _parentContext?: unknown): boolean|boolean[]|null {
if (ts.isNil(input)) return null;
if (isArray(input)) return input.filter(ts.isNotNil).map(ts.toBoolean);
return ts.toBoolean(input);
}
/**
* Converts strings to UpperCase
* if given an array it will convert everything in the array excluding null/undefined values
*
* @example
*
* FieldTransform.toUpperCase('lowercase'); // 'LOWERCASE';
* FieldTransform.toUpperCase(['MixEd', null, 'lower']); // ['MIXED', 'LOWER'];
*
* @param {StringInput} input string or string[]
* @returns { String | String[] | null } returns null if input is null/undefined
*/
export function toUpperCase(input: StringInput, _parentContext?: unknown): string|string[]|null {
if (ts.isNil(input)) return null;
if (isArray(input)) return input.filter(ts.isNotNil).map((str: string) => str.toUpperCase());
if (!isString(input)) throw new Error(`Input must be a string, or an array of string, received ${ts.getTypeOf(input)}`);
return input.toUpperCase();
}
/**
* Converts strings to lowercase
* if given an array it will convert everything in the array excluding null/undefined values
*
* @example
*
* FieldTransform.toLowerCase('UPPERCASE'); // 'uppercase';
* FieldTransform.toLowerCase(['MixEd', null, 'UPPER']); // ['mixed', 'upper'];
*
* @param {StringInput} input string | string[]
* @returns { String | String[] | null } returns null if input is null/undefined
*/
export function toLowerCase(input: StringInput, _parentContext?: unknown): string|string[]|null {
if (ts.isNil(input)) return null;
if (isArray(input)) return input.filter(ts.isNotNil).map((str: string) => str.toLowerCase());
if (!isString(input)) throw new Error(`Input must be a string, or an array of string, received ${ts.getTypeOf(input)}`);
return input.toLowerCase();
}
/**
* Will trim the input
* if given an array it will convert everything in the array excluding null/undefined values
*
* @example
*
* FieldTransform.trim('right '); // 'right';
* FieldTransform.trim('fast cars race fast', {}, { char: 'fast' }); // ' cars race ';
* FieldTransform.trim(' string ')).toBe('string');
* FieldTransform.trim(' left')).toBe('left');
* FieldTransform.trim('.*.*a regex test.*.*.*.* stuff', {}, { char: '.*' }); // 'a regex test'
* FieldTransform.trim('\t\r\rtrim this\r\r', {}, { char: '\r' }); // 'trim this'
* FieldTransform.trim(' '); // ''
* FieldTransform.trim(['right ', ' left']); // ['right', 'left'];
*
* @param {StringInput} input string | string[]
* @param {{ char: string }} [args] a single char or word that will be cut out
* @returns { String | String[] | null } returns null if input is null/undefined
*/
export function trim(
input: StringInput, parentContext?: unknown, args?: { char: string }
): string|string[]|null {
if (ts.isNil(input)) return null;
const char: string = (args?.char && isString(args.char)) ? args.char : ' ';
if (isArray(input)) {
return input
.filter(ts.isNotNil)
.map((str: string) => ts.trim(str, char));
}
return ts.trim(input, char);
}
/**
* Will trim the beginning of the input
* if given an array it will convert everything in the array excluding null/undefined values
*
* @example
*
* const config = { char: 'i' };
* FieldTransform.trimStart(' Hello Bob '); // 'Hello Bob ';
* FieldTransform.trimStart('iiii-wordiwords-iii', {}, config); // '-wordiwords-iii';
* FieldTransform.trimStart([' Hello Bob ', 'right ']); // ['Hello Bob ', 'right '];
*
* @param {StringInput} input string | string[]
* @param {{ char: string }} [args]
* @returns { String | String[] | null } returns null if input is null/undefined
*/
export function trimStart(
input: StringInput, _parentContext?: unknown, args?: { char: string }
): string|string[]|null {
if (ts.isNil(input)) return null;
if (args?.char && !isString(args.char)) throw new Error(`Parameter char must be a string, received ${ts.getTypeOf(input)}`);
if (isArray(input)) {
return input
.filter(ts.isNotNil)
.map((str: any) => ts.trimStart(str, args?.char));
}
if (!isString(input)) throw new Error(`Input must be a string, or an array of string, received ${ts.getTypeOf(input)}`);
return ts.trimStart(input, args?.char);
}
/**
* Will trim the end of the input
* if given an array it will convert everything in the array excluding null/undefined values
*
* @example
*
* FieldTransform.trimEnd(' Hello Bob '); // ' Hello Bob';
* FieldTransform.trimEnd('iiii-wordiwords-iii', {}, { char: 'i' }); // 'iiii-wordiwords';
* FieldTransform.trimEnd([' Hello Bob ', 'right ']); // [' Hello Bob', 'right'];
*
* @param {StringInput} input string | string[]
* @param {{ char: string }} [args]
* @returns { String | String[] | null } returns null if input is null/undefined
*/
export function trimEnd(
input: StringInput, _parentContext?: unknown, args?: { char: string }
): string|string[]|null {
if (ts.isNil(input)) return null;
if (args?.char && !isString(args.char)) throw new Error(`Parameter char must be a string, received ${ts.getTypeOf(input)}`);
if (isArray(input)) {
return input
.filter(ts.isNotNil)
.map((str: any) => ts.trimEnd(str, args?.char));
}
if (!isString(input)) throw new Error(`Input must be a string, or an array of string, received ${ts.getTypeOf(input)}`);
return ts.trimEnd(input, args?.char);
}
/**
* Will truncate the input to the length of the size given
* if given an array it will convert everything in the array excluding null/undefined values
*
* @example
*
* FieldTransform.truncate('thisisalongstring', {}, { size: 4 }); // 'this';
* FieldTransform.truncate(['hello', null, 'world'], {}, { size: 2 }); // ['he', 'wo'];
*
* @param {StringInput} input string | string[]
* @param {{ size: number }} args
* @returns { String | String[] | null } returns null if input is null/undefined
*/
export function truncate(
input: StringInput, _parentContext: unknown, args: { size: number }
): string|string[]|null {
const { size } = args;
if (ts.isNil(input)) return null;
if (!size || !ts.isNumber(size) || size <= 0) throw new Error('Invalid size paramter for truncate');
if (isArray(input)) {
return input
.filter(ts.isNotNil)
.map((str: any) => str.slice(0, size));
}
if (!isString(input)) throw new Error(`Input must be a string, or an array of string, received ${ts.getTypeOf(input)}`);
return input.slice(0, size);
}
function parsePhoneNumber(str: any) {
let testNumber = ts.toString(str).trim();
if (testNumber.charAt(0) === '0') testNumber = testNumber.slice(1);
// needs to start with a +
if (testNumber.charAt(0) !== '+') testNumber = `+${testNumber}`;
const fullNumber = new PhoneValidator(testNumber).getNumber();
if (fullNumber) return String(fullNumber).slice(1);
throw Error('Could not determine the incoming phone number');
}
/**
* Parses a string or number to a fully validated phone number
* if given an array it will convert everything in the array excluding null/undefined values
*
* @example
*
* FieldTransform.toISDN('+33-1-22-33-44-55'); // '33122334455';
* FieldTransform.toISDN('1(800)FloWErs'); // '18003569377';
* FieldTransform.toISDN(['1(800)FloWErs','+33-1-22-33-44-55' ]); // ['18003569377', '33122334455'];
*
* @param {*} input string | string[] | number | number[]
* @returns { String | String[] | null } a fully validated phone number,
* returns null if input is null/undefined
*/
export function toISDN(input: unknown, _parentContext?: unknown): string|string[]|null {
if (ts.isNil(input)) return null;
if (isArray(input)) return input.filter(ts.isNotNil).map(parsePhoneNumber);
return parsePhoneNumber(input);
}
function convertToNumber(input: any, args?: { booleanLike?: boolean }) {
let result = input;
if (args?.booleanLike === true && ts.isBooleanLike(input)) {
result = ts.toNumber(toBoolean(result));
}
result = ts.toNumber(result);
if (Number.isNaN(result)) throw new Error(`Could not convert input of type ${ts.getTypeOf(input)} to a number`);
return result;
}
/**
* Converts a value to a number if possible
* if given an array it will convert everything in the array excluding null/undefined values
*
* @example
*
* FieldTransform.toNumber('12321'); // 12321;
* FieldTransform.toNumber('000011'); // 11;
* FieldTransform.toNumber('true', {}, { booleanLike: true }); // 1;
* FieldTransform.toNumber(null, {}, { booleanLike: true }); // 0;
* FieldTransform.toNumber(null); // null;
* FieldTransform.toNumber(['000011', '12321']); // [11, 12321];
*
* @param {*} input
* @param {{ booleanLike?: boolean }} [args]
* @returns { number | null } returns null if input is null/undefined
*/
export function toNumber(
input: unknown, _parentContext?: unknown, args?: { booleanLike?: boolean }
): number|number[]|null {
if (ts.isNil(input) && args?.booleanLike !== true) return null;
if (isArray(input)) {
return input
.filter(ts.isNotNil)
.map((data: any) => convertToNumber(data, args));
}
return convertToNumber(input, args);
}
/**
* decodes a base64 encoded value
* if given an array it will convert everything in the array excluding null/undefined values
*
* @example
*
* const str = 'hello world';
* const encoded = encodeBase64(str);
*
* const results = FieldTransform.decodeBase64(encoded)
* results === str
*
* FieldTransform.decodeBase64([encoded]) === [str]
*
* @param {*} input
* @returns { string | null } returns null if input is null/undefined
*/
export function decodeBase64(input: unknown, _parentContext?: unknown): string|string[]|null {
if (ts.isNil(input)) return null;
if (isArray(input)) {
return input
.filter(ts.isNotNil)
.map((data: any) => Buffer.from(data, 'base64').toString('utf8'));
}
return Buffer.from(input as string, 'base64').toString('utf8');
}
/**
* converts a value into a base64 encoded value
* if given an array it will convert everything in the array excluding null/undefined values
*
* @example
*
* const str = 'hello world';
*
* const encodedValue = FieldTransform.encodeBase64(str);
* const arrayOfEncodedValues = FieldTransform.encodeBase64([str]);
*
* @param {*} input
* @returns { string | null } returns null if input is null/undefined
*/
export function encodeBase64(input: unknown, _parentContext?: unknown): string|string[]|null {
if (ts.isNil(input)) return null;
if (isArray(input)) {
return input
.filter(ts.isNotNil)
.map((data: any) => Buffer.from(data).toString('base64'));
}
return Buffer.from(input as any).toString('base64');
}
/**
* decodes a URL encoded value
* if given an array it will convert everything in the array excluding null/undefined values
*
* @example
*
* const source = 'HELLO AND GOODBYE';
* const encoded = 'HELLO%20AND%20GOODBYE';
*
* FieldTransform.decodeURL(encoded); // source;
* FieldTransform.decodeURL([encoded]); //[source];
*
* @param {StringInput} input
* @returns { string | null } returns null if input is null/undefined
*/
export function decodeURL(input: StringInput, _parentContext?: unknown): string|string[]|null {
if (ts.isNil(input)) return null;
if (isArray(input)) return input.filter(ts.isNotNil).map(decodeURIComponent);
if (!isString(input)) throw new Error(`Input must be a string, or an array of string, received ${ts.getTypeOf(input)}`);
return decodeURIComponent(input);
}
/**
* URL encodes a value
* if given an array it will convert everything in the array excluding null/undefined values
*
* @example
*
* const source = 'HELLO AND GOODBYE';
* const encoded = 'HELLO%20AND%20GOODBYE';
*
* FieldTransform.encodeURL(source); // encoded;
* const arrayOfEncodedValues = FieldTransform.encodeURL([source]);
*
* @param {StringInput} input
* @returns { string | null } returns null if input is null/undefined
*/
export function encodeURL(input: StringInput, _parentContext?: unknown): string|string[]|null {
if (ts.isNil(input)) return null;
if (isArray(input)) return input.filter(ts.isNotNil).map(encodeURIComponent);
if (!isString(input)) throw new Error(`Input must be a string, or an array of string, received ${ts.getTypeOf(input)}`);
return encodeURIComponent(input);
}
/**
* decodes the hex encoded input
* if given an array it will convert everything in the array excluding null/undefined values
*
* @example
*
* const source = 'hello world';
* const encoded = encodeHex(source);
*
* FieldTransform.decodeHex(encoded); // source;
* FieldTransform.decodeHex([encoded]); // [source];
*
* @param {*} input
* @returns { string | null } returns null if input is null/undefined
*/
export function decodeHex(input: unknown, _parentContext?: unknown): string|string[]|null {
if (ts.isNil(input)) return null;
if (isArray(input)) {
return input
.filter(ts.isNotNil)
.map((data: any) => Buffer.from(data, 'hex').toString('utf8'));
}
return Buffer.from(input as string, 'hex').toString('utf8');
}
/**
* hex encodes the input
* if given an array it will convert everything in the array excluding null/undefined values
*
* @example
*
* const source = 'hello world';
*
* FieldTransform.encodeHex(source);
* const arrayOfEncodedValues = FieldTransform.encodeHex([source]);
*
* @param {*} input
* @returns { string | null } returns null if input is null/undefined
*/
export function encodeHex(input: unknown, _parentContext?: unknown): string|string[]|null {
if (ts.isNil(input)) return null;
if (isArray(input)) {
return input
.filter(ts.isNotNil)
.map((data: any) => Buffer.from(data).toString('hex'));
}
return Buffer.from(input as string).toString('hex');
}
/**
* MD5 encodes the input
* if given an array it will convert everything in the array excluding null/undefined values
* @example
* const source = 'hello world';
*
* FieldTransform.encodeMD5(source);
* const arrayOfEncodedValues = FieldTransform.encodeHex([source]);
*
* @param {*} input
* @returns { string | null } returns null if input is null/undefined
*/
export function encodeMD5(input: unknown, _parentContext?: unknown): string|string[]|null {
if (ts.isNil(input)) return null;
if (isArray(input)) {
return input
.filter(ts.isNotNil)
.map((data: any) => crypto.createHash('md5').update(data).digest('hex'));
}
return crypto.createHash('md5').update(input as string).digest('hex');
}
/**
* SHA encodes the input to the hash specified
* if given an array it will convert everything in the array excluding null/undefined values
*
* @example
*
* const data = 'some string';
* const config = { hash: 'sha256', digest: 'hex'};
* fieldTransform.encodeSHA(data , {}, config)
* const arrayOfEncodedValues = FieldTransform.encodeSHA([source], {}, config);
*
* @param {*} input
* @param {*} [{ hash = 'sha256', digest = 'hex' }={}]
* possible digest values ['ascii', 'utf8', 'utf16le', 'ucs2', 'base64', 'latin1', 'hex', 'binary']
* possible hash values
* @returns { string | null } returns null if input is null/undefined
*/
export function encodeSHA(
input: unknown, _parentContext?: unknown, { hash = 'sha256', digest = 'hex' } = {}
): string|string[]|null {
if (ts.isNil(input)) return null;
if (!['ascii', 'utf8', 'utf16le', 'ucs2', 'base64', 'latin1', 'hex', 'binary'].includes(digest)) {
throw new Error('Parameter digest is misconfigured');
}
if (isArray(input)) {
return input
.filter(ts.isNotNil)
.map((data: any) => crypto.createHash(hash).update(data).digest(digest as any));
}
return crypto.createHash(hash).update(input as string).digest(digest as any);
}
/**
* converts the value to a SHA1 encoded value
* if given an array it will convert everything in the array excluding null/undefined values
*
* @example
*
* const source = 'hello world';
*
* FieldTransform.encodeSHA1(source);
* const arrayOfEncodedValues = FieldTransform.encodeSHA([source]);
*
* @param {*} input
* @returns { string | null } returns null if input is null/undefined
*/
export function encodeSHA1(input: unknown, _parentContext?: unknown): string|string[]|null {
if (ts.isNil(input)) return null;
if (isArray(input)) {
return input
.filter(ts.isNotNil)
.map((data: any) => crypto.createHash('sha1').update(data).digest('hex'));
}
return crypto.createHash('sha1').update(input as string).digest('hex');
}
/**
* Parses the json input
* if given an array it will convert everything in the array excluding null/undefined values
*
* @example
*
* const obj = { hello: 'world' };
* const json = JSON.stringify(obj);
* const results = FieldTransform.parseJSON(json);
* results === obj
*
* FieldTransform.parseJSON([json]); // [obj]
*
* @param {*} input
* @returns { any | null } returns null if input is null/undefined
*/
export function parseJSON(input: unknown, _parentContext?: unknown): any|null {
if (ts.isNil(input)) return null;
if (isArray(input)) {
return input
.filter(ts.isNotNil)
.map((data: any) => JSON.parse(data));
}
return JSON.parse(input as string);
}
/**
* Converts input to JSON
* if given an array it will convert everything in the array excluding null/undefined values
*
* @example
*
* const obj = { hello: 'world' };
*
* FieldTransform.toJSON(obj); // '{"hello": "world"}'
* FieldTransform.toJSON([obj]); // ['{"hello": "world"}']
*
* @param {*} input
* @param {*} [{ pretty = false }={}] setting pretty to true will format the json output
* @returns { string | string[] | null } returns null if input is null/undefined
*/
export function toJSON(
input: unknown, _parentContext?: unknown, { pretty = false } = {}
): string|string[]|null {
if (ts.isNil(input)) return null;
if (isArray(input)) {
return input
.filter(ts.isNotNil)
.map((data: any) => {
if (pretty) return JSON.stringify(data, null, 2);
return JSON.stringify(data);
});
}
if (pretty) return JSON.stringify(input, null, 2);
return JSON.stringify(input);
}
/**
* Converts the value into a geo-point
* if given an array it will convert everything in the array excluding null/undefined values
*
* @example
*
* fieldTransform.toGeoPoint('60, 40'); // { lon: 40, lat: 60 };
* fieldTransform.toGeoPoint([40, 60]); // { lon: 40, lat: 60 };
* fieldTransform.toGeoPoint({ lat: 40, lon: 60 }); // { lon: 60, lat: 40 };
* fieldTransform.toGeoPoint({ latitude: 40, longitude: 60 }); // { lon: 60, lat: 40 }
*
* const results = FieldTransform.toGeoPoint(['60, 40', null, [50, 60]]);
* results === [{ lon: 40, lat: 60 },{ lon: 50, lat: 60 }];
*
* @param {*} input
* @returns {{ lat: number, lon: number } | { lat: number, lon: number }[] | null }
* returns null if input is null/undefined
*/
export function toGeoPoint(
input: unknown, _parentContext?: unknown
): { lat: number, lon: number }|({ lat: number, lon: number })[]|null {
if (ts.isNil(input)) return null;
// a tuple of numbers is a form of geo-point, do not map it
if (isArray(input) && !isNumberTuple(input)) {
return input
.filter(ts.isNotNil)
.map((data: any) => ts.parseGeoPoint(data, true));
}
return ts.parseGeoPoint(input as any, true);
}
/**
* Can extract values from a string input. You may either specify a regex, a jexl expression, or
* specify the start and end from which the extraction will take all values between
* if given an array it will convert everything in the array excluding null/undefined values
*
* @param {*} input
* @param {ExtractFieldConfig} {
* regex, isMultiValue = true, jexlExp, start, end
* }
* If regex is specified, it will run the regex against the value.
* If isMultiValue is true, then an array containing the return results will be returned.
* If it is set to false, then only the first possible extraction will be returned.
* start/end are used as boundaries for extraction, should not be used with jexlExp or regex
* jexlExp is a jexl expression => https://github.com/TomFrost/Jexl
* @returns { string | string[] | null } returns null if input is null/undefined
*
* @example
*
* const config = { start: '<', end: '>' }
* const results1 = FieldTransform.extract('<hello>', { field: '<hello>' }, config);
* results1; // 'hello';
*
* const results2 = FieldTransform.extract('bar', { foo: 'bar' }, { jexlExp: '[foo]' });
* results2; // ['bar'];
*
* const results3 = FieldTransform.extract('hello', { field: 'hello'}, { regex: 'he.*' });
* results3; // ['hello'];
*
* const config2 = { regex: 'he.*', isMultiValue: false };
* const results = FieldTransform.extract('hello', { field: 'hello'}, config2);
* results; // 'hello';
*
* const context = { field: ['<hello>', '<world>'] };
* const results = FieldTransform.extract(['<hello>', '<world>'], context, config);
* results; // ['hello', 'world'];
*/
// this will be overritten by extract in jexl folder
export function extract(
_input: unknown,
_parentContext: ts.AnyObject,
_args: ExtractFieldConfig
): any|null {}
/**
* This function replaces chars in a string based off the regex value provided
*
* @example
*
* const config1 = { regex: 's|e', replace: 'd' };
* const results1 = FieldTransform.replaceRegex('somestring', {}, config1)
* results1 === 'domestring'
*
* const config2 = { regex: 's|e', replace: 'd', global: true };
* const results2 = FieldTransform.replaceRegex('somestring', {}, config)
* results2 === 'domddtring'
*
* const config3 = {
* regex: 'm|t', replace: 'W', global: true, ignoreCase: true
* };
* const results3 = FieldTransform.replaceRegex('soMesTring', {}, config3))
* results3 === 'soWesWring'
*
* @param {StringInput} input
* @param {ReplaceRegexConfig} {
* regex, replace, ignoreCase, global
* }
* @returns { string | string[] | null } returns null if input is null/undefined
*/
export function replaceRegex(
input: StringInput,
_parentContext: unknown,
{
regex, replace, ignoreCase, global
}: ReplaceRegexConfig
): string|string[]|null {
if (ts.isNil(input)) return null;
let options = '';
if (ignoreCase) options += 'i';
if (global) options += 'g';
if (isArray(input)) {
return input.filter(ts.isNotNil).map((data: any) => {
if (!isString(data)) throw new Error(`Input must be a string, or an array of string, received ${ts.getTypeOf(input)}`);
const re = new RegExp(regex, options);
return data.replace(re, replace);
});
}
if (!isString(input)) throw new Error(`Input must be a string, or an array of string, received ${ts.getTypeOf(input)}`);
const re = new RegExp(regex, options);
return input.replace(re, replace);
}
/**
* This function replaces the searched value with the replace value
*
* @example
*
* const context = { key: 'Hi bob' };
* FieldTransform.replaceLiteral('Hi bob', context, { search: 'bob', replace: 'mel' }) === 'Hi mel';
* FieldTransform.replaceLiteral('Hi Bob', context, { search: 'bob', replace: 'Mel' }) === 'Hi Bob';
*
* const data = ['Hi bob', 'hello bob'];
* const config = { search: 'bob', replace: 'mel' };
* FieldTransform.replaceLiteral(data, {}, config) // ['Hi mel', 'hello mel'];
*
* @param {StringInput} input
* @param {ReplaceLiteralConfig} { search, replace }
* search is the word that is to be changed to the value specified with the paramter replace
* @returns { string | string[] | null } returns null if input is null/undefined
*/
export function replaceLiteral(
input: StringInput,
_parentContext: unknown,
{ search, replace }: ReplaceLiteralConfig
): string|string[]|null {
if (ts.isNil(input)) return null;
if (isArray(input)) {
return input.filter(ts.isNotNil).map((data: any) => {
if (!isString(data)) throw new Error(`Input must be a string, or an array of string, received ${ts.getTypeOf(data)}`);
return data.replace(search, replace);
});
}
if (!isString(input)) throw new Error(`Input must be a string, or an array of string, received ${ts.getTypeOf(input)}`);
try {
return input.replace(search, replace);
} catch (e) {
throw new Error(`Could not replace ${search} with ${replace}`);
}
}
/**
* Converts a string to an array of characters split by the delimiter provided
*
* @example
*
* FieldTransform.splitString('astring'); // ['a', 's', 't', 'r', 'i', 'n', 'g'];
* FieldTransform.splitString('astring', {}, { delimiter: ',' }); // ['astring'];
* expect(FieldTransform.splitString(
* 'a-stri-ng', {}, { delimiter: '-' }
* )).toEqual(['a', 'stri', 'ng']);
*
* @param {*} input
* @param {{ delimiter: string }} [args] delimter defaults to an empty string
* @returns {(string[] | null)}
*/
export function splitString(
input: unknown,
_parentContext?: unknown,
args?: { delimiter: string }
): string[]|(string[][])|null {
if (ts.isNil(input)) return null;
const delimiter = args ? args.delimiter : '';
if (isArray(input)) {
return input.filter(ts.isNotNil).map((data: any) => {
if (!ts.isString(data)) {
throw new Error(`Input must be a string, or an array of string, received ${ts.getTypeOf(data)}`);
}
return data.split(delimiter);
});
}
if (ts.isString(input)) {
return input.split(delimiter);
}
throw new Error(`Input must be a string or an array, got ${ts.getTypeOf(input)}`);
}
function _makeUnitTime(input: any, { ms = false } = {}) {
let time: boolean | number;
if (ms) {
time = ts.getTime(input);
} else {
time = ts.getUnixTime(input);
}
return time as number;
}
/**
* Converts a given date to its time in milliseconds or seconds
*
* @example
*
* FieldTransform.toUnixTime('2020-01-01'); // 1577836800;
* FieldTransform.toUnixTime('Jan 1, 2020 UTC'); // 1577836800;
* FieldTransform.toUnixTime('2020 Jan, 1 UTC'); // 1577836800;
*
* FieldTransform.toUnixTime(1580418907000); // 1580418907;
* FieldTransform.toUnixTime(1580418907000, {}, { ms: true }); // 1580418907000;
*
* FieldTransform.toUnixTime(['Jan 1, 2020 UTC', '2020 Jan, 1 UTC']); // [1577836800, 1577836800];
*
* @param {*} input
* @param {*} [{ ms = false }={}] set ms to true if you want time in milliseconds
* @returns { number | number[] | null} returns null if input is null/undefined
*/
export function toUnixTime(
input: unknown, _parentContext?: unknown, { ms = false } = {}
): number|number[]|null {
if (ts.isNil(input)) return null;
if (isArray(input)) {
return input.filter(ts.isNotNil).map((data: any) => {
if (!isValidDate(data)) {
throw new Error(`Not a valid date, cannot transform ${data} to unix time`);
}
return _makeUnitTime(data, { ms });
});
}
if (!isValidDate(input)) throw new Error(`Not a valid date, cannot transform ${input} to unix time`);
return _makeUnitTime(input, { ms });
}
function _makeIso(input: any, args?: { resolution?: 'seconds' | 'milliseconds' }) {
let value = input;
if (isNumber(input) && args && args.resolution) value *= 1000;
return new Date(value).toISOString();
}
/**
* Converts a date string or number to an ISO date
*
* @example
*
* FieldTransform.toISO8601('2020-01-01'); // '2020-01-01T00:00:00.000Z';
*
* const config = { resolution: 'seconds' };
* FieldTransform.toISO8601(1580418907, {}, config); // '2020-01-30T21:15:07.000Z';
*
* const data = ['2020-01-01', '2020-01-02'];
* FieldTransform.toISO8601(data); // ['2020-01-01T00:00:00.000Z', '2020-01-02T00:00:00.000Z'];
*
* @param {*} input
* @param {({ resolution?: 'seconds' | 'milliseconds' })} [args]
* if input is a number, you may specify the resolution of that number, defaults to seconds
* @returns { string | string[] | null } returns null if input is null/undefined
*/
export function toISO8601(
input: unknown, _parentContext?: unknown, args?: { resolution?: 'seconds' | 'milliseconds' }
): string|string[]|null {
if (ts.isNil(input)) return null;
if (isArray(input)) {
return input
.filter(ts.isNotNil)
.map((data: any) => {
if (!isValidDate(data)) {
throw new Error(`Input is not valid date, received ${data}`);
}
return _makeIso(data, args);
});
}
if (!isValidDate(input)) {
throw new Error(`Input is not valid date, received ${input}`);
}
return _makeIso(input, args);
}
interface FormatDateConfig {
format: string;
resolution?: 'seconds' | 'milliseconds';
}
function _formatDate(input: any, args: FormatDateConfig) {
if (!isValidDate(input)) {
throw new Error('Input is not valid date');
}
let value = input;
const { format, resolution } = args;
if (!isString(format)) throw new Error(`Invalid parameter format, must be a string, received ${ts.getTypeOf(input)}`);
if (isString(value)) value = new Date(value);
if (isNumber(value) && resolution === 'seconds') value *= 1000;
return dateFormat(value, format);
}
/**
* Function that will format a number or date string to a given date format provided
*
* @example
*
* const config = { format: 'MMM do yy' };
* const results1 = FieldTransform.formatDate('2020-01-14T20:34:01.034Z', {}, config)
* results1 === 'Jan 14th 20';
*
* const results2 = FieldTransform.formatDate('March 3, 2019', {}, { format: 'M/d/yyyy' })
* results2 === '3/3/2019';
*
* const config = { format: 'yyyy-MM-dd', resolution: 'seconds' };
* const results3 = FieldTransform.formatDate(1581013130, {}, config)
* results3 === '2020-02-06';
*
* const config = { format: 'yyyy-MM-dd' };
* const results = FieldTransform.formatDate([1581013130856, undefined], {}, config)
* results // ['2020-02-06']);
*
* @param {*} input
* @param {{ format: string, resolution?: 'seconds' | 'milliseconds' }} args
* format is the shape that the date will be, resolution is only needed when input is a number
* @returns { string | string[] | null } returns null if input is null/undefined
*/
export function formatDate(
input: unknown, _parentContext: unknown, args: FormatDateConfig
): string|string[]|null {
if (ts.isNil(input)) return null;
if (isArray(input)) {
return input
.filter(ts.isNotNil)
.map((data: any) => _formatDate(data, args));
}
return _formatDate(input, args);
}
interface ParseDateConfig {
format: string;
}
function _parseDate(input: any, args: ParseDateConfig) {
if (ts.isNil(input)) return null;
const { format } = args;
if (!isString(format)) {
throw new Error(`Invalid parameter format, must be a string, received ${ts.getTypeOf(input)}`);
}
const parsed = parse(input, format, new Date());
if (!ts.isValidDateInstance(parsed)) {
throw new Error('Cannot parse date');
}
return parsed;
}
/**
* Will use date-fns parse against the input and return a date object
*
* @example
*
* const result = FieldTransform.parseDate('2020-01-10-00:00', {}, { format: 'yyyy-MM-ddxxx' })
* result === new Date('2020-01-10T00:00:00.000Z');
*
* const result = FieldTransform.parseDate('Jan 10, 2020-00:00', {}, { format: 'MMM dd, yyyyxxx' })
* result === new Date('2020-01-10T00:00:00.000Z');
*
* const result = FieldTransform.parseDate(1581025950223, {}, { format: 'T' })
* result === new Date('2020-02-06T21:52:30.223Z');
*
* const result = FieldTransform.parseDate(1581025950, {}, { format: 't' })
* result === new Date('2020-02-06T21:52:30.000Z');
*
* const result = FieldTransform.parseDate('1581025950', {} { format: 't' })
* result === new Date('2020-02-06T21:52:30.000Z');
*
* @param {*} input
* @param { format: string } args
* @returns { Date | Date[] | null } returns null if input is null/undefined
*/
export function parseDate(
input: unknown, _parentContext: unknown, args: ParseDateConfig
): Date|(Date|null)[]|null {
if (ts.isNil(input)) return null;
if (isArray(input)) {
return input
.filter(ts.isNotNil)
.map((data: any) => _parseDate(data, args));
}
return _parseDate(input, args);
}
/**
* Will convert a string, or an array of strings to camel case;
*
* @example
* FieldTransform.toCamelCase('I need camel case'); // 'iNeedCamelCase';
* FieldTransform.toCamelCase('happyBirthday'); // 'happyBirthday';
* FieldTransform.toCamelCase('what_is_this'); // 'whatIsThis';
*
* const array = ['what_is_this', 'I need camel case'];
* FieldTransform.toCamelCase(array); // ['whatIsThis', 'iNeedCamelCase'];
*
* @param {string | string[]} input
* @returns { string | string[] | null } returns null if input is null/undefined
*/
export function toCamelCase(
input: string, _parentContext?: unknown
): string|string[]|null {
if (ts.isNil(input)) return null;
if (isArray(input)) return input.filter(ts.isNotNil).map(ts.toCamelCase);
return ts.toCamelCase(input);
}
/**
* Will convert a string, or an array of strings to kebab case
* @example
*
* FieldTransform.toKebabCase('I need kebab case'); // 'i-need-kebab-case';
* FieldTransform.toKebabCase('happyBirthday'); // 'happy-birthday';
* FieldTransform.toKebabCase('what_is_this'); // 'what-is-this';
* FieldTransform.toKebabCase('this-should-be-kebab'); // 'this-should-be-kebab';
*
* const array = ['happyBirthday', 'what_is_this']
* FieldTransform.toKebabCase(array); // ['happy-birthday', 'what-is-this'];
*
* @param {string | string[]} input
* @returns { string | string[] | null } returns null if input is null/undefined
*/
export function toKebabCase(
input: string, _parentContext?: unknown
): string|string[]|null {
if (ts.isNil(input)) return null;
if (isArray(input)) return input.filter(ts.isNotNil).map(ts.toKebabCase);
return ts.toKebabCase(input);
}
/**
* Converts a string, or an array of strings to pascal case
*
* @example
* FieldTransform.toPascalCase('I need pascal case'); // 'INeedPascalCase';
* FieldTransform.toPascalCase('happyBirthday'); // 'HappyBirthday';
* FieldTransform.toPascalCase('what_is_this'); // 'WhatIsThis';
*
* const array = ['happyBirthday', 'what_is_this']
* FieldTransform.toKebabCase(array); // ['HappyBirthday', 'WhatIsThis'];
*
* @param {string | string[]} input
* @returns { string | string[] | null } returns null if input is null/undefined
*/
export function toPascalCase(input: string, _parentContext?: unknown): string|string[]|null {
if (ts.isNil(input)) return null;
if (isArray(input)) return input.filter(ts.isNotNil).map(ts.toPascalCase);
return ts.toPascalCase(input);
}
/**
* Converts a string, or an array of strings to snake case
* @example
* FieldTransform.toSnakeCase('I need snake case'); // 'i_need_snake_case';
* FieldTransform.toSnakeCase('happyBirthday'); // 'happy_birthday';
* FieldTransform.toSnakeCase('what_is_this'); // 'what_is_this';
*
* const array = ['happyBirthday', 'what_is_this']
* FieldTransform.toKebabCase(array); // ['happy_birthday', 'what_is_this'];
*
* @param {string | string[]} input
* @returns { string | string[] | null } returns null if input is null/undefined
*/
export function toSnakeCase(input: string, _parentContext?: unknown): string|string[]|null {
if (ts.isNil(input)) return null;
if (isArray(input)) return input.filter(ts.isNotNil).map(ts.toSnakeCase);
return ts.toSnakeCase(input);
}
/**
* Converts a string, or an array of strings to title case
* @example
* FieldTransform.toTitleCase('I need some capitols'); // 'I Need Some Capitols';
* FieldTransform.toTitleCase('happyBirthday'); // 'Happy Birthday';
* FieldTransform.toTitleCase('what_is_this'); // 'What Is This';
*
* @param {string | string[]} input
* @returns { string | string[] | null } returns null if input is null/undefined
*/
export function toTitleCase(input: string, _parentContext?: unknown): string|string[]|null {
if (ts.isNil(input)) return null;
if (isArray(input)) return input.filter(ts.isNotNil).map(ts.toTitleCase);
return ts.toTitleCase(input);
} | the_stack |
import { Component, OnInit, Inject, Input, OnDestroy, OnChanges, SimpleChanges, Output, EventEmitter, HostListener, AfterViewInit } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { environment } from './../../../../environments/environment';
import { LoggerService } from '../../../shared/services/logger.service';
import { AssetGroupObservableService } from '../../../core/services/asset-group-observable.service';
import { HttpService } from '../../../shared/services/http-response.service';
import { UtilsService } from '../../../shared/services/utils.service';
import { CommonResponseService } from '../../../shared/services/common-response.service';
@Component({
selector: 'app-vuln-report-distribution',
templateUrl: './vuln-report-distribution.component.html',
styleUrls: ['./vuln-report-distribution.component.css']
})
export class VulnReportDistributionComponent implements OnInit, OnChanges, OnDestroy, AfterViewInit {
selectedAssetGroup: string;
private errorMessage = 'apiResponseError';
private InfraDataSubscription: Subscription;
private EnvDataSubscription: Subscription;
private VulnTypeDataSubscription: Subscription;
private subscriptionToAssetGroup: Subscription;
private failureOccurred = 0;
public responseReceived = 0;
private donutData = {};
widgetWidth;
widgetHeight;
MainTextcolor = '#000';
innerRadious: any = 80;
outerRadious: any = 50;
strokeColor = '#fff';
index = 0;
distributionArray = [];
@Input() filter: any;
currentFilters = '3,4,5';
@Output() emitFailureError = new EventEmitter();
constructor(
private assetGroupObservableService: AssetGroupObservableService,
private logger: LoggerService,
private utilsService: UtilsService,
private commonResponseService: CommonResponseService,
@Inject(HttpService) private httpService: HttpService) {
this.subscriptionToAssetGroup = this.assetGroupObservableService.getAssetGroup().subscribe(
assetGroupName => {
this.selectedAssetGroup = assetGroupName;
this.updateComponent();
});
}
@HostListener('window:resize', ['$event']) onResize(event) {
this.setWidthForDonutChart();
}
ngOnInit() {
}
ngAfterViewInit() {
this.setWidthForDonutChart();
}
ngOnChanges(changes: SimpleChanges) {
try {
const filterChange = changes['filter'];
if (filterChange && filterChange.currentValue) {
this.currentFilters = filterChange.currentValue.severity;
const cur = JSON.stringify(filterChange.currentValue);
const prev = JSON.stringify(filterChange.previousValue);
if (cur !== prev && !filterChange.firstChange) {
this.updateComponent();
}
}
} catch (error) {
this.logger.log('error', error);
}
}
updateComponent() {
try {
if (this.VulnTypeDataSubscription) {
this.VulnTypeDataSubscription.unsubscribe();
}
if (this.InfraDataSubscription) {
this.InfraDataSubscription.unsubscribe();
}
if (this.EnvDataSubscription) {
this.EnvDataSubscription.unsubscribe();
}
this.donutData = {};
this.failureOccurred = 0;
this.responseReceived = 0;
this.distributionArray = [];
this.index = 0;
// function call to apis of each donut
this.getVulnTypeData();
this.getInfraData();
this.getEnvData();
} catch (e) {
this.logger.log('error', e);
}
}
getInfraData() {
const payload = {};
const queryParam = {
'ag': this.selectedAssetGroup,
'severity': this.currentFilters
};
const url = environment.VulnerabilitiesDistributionInfra.url;
const method = environment.VulnerabilitiesDistributionInfra.method;
this.InfraDataSubscription = this.commonResponseService.getData(url, method, payload, queryParam).subscribe(
response => {
try {
this.responseReceived++;
if (this.utilsService.checkIfAPIReturnedDataIsEmpty(response.distribution)) {
this.errorMessage = 'vulnerabilityMessage';
this.failureOccurred++;
if (this.failureOccurred === 3) {
this.emitFailureError.emit();
}
} else {
// order for displaying donut
const order = 2;
const category = ['Cloud', 'On-Prem'];
this.processGraphData(response.distribution, category, order);
}
} catch (e) {
this.errorMessage = 'jsError';
this.logger.log('error', e);
this.failureOccurred++;
if (this.failureOccurred === 3) {
this.emitFailureError.emit();
}
}
},
error => {
this.responseReceived++;
this.errorMessage = 'apiResponseError';
this.logger.log('error', error);
this.failureOccurred++;
if (this.failureOccurred === 3) {
this.emitFailureError.emit();
}
});
}
getEnvData() {
const payload = {};
const queryParam = {
'ag': this.selectedAssetGroup,
'severity': this.currentFilters
};
const url = environment.VulnerabilitiesDistributionEnv.url;
const method = environment.VulnerabilitiesDistributionEnv.method;
this.EnvDataSubscription = this.commonResponseService.getData(url, method, payload, queryParam).subscribe(
response => {
try {
this.responseReceived++;
if (this.utilsService.checkIfAPIReturnedDataIsEmpty(response.distribution)) {
this.errorMessage = 'vulnerabilityMessage';
this.failureOccurred++;
if (this.failureOccurred === 3) {
this.emitFailureError.emit();
}
} else {
// order for displaying donut
const order = 3;
const category = ['Prod', 'Non-Prod'];
this.processGraphData(response.distribution, category, order);
}
} catch (e) {
this.errorMessage = 'jsError';
this.logger.log('error', e);
this.failureOccurred++;
if (this.failureOccurred === 3) {
this.emitFailureError.emit();
}
}
},
error => {
this.responseReceived++;
this.errorMessage = 'apiResponseError';
this.logger.log('error', error);
this.failureOccurred++;
if (this.failureOccurred === 3) {
this.emitFailureError.emit();
}
});
}
getVulnTypeData() {
const payload = {};
const queryParam = {
'ag': this.selectedAssetGroup,
'severity': this.currentFilters
};
const url = environment.VulnerabilitiesDistributionVulnType.url;
const method = environment.VulnerabilitiesDistributionVulnType.method;
this.VulnTypeDataSubscription = this.commonResponseService.getData(url, method, payload, queryParam).subscribe(
response => {
try {
this.responseReceived++;
if (this.utilsService.checkIfAPIReturnedDataIsEmpty(response.distribution)) {
this.errorMessage = 'vulnerabilityMessage';
this.failureOccurred++;
if (this.failureOccurred === 3) {
this.emitFailureError.emit();
}
} else {
// order for displaying donut
const order = 1;
const category = ['OS', 'Application'];
this.processGraphData(response.distribution, category, order);
}
} catch (e) {
this.errorMessage = 'jsError';
this.logger.log('error', e);
this.failureOccurred++;
if (this.failureOccurred === 3) {
this.emitFailureError.emit();
}
}
},
error => {
this.responseReceived++;
this.errorMessage = 'apiResponseError';
this.logger.log('error', error);
this.failureOccurred++;
if (this.failureOccurred === 3) {
this.emitFailureError.emit();
}
});
}
processGraphData(data, categoryArray, order) {
try {
// check if data available for both categories. if not, add another with zero percent.
if (data.length === 1) {
const zeroContributionObj = {
'contribution': 0,
'totalVulnerableAssets': 0,
'uniqueVulnCount': 0,
'vulnerabilities': 0
};
if (categoryArray.includes(data[0].category)) {
if (data[0].category === categoryArray[0]) {
Object.assign(zeroContributionObj, {'category': categoryArray[1]} );
} else {
Object.assign(zeroContributionObj, {'category': categoryArray[0]} );
}
}
data.push(zeroContributionObj);
}
// color Obj for all donut
const donutColor = {
'OS': ['#645EC5 ', '#D0CEED'], /* Previous colors: 'OS': ['#ffb00d', '#f2cd80'],*/
'Cloud': ['#289cf7', '#bee1fc'],
'Prod': ['#aee6df', '#26ba9d']
};
// dataobj is the format of data expected by donut chart
const dataValue = [data[0].contribution, data[1].contribution];
const legendText = [data[0].category, data[1].category];
const dataObj = {
'color': donutColor[categoryArray[0]],
'data': dataValue,
'legendText' : legendText,
'legendTextcolor': '#000',
'centerText' : data[0].category + ' vs. ' + data[1].category,
'link': false,
'styling': {
'cursor': 'text'
}
};
// storing the final data in donutData variable to pass it to the donut chart component
this.donutData = dataObj;
// appending donutData obj to response data array received
data.push(this.donutData);
const eachDonutObj = {};
Object.assign(eachDonutObj, {'data': data});
Object.assign(eachDonutObj, {'order': order});
// Pushing data of each donut to common distributionArray.
this.distributionArray.push(eachDonutObj);
} catch (error) {
this.logger.log('error', error);
}
}
setWidthForDonutChart() {
const wrapperElement: any = document.getElementsByClassName('vuln-distribution-wrapper')[0];
if (wrapperElement) {
const donutElement: any = wrapperElement.clientWidth / 3;
let donutWidth = donutElement / 2.5;
if (donutWidth > 250) {
donutWidth = 250;
}
this.widgetWidth = donutWidth;
this.widgetHeight = this.widgetWidth;
} else {
this.widgetWidth = 140;
this.widgetHeight = this.widgetWidth;
}
}
ngOnDestroy() {
try {
if (this.subscriptionToAssetGroup) {
this.subscriptionToAssetGroup.unsubscribe();
}
if (this.VulnTypeDataSubscription) {
this.VulnTypeDataSubscription.unsubscribe();
}
if (this.InfraDataSubscription) {
this.InfraDataSubscription.unsubscribe();
}
if (this.EnvDataSubscription) {
this.EnvDataSubscription.unsubscribe();
}
} catch (error) {
this.logger.log('error', '--- Error while unsubscribing ---');
}
}
} | the_stack |
import {
AccessKeyedExpression,
AccessMemberExpression,
AccessScopeExpression,
AnyBindingExpression,
BinaryExpression,
BindingBehaviorExpression,
CallMemberExpression,
CallScopeExpression,
ConditionalExpression,
ExpressionKind,
ExpressionType,
ForOfStatement,
Interpolation,
IsAssign,
IsExpression,
ObjectLiteralExpression,
parseExpression,
PrimitiveLiteralExpression,
TemplateExpression,
UnaryExpression,
ValueConverterExpression,
} from '../@aurelia-runtime-patch/src';
import '@aurelia/metadata';
import {
ArrayLiteralExpression,
SourceCodeLocation,
} from '../@aurelia-runtime-patch/src/binding/ast';
type Writeable<T> = { -readonly [P in keyof T]: T[P] };
/* prettier-ignore */
export type KindToActualExpression<TargetKind extends ExpressionKind> =
TargetKind extends ExpressionKind.AccessKeyed ? AccessKeyedExpression :
TargetKind extends ExpressionKind.AccessScope ? AccessScopeExpression :
TargetKind extends ExpressionKind.AccessMember ? AccessMemberExpression :
TargetKind extends ExpressionKind.CallScope ? CallScopeExpression :
TargetKind extends ExpressionKind.CallMember ? CallMemberExpression :
TargetKind extends ExpressionKind.PrimitiveLiteral ? PrimitiveLiteralExpression :
TargetKind extends ExpressionKind.ValueConverter ? ValueConverterExpression :
TargetKind extends ExpressionKind.Conditional ? ConditionalExpression :
TargetKind extends ExpressionKind.Unary ? UnaryExpression :
TargetKind extends ExpressionKind.ForOfStatement ? ForOfStatement :
TargetKind extends ExpressionKind.ArrayLiteral ? ArrayLiteralExpression :
TargetKind extends ExpressionKind.ObjectLiteral ? ObjectLiteralExpression :
never;
export enum ExpressionKind_Dev {
CallsFunction = 0b0000000000100_00000, // Calls a function (CallFunction, CallScope, CallMember, TaggedTemplate) -> needs a valid function object returning from its lefthandside's evaluate()
HasAncestor = 0b0000000001000_00000, // Has an "ancestor" property, meaning the expression could climb up the context (only AccessThis, AccessScope and CallScope)
IsPrimary = 0b0000000010000_00000, // Is a primary expression according to ES parsing rules
IsLeftHandSide = 0b0000000100000_00000, // Is a left-hand side expression according to ES parsing rules, includes IsPrimary
HasBind = 0b0000001000000_00000, // Has a bind() method (currently only BindingBehavior)
HasUnbind = 0b0000010000000_00000, // Has an unbind() method (currentl only BindingBehavior and ValueConverter)
IsAssignable = 0b0000100000000_00000, // Is an assignable expression according to ES parsing rules (only AccessScope, AccessMember, AccessKeyed ans Assign)
IsLiteral = 0b0001000000000_00000, // Is literal expression (Primitive, Array, Object or Template)
IsResource = 0b0010000000000_00000, // Is an Aurelia resource (ValueConverter or BindingBehavior)
IsForDeclaration = 0b0100000000000_00000, // Is a For declaration (for..of, for..in -> currently only ForOfStatement)
Type = 0b0000000000000_11111, // Type mask to uniquely identify each AST class (concrete types start below)
// ---------------------------------------------------------------------------------------------------------------------------
AccessThis = 0b0000000111000_00001, // HasAncestor
AccessScope = 0b0000100111011_00010, // IsAssignable HasAncestor
ArrayLiteral = 0b0001000110001_00011, //
ObjectLiteral = 0b0001000110001_00100, //
PrimitiveLiteral = 0b0001000110000_00101, //
Template = 0b0001000110001_00110, //
Unary = 0b0000000000001_00111, //
CallScope = 0b0000000101101_01000, // HasAncestor CallsFunction
CallMember = 0b0000000100100_01001, // CallsFunction
CallFunction = 0b0000000100100_01010, // CallsFunction
AccessMember = 0b0000100100011_01011, // IsAssignable
AccessKeyed = 0b0000100100011_01100, // IsAssignable
TaggedTemplate = 0b0000000100101_01101, // CallsFunction
Binary = 0b0000000000001_01110, //
Conditional = 0b0000000000001_11111, //
Assign = 0b0000100000000_10000, // IsAssignable
ValueConverter = 0b0010010000001_10001, //
BindingBehavior = 0b0010011000001_10010, //
HtmlLiteral = 0b0000000000001_10011, //
ArrayBindingPattern = 0b0100000000000_10100, //
ObjectBindingPattern = 0b0100000000000_10101, //
BindingIdentifier = 0b0100000000000_10110, //
ForOfStatement = 0b0000011000001_10111, //
Interpolation = 0b0000000000000_11000, //
ArrayDestructuring = 0b0101100000000_11001, // IsAssignable
ObjectDestructuring = 0b0110100000000_11001, // IsAssignable
DestructuringAssignmentLeaf = 0b1000100000000_11001, // IsAssignable
}
export interface ExpressionsOfKindOptions {
expressionType?: ExpressionType;
/**
* Flatten eg. AccessScope inside CallScope.
* Instead of
* CallScopeExpression {
* name: 'hello',
* args: [ AccessScopeExpression { name: 'what', ancestor: 0 } ],
* ancestor: 0
* }
* We get
* AccessScopeExpression { name: 'what', ancestor: 0 },
* CallScopeExpression {
* name: 'hello',
* args: [ AccessScopeExpression { name: 'what', ancestor: 0 } ],
* ancestor: 0
* }
*
* @example
* Try with: `${repos | sort:direction.value:hello(what) | take:10}`
*/
flatten?: boolean;
/**
* To be added to expression parsers location
*/
startOffset: number;
}
export interface ExpressionsOfKindOptions_ForceInterpolation
extends ExpressionsOfKindOptions {
expressionType?: ExpressionType.Interpolation;
}
export class ParseExpressionUtil {
/**
* V2: pass input (parsing internal)
* V1: pass parsed (parsing external)
*/
public static getAllExpressionsOfKindV2<
TargetKind extends ExpressionKind,
TargetExpression extends KindToActualExpression<TargetKind>
>(
input: string,
targetKinds: TargetKind[],
options?: ExpressionsOfKindOptions
): { expressions: TargetExpression[]; parts?: readonly string[] } {
// /* prettier-ignore */ console.log('----------------------------------------')
let finalExpressions: TargetExpression[] = [];
if (input.trim() === '') return { expressions: [] };
let parsed: ReturnType<typeof parseExpression> | undefined;
try {
parsed = parseExpression(
input,
{
expressionType: options?.expressionType ?? ExpressionType.None,
startOffset: options?.startOffset ?? 0,
isInterpolation:
options?.expressionType === ExpressionType.Interpolation,
}
// options?.expressionType ?? ExpressionType.None,
) as unknown as Interpolation;
// parsed; /* ? */
if (parsed === null) {
finalExpressions = [];
}
// Interpolation
else if (parsed instanceof Interpolation) {
// if (parsed) {
// parsed.parts; /* ? */
// // parsed.expressions /* ? */
// JSON.stringify(parsed.expressions, null, 4); /* ? */
// }
parsed.expressions.forEach((expression) => {
// ExpressionKind_Dev[expression.$kind]; /*?*/
// expression; /*?*/
// console.log('vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv');
findAllExpressionRecursive(
expression,
targetKinds,
finalExpressions,
options
);
});
/*
* CONSIDER: Does this make sense for AccessMember?
* Eg. for `foo.bar.qux` we return [..."bar", ..."qux"]
*/
if (finalExpressions[0] instanceof AccessMemberExpression) {
finalExpressions = finalExpressions.reverse();
}
}
// None
else {
// parsed; /* ? */
// JSON.stringify(parsed, null, 4); /* ? */
findAllExpressionRecursive(
parsed,
targetKinds,
finalExpressions,
options
);
}
} catch (_error) {
// const _error = error as Error
// logger.log(_error.message,{logLevel:'DEBUG'})
// logger.log(_error.stack,{logLevel:'DEBUG'})
}
finalExpressions = sortExpressions<TargetExpression>(finalExpressions);
const finalReturn = {
expressions: finalExpressions,
parts: parsed instanceof Interpolation ? parsed.parts : undefined,
};
return finalReturn;
}
public static getAllExpressionsOfKind<
TargetKind extends ExpressionKind,
ReturnType extends KindToActualExpression<TargetKind>
>(
parsed: Interpolation,
targetKinds: TargetKind[],
options?: ExpressionsOfKindOptions
): ReturnType[] {
let finalExpressions: ReturnType[] = [];
// Interpolation
if (parsed instanceof Interpolation) {
parsed.expressions.forEach((expression) => {
// ExpressionKind_Dev[expression.$kind]; /*?*/
// expression; /*?*/
// console.log('vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv');
findAllExpressionRecursive(
expression,
targetKinds,
finalExpressions,
options
);
});
/*
* CONSIDER: Does this make sense for AccessMember?
* Eg. for `foo.bar.qux` we return [..."bar", ..."qux"]
*/
if (finalExpressions[0] instanceof AccessMemberExpression) {
finalExpressions = finalExpressions.reverse();
}
}
// None
else {
findAllExpressionRecursive(
parsed,
targetKinds,
finalExpressions,
options
);
}
return finalExpressions;
}
public static parseInterpolation(input: string, startOffset: number) {
if (input.trim() === '') return;
try {
const parsed = parseExpression(input, {
expressionType: ExpressionType.Interpolation,
startOffset: startOffset ?? 0,
isInterpolation: true,
});
return parsed;
} catch (_error) {
const error = _error as Error;
console.log(error.message);
// console.log(error.stack);
}
}
public static getFirstExpressionByKind<
TargetKind extends ExpressionKind,
ReturnType extends KindToActualExpression<TargetKind>
>(parsed: IsExpression, targetKinds: TargetKind[]): ReturnType {
const finalExpressions = ParseExpressionUtil.getAllExpressionsOfKind<
TargetKind,
ReturnType
>(parsed as Interpolation, targetKinds);
const target = finalExpressions[0];
return target;
}
public static getAllExpressionsByName<TargetKind extends ExpressionKind>(
input: string,
targetName: string,
targetKinds: TargetKind[]
): KindToActualExpression<TargetKind>[] {
try {
const parsed = parseExpression(input) as unknown as Interpolation; // Cast because, pretty sure we only get Interpolation as return in our use cases
const accessScopes = ParseExpressionUtil.getAllExpressionsOfKind(
parsed,
targetKinds
);
const hasSourceWordInScope = accessScopes.filter((accessScope) => {
const isAccessOrCallScope =
accessScope.$kind === ExpressionKind.AccessScope ||
accessScope.$kind === ExpressionKind.CallScope;
if (isAccessOrCallScope) {
return accessScope.name === targetName;
}
return false;
});
return hasSourceWordInScope;
} catch (error) {
// const _error = error as Error
// logger.log(_error.message,{logLevel:'DEBUG'})
// logger.log(_error.stack,{logLevel:'DEBUG'})
// console.log(error);
return [];
}
}
}
export function findAllExpressionRecursive(
expressionOrList: AnyBindingExpression | AnyBindingExpression[],
targetKinds: ExpressionKind[],
collector: unknown[],
options?: ExpressionsOfKindOptions
) {
if (expressionOrList === undefined) {
return;
}
// expressionOrList /* ? */
// JSON.stringify(expressionOrList, null, 4); /* ? */
// .args
if (Array.isArray(expressionOrList)) {
const targetExpressions = expressionOrList.filter((expression) => {
const targetExpressionKind = isKindIncluded(
targetKinds,
expression.$kind
);
// Array can have children eg. AccessScopes
if (!targetExpressionKind) {
findAllExpressionRecursive(expression, targetKinds, collector, options);
}
// Special case, if we want CallScope AND AccessScope
else if (expression instanceof CallScopeExpression) {
findAllExpressionRecursive(
expression.args as Writeable<IsAssign[]>,
targetKinds,
collector,
options
);
}
return targetExpressionKind;
});
collector.push(...targetExpressions);
return;
}
// default rec return
const singleExpression = expressionOrList;
// if nothing to filter, return all
if (targetKinds.length === 0) {
collector.push(singleExpression);
}
// return targets only
else if (isKindIncluded(targetKinds, singleExpression.$kind)) {
collector.push(singleExpression);
}
// .ancestor
if (singleExpression instanceof AccessScopeExpression) {
return;
}
// .object .name
else if (singleExpression instanceof AccessMemberExpression) {
findAllExpressionRecursive(
singleExpression.object,
targetKinds,
collector,
options
);
return;
}
// .object
else if (singleExpression instanceof CallMemberExpression) {
findAllExpressionRecursive(
singleExpression.object,
targetKinds,
collector,
options
);
findAllExpressionRecursive(
singleExpression.args as Writeable<IsAssign[]>,
targetKinds,
collector,
options
);
return;
}
// .object .key
else if (singleExpression instanceof AccessKeyedExpression) {
findAllExpressionRecursive(
singleExpression.object,
targetKinds,
collector,
options
);
findAllExpressionRecursive(
singleExpression.key,
targetKinds,
collector,
options
);
return;
}
// .args
else if (singleExpression instanceof CallScopeExpression) {
findAllExpressionRecursive(
singleExpression.args as Writeable<IsAssign[]>,
targetKinds,
collector,
options
);
return;
}
// .value
else if (singleExpression instanceof PrimitiveLiteralExpression) {
return;
}
// .expression, .args
else if (singleExpression instanceof ValueConverterExpression) {
findAllExpressionRecursive(
singleExpression.expression,
targetKinds,
collector,
options
);
findAllExpressionRecursive(
singleExpression.args as Writeable<IsAssign[]>,
targetKinds,
collector,
options
);
return;
}
// .left, .right
else if (singleExpression instanceof BinaryExpression) {
findAllExpressionRecursive(
singleExpression.left,
targetKinds,
collector,
options
);
findAllExpressionRecursive(
singleExpression.right,
targetKinds,
collector,
options
);
return;
}
// .condition .yes .no
else if (singleExpression instanceof ConditionalExpression) {
findAllExpressionRecursive(
singleExpression.condition,
targetKinds,
collector,
options
);
findAllExpressionRecursive(
singleExpression.yes,
targetKinds,
collector,
options
);
findAllExpressionRecursive(
singleExpression.no,
targetKinds,
collector,
options
);
return;
}
// .expression (.operation)
else if (singleExpression instanceof UnaryExpression) {
findAllExpressionRecursive(
singleExpression.expression,
targetKinds,
collector,
options
);
return;
}
// .iterable
else if (singleExpression instanceof ForOfStatement) {
findAllExpressionRecursive(
singleExpression.iterable,
targetKinds,
collector,
options
);
return;
}
// .expression
else if (singleExpression instanceof BindingBehaviorExpression) {
// singleExpression.expression/*?*/
findAllExpressionRecursive(
singleExpression.expression,
targetKinds,
collector,
options
);
return;
}
// .expression
else if (singleExpression instanceof TemplateExpression) {
findAllExpressionRecursive(
singleExpression.expressions as Writeable<IsAssign[]>,
targetKinds,
collector,
options
);
return;
}
// .values
else if (singleExpression instanceof ObjectLiteralExpression) {
findAllExpressionRecursive(
singleExpression.values as Writeable<IsAssign[]>,
targetKinds,
collector,
options
);
return;
} else if (singleExpression instanceof ArrayLiteralExpression) {
findAllExpressionRecursive(
singleExpression.elements as Writeable<IsAssign[]>,
targetKinds,
collector,
options
);
return;
}
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
singleExpression; /* ? */
/* prettier-ignore */ throw new Error(`Unconsumed. Was: '${ExpressionKind_Dev[expressionOrList.$kind]}'`);
}
function isKindIncluded(
queriedKinds: ExpressionKind[],
targetKind: ExpressionKind
) {
const isKind = queriedKinds.find((queriedKind) => {
return ExpressionKind_Dev[queriedKind] === ExpressionKind_Dev[targetKind];
});
return isKind;
}
function sortExpressions<T>(finalExpressions: T[]): T[] {
const sorted = finalExpressions.sort((rawExpressionA, rawExpressionB) => {
const expressionA = rawExpressionA as unknown as {
nameLocation: SourceCodeLocation;
};
const expressionB = rawExpressionB as unknown as {
nameLocation: SourceCodeLocation;
};
const sortedCheck =
expressionA.nameLocation.start - expressionB.nameLocation.start;
return sortedCheck;
});
return sorted;
}
// const input = '${repos || hello | sort:direction.value:hello(what) | take:10}';
// const parsed = parseExpression(input /*?*/, ExpressionType.Interpolation);
// const accessScopes = ParseExpressionUtil.getAllExpressionsOfKind(parsed, [
// ExpressionKind.AccessScope,
// ExpressionKind.CallScope,
// ExpressionKind.ValueConverter,
// ]);
// // accessScopes; /*?*/
// const [initiatorText, ...valueConverterRegionsSplit] = input.split(
// /(?<!\|)\|(?!\|)/g
// );/*?*/ | the_stack |
import { tick } from 'svelte';
import Select from '../Select.svelte';
const items = [
{ id: 'au', text: 'Australia' },
{ id: 'cn', text: 'China' },
{ id: 'jp', text: 'Japan' },
{ id: 'kr', text: 'Korea' },
{ id: 'other', text: 'Other / Unknown' },
];
/* eslint-disable sort-keys */
const itemsDisabled = [
{ id: '0', text: 'Zero', disabled: true },
{ id: '1', text: 'One' },
{ id: '2', text: 'Two', disabled: true },
{ id: '3', text: 'Three' },
{ id: '4', text: 'Four', disabled: true },
{ id: '5', text: 'Five', disabled: true },
{ id: '6', text: 'Six', disabled: true },
{ id: '7', text: 'Seven' },
{ id: '8', text: 'Eight', disabled: true },
{ id: '9', text: 'Nine', disabled: true },
];
/* eslint-enable sort-keys */
const selectOpts = {
id: 'test-select',
items,
value: '',
};
describe('Select component', () => {
it('has default props set correctly', () => {
expect.assertions(7);
const target = document.createElement('div');
const component = new Select({
props: { items: [] },
target,
});
expect(component.disabled).toBe(false);
expect(component.filterable).toBe(true);
expect(component.filterHelp).toBe('Filter...');
expect(component.isOpen).toBe(false);
expect(component.placeholder).toBe('Choose...');
expect(component.id).toBeUndefined();
expect(component.value).toBeUndefined();
});
it('renders correctly with required props set', () => {
expect.assertions(8);
const target = document.createElement('div');
const component = new Select({
props: selectOpts,
target,
});
const select = target.querySelector('.select')!;
expect(Array.isArray(component.items)).toBe(true);
expect(component.items).not.toHaveLength(0);
expect(select.getAttribute('tabindex')).toBe('0');
expect(select.getAttribute('disabled')).toBeNull();
expect(select.getAttribute('placeholder')).not.toBe(false);
expect(document.querySelector('select-active')).toBeNull();
expect(document.querySelector('select-disabled')).toBeNull();
expect(target.innerHTML).toMatchSnapshot();
});
it("doesn't log errors or warnings with required props", () => {
expect.assertions(2);
const spy1 = jest.spyOn(console, 'error');
const spy2 = jest.spyOn(console, 'warn');
const target = document.createElement('div');
new Select({
props: selectOpts,
target,
});
expect(spy1).not.toHaveBeenCalled();
expect(spy2).not.toHaveBeenCalled();
spy1.mockRestore();
spy2.mockRestore();
});
it('renders with value prop set', () => {
expect.assertions(2);
const target = document.createElement('div');
new Select({
props: {
...selectOpts,
value: 'jp',
},
target,
});
const active = target.querySelector('.option-active')!;
expect(active.getAttribute('value')).toBe('jp');
expect(target.innerHTML).toMatchSnapshot();
});
it('renders with filterable prop set to false', () => {
expect.assertions(3);
const target = document.createElement('div');
const component = new Select({
props: {
...selectOpts,
filterable: false,
isOpen: true,
},
target,
});
expect(component.filterable).toBe(false);
const select = target.querySelector('.select')!;
expect(select.getAttribute('placeholder')).toBe('Choose...'); // not "Filer..."
expect(target.innerHTML).toMatchSnapshot();
});
it('renders with filterHelp prop', () => {
expect.assertions(3);
const target = document.createElement('div');
const component = new Select({
props: {
...selectOpts,
filterHelp: 'Filter me',
isOpen: true,
},
target,
});
expect(component.filterHelp).toBe('Filter me');
const select = target.querySelector('.select')!;
expect(select.getAttribute('placeholder')).toBe('Filter me');
expect(target.innerHTML).toMatchSnapshot();
});
it('renders with placeholder prop', () => {
expect.assertions(3);
const target = document.createElement('div');
const component = new Select({
props: {
...selectOpts,
placeholder: 'Hold your places',
},
target,
});
expect(component.placeholder).toBe('Hold your places');
const select = target.querySelector('.select')!;
expect(select.getAttribute('placeholder')).toBe('Hold your places');
expect(target.innerHTML).toMatchSnapshot();
});
it('renders with disabled prop', () => {
expect.assertions(5);
const target = document.createElement('div');
const component = new Select({
props: {
...selectOpts,
disabled: true,
},
target,
});
expect(component.disabled).toBe(true);
const select = target.querySelector('.select')!;
expect(select.getAttribute('disabled')).not.toBeNull();
expect(select.getAttribute('tabindex')).toBe('-1');
expect(target.querySelector('.select-disabled')).not.toBeNull();
expect(target.innerHTML).toMatchSnapshot();
});
it('updates selected item on value change', async () => {
expect.assertions(2);
const target = document.createElement('div');
const component = new Select({
props: {
...selectOpts,
value: 'cn',
},
target,
});
const active1 = target.querySelector('.option-active')!;
expect(active1.getAttribute('value')).toBe('cn');
component.value = 'kr';
const select = target.querySelector<HTMLSelectElement>('.select')!;
select.click(); // To set correct selected index
await tick();
const active2 = target.querySelector('.option-active')!;
expect(active2.getAttribute('value')).toBe('kr');
});
it('shows on click', async () => {
expect.assertions(2);
const target = document.createElement('div');
const component = new Select({
props: selectOpts,
target,
});
const select = target.querySelector<HTMLInputElement>('.select')!;
expect(component.isOpen).toBe(false);
select.click();
await tick();
expect(component.isOpen).toBe(true);
});
it('does not show on click when disabled', async () => {
expect.assertions(2);
const target = document.createElement('div');
const component = new Select({
props: {
...selectOpts,
disabled: true,
},
target,
});
const select = target.querySelector<HTMLInputElement>('.select')!;
expect(component.isOpen).toBe(false);
select.click();
await tick();
expect(component.isOpen).toBe(false);
});
it('shows on enter key press', () => {
expect.assertions(2);
const target = document.createElement('div');
const component = new Select({
props: selectOpts,
target,
});
expect(component.isOpen).toBe(false);
const select = target.querySelector('.select')!;
const event = new KeyboardEvent('keydown', { key: 'Enter' });
select.dispatchEvent(event);
expect(component.isOpen).toBe(true);
});
it('shows on spacebar key press', () => {
expect.assertions(3);
const target = document.createElement('div');
const component = new Select({
props: selectOpts,
target,
});
expect(component.isOpen).toBe(false);
const select = target.querySelector('.select')!;
const event1 = new KeyboardEvent('keydown', { key: ' ' }); // spacebar
select.dispatchEvent(event1);
expect(component.isOpen).toBe(true);
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore - keyCode does actually exist!
const event2 = new KeyboardEvent('keydown', { keyCode: 32 });
select.dispatchEvent(event2);
expect(component.isOpen).toBe(true);
});
it('shows on down key press', () => {
expect.assertions(2);
const target = document.createElement('div');
const component = new Select({
props: selectOpts,
target,
});
expect(component.isOpen).toBe(false);
const select = target.querySelector('.select')!;
const event = new KeyboardEvent('keydown', { key: 'ArrowDown' });
select.dispatchEvent(event);
expect(component.isOpen).toBe(true);
});
it('shows on up key press', () => {
expect.assertions(2);
const target = document.createElement('div');
const component = new Select({
props: selectOpts,
target,
});
expect(component.isOpen).toBe(false);
const select = target.querySelector('.select')!;
const event = new KeyboardEvent('keydown', { key: 'ArrowUp' });
select.dispatchEvent(event);
expect(component.isOpen).toBe(true);
});
it('shows automatically on focus', () => {
expect.assertions(3);
const target = document.createElement('div');
document.body.appendChild(target);
const component = new Select({
props: selectOpts,
target,
});
expect(component.isOpen).toBe(false);
const select = target.querySelector<HTMLInputElement>('.select')!;
select.focus();
expect(component.isOpen).toBe(true);
expect(document.activeElement).toStrictEqual(select);
});
it('hides on click outside the component', () => {
expect.assertions(4);
const target = document.createElement('div');
document.body.appendChild(target);
const component = new Select({
props: selectOpts,
target,
});
const select = target.querySelector<HTMLInputElement>('.select')!;
select.focus();
expect(component.isOpen).toBe(true);
expect(document.activeElement).toStrictEqual(select);
select.blur();
expect(component.isOpen).toBe(false);
expect(document.activeElement).toStrictEqual(document.body);
});
it('hides on ESC key press', () => {
expect.assertions(2);
const target = document.createElement('div');
const component = new Select({
props: {
...selectOpts,
isOpen: true,
},
target,
});
expect(component.isOpen).toBe(true);
const select = target.querySelector('.select')!;
const event = new KeyboardEvent('keydown', { key: 'Escape' });
select.dispatchEvent(event);
expect(component.isOpen).toBe(false);
});
it('does nothing on invalid key press', () => {
expect.assertions(2);
const target = document.createElement('div');
const component = new Select({
props: selectOpts,
target,
});
expect(component.isOpen).toBe(false);
const select = target.querySelector('.select')!;
const event = new KeyboardEvent('keydown', { key: 'xxx' });
select.dispatchEvent(event);
expect(component.isOpen).toBe(false);
});
it('selects next item on down key press', () => {
expect.assertions(5);
const target = document.createElement('div');
const component = new Select({
props: {
...selectOpts,
isOpen: true,
selected: 0,
},
target,
});
expect(component.isOpen).toBe(true);
const active1 = target.querySelector('.option-active')!;
expect(active1.getAttribute('value')).toBe('au');
const select = target.querySelector('.select')!;
const event = new KeyboardEvent('keydown', { key: 'ArrowDown' });
select.dispatchEvent(event);
const active2 = target.querySelector('.option-active')!;
expect(active2.getAttribute('value')).toBe('au');
select.dispatchEvent(event);
const active3 = target.querySelector('.option-active')!;
expect(active3.getAttribute('value')).toBe('au');
expect(component.isOpen).toBe(true); // Still open
});
it('selects previous item on up key press', async () => {
expect.assertions(5);
const target = document.createElement('div');
const component = new Select({
props: {
...selectOpts,
value: items[2].id,
},
target,
});
const select = target.querySelector<HTMLSelectElement>('.select')!;
select.click(); // To set correct selected index
expect(component.isOpen).toBe(true);
const active1 = target.querySelector('.option-active')!;
expect(active1.getAttribute('value')).toBe('jp');
const event = new KeyboardEvent('keydown', { key: 'ArrowUp' });
select.dispatchEvent(event);
await tick();
const active2 = target.querySelector('.option-active')!;
expect(active2.getAttribute('value')).toBe('cn');
select.dispatchEvent(event);
await tick();
const active3 = target.querySelector('.option-active')!;
expect(active3.getAttribute('value')).toBe('au');
expect(component.isOpen).toBe(true); // Still open
});
it('skips over disabled items on down key press', async () => {
expect.assertions(5);
const target = document.createElement('div');
const component = new Select({
props: {
...selectOpts,
items: itemsDisabled,
value: itemsDisabled[1].id,
},
target,
});
const select = target.querySelector<HTMLSelectElement>('.select')!;
select.click(); // To set correct selected index
const active1 = target.querySelector('.option-active')!;
expect(active1.getAttribute('value')).toBe('1');
const event = new KeyboardEvent('keydown', { key: 'ArrowDown' });
select.dispatchEvent(event);
await tick();
const active2 = target.querySelector('.option-active')!;
expect(active2.getAttribute('value')).toBe('3');
select.dispatchEvent(event);
await tick();
const active3 = target.querySelector('.option-active')!;
expect(active3.getAttribute('value')).toBe('7');
select.dispatchEvent(event);
await tick();
const active4 = target.querySelector('.option-active')!;
expect(active4.getAttribute('value')).toBe('7');
expect(component.isOpen).toBe(true); // Still open
});
it('skips over disabled items on up key press', async () => {
expect.assertions(5);
const target = document.createElement('div');
const component = new Select({
props: {
...selectOpts,
items: itemsDisabled,
value: itemsDisabled[7].id,
},
target,
});
const select = target.querySelector<HTMLSelectElement>('.select')!;
select.click(); // To set correct selected index
const active1 = target.querySelector('.option-active')!;
expect(active1.getAttribute('value')).toBe('7');
const event = new KeyboardEvent('keydown', { key: 'ArrowUp' });
select.dispatchEvent(event);
await tick();
const active2 = target.querySelector('.option-active')!;
expect(active2.getAttribute('value')).toBe('3');
select.dispatchEvent(event);
await tick();
const active3 = target.querySelector('.option-active')!;
expect(active3.getAttribute('value')).toBe('1');
select.dispatchEvent(event);
await tick();
const active4 = target.querySelector('.option-active')!;
expect(active4.getAttribute('value')).toBe('1');
expect(component.isOpen).toBe(true); // Still open
});
it("doesn't go past end of items on down key press", async () => {
expect.assertions(4);
const target = document.createElement('div');
const component = new Select({
props: {
...selectOpts,
value: items[3].id,
},
target,
});
const select = target.querySelector<HTMLSelectElement>('.select')!;
select.click(); // To set correct selected index
const active1 = target.querySelector('.option-active')!;
expect(active1.getAttribute('value')).toBe('kr');
const event = new KeyboardEvent('keydown', { key: 'ArrowDown' });
select.dispatchEvent(event);
await tick();
const active2 = target.querySelector('.option-active')!;
expect(active2.getAttribute('value')).toBe('other');
select.dispatchEvent(event);
await tick();
const active3 = target.querySelector('.option-active')!;
expect(active3.getAttribute('value')).toBe('other');
expect(component.isOpen).toBe(true); // Still open
});
it("doesn't go past end of items on up key press", async () => {
expect.assertions(4);
const target = document.createElement('div');
const component = new Select({
props: {
...selectOpts,
value: items[1].id,
},
target,
});
const select = target.querySelector<HTMLSelectElement>('.select')!;
select.click(); // To set correct selected index
const active1 = target.querySelector('.option-active')!;
expect(active1.getAttribute('value')).toBe('cn');
const event = new KeyboardEvent('keydown', { key: 'ArrowUp' });
select.dispatchEvent(event);
await tick();
const active2 = target.querySelector('.option-active')!;
expect(active2.getAttribute('value')).toBe('au');
select.dispatchEvent(event);
await tick();
const active3 = target.querySelector('.option-active')!;
expect(active3.getAttribute('value')).toBe('au');
expect(component.isOpen).toBe(true); // Still open
});
it('selects an item on click', async () => {
expect.assertions(7);
const target = document.createElement('div');
const component = new Select({
props: {
...selectOpts,
isOpen: true,
},
target,
});
expect(component.isOpen).toBe(true);
const active1 = target.querySelector('.option-active')!;
expect(active1.getAttribute('value')).toBe('au');
const select = target.querySelector<HTMLSelectElement>('.select')!;
const option = target.querySelector('.option[value="jp"]');
const listbox = target.querySelector('.select-listbox')!;
const event = new MouseEvent('mousedown');
Object.defineProperty(event, 'target', { enumerable: true, value: option });
const spy1 = jest.spyOn(select, 'dispatchEvent');
const spy2 = jest.spyOn(event, 'preventDefault'); // Only present in mouse event part of select()
listbox.dispatchEvent(event);
expect(spy1).toHaveBeenCalledTimes(1);
expect(spy2).toHaveBeenCalledTimes(1);
expect(component.isOpen).toBe(false);
select.click(); // To set correct selected index
await tick();
const active2 = target.querySelector('.option-active')!;
expect(active2.getAttribute('value')).toBe('jp');
expect(component.isOpen).toBe(true);
spy1.mockRestore();
spy2.mockRestore();
});
it("doesn't select an item on click when option disabled", () => {
expect.assertions(6);
const target = document.createElement('div');
const component = new Select({
props: {
...selectOpts,
isOpen: true,
items: [
{ id: 'one', text: 'Opt 1' },
// eslint-disable-next-line sort-keys
{ id: 'two', text: 'Opt 2', disabled: true },
{ id: 'three', text: 'Opt 3' },
],
},
target,
});
expect(component.isOpen).toBe(true);
const active1 = target.querySelector('.option-active')!;
expect(active1.getAttribute('value')).toBe('one');
const select = target.querySelector('.select')!;
const option = target.querySelector('.option[value="two"]');
const listbox = target.querySelector('.select-listbox')!;
const spy1 = jest.spyOn(select, 'dispatchEvent');
const event = new MouseEvent('mousedown');
Object.defineProperty(event, 'target', { enumerable: true, value: option });
const spy2 = jest.spyOn(event, 'preventDefault');
listbox.dispatchEvent(event);
expect(spy1).not.toHaveBeenCalled(); // Doesn't emit an event
expect(spy2).toHaveBeenCalledTimes(1);
const active2 = target.querySelector('.option-active')!;
expect(active2.getAttribute('value')).toBe('one');
expect(component.isOpen).toBe(true); // Still open
spy1.mockRestore();
spy2.mockRestore();
});
it('selects item on enter key press', async () => {
expect.assertions(7);
const target = document.createElement('div');
const component = new Select({
props: {
...selectOpts,
isOpen: true,
},
target,
});
expect(component.isOpen).toBe(true);
const active1 = target.querySelector('.option-active')!;
expect(active1.getAttribute('value')).toBe('au');
const select = target.querySelector('.select')!;
const event1 = new KeyboardEvent('keydown', { key: 'ArrowDown' });
const spy1 = jest.spyOn(event1, 'preventDefault');
select.dispatchEvent(event1);
await tick();
const active2 = target.querySelector('.option-active')!;
expect(active2.getAttribute('value')).toBe('cn');
const event2 = new KeyboardEvent('keydown', { key: 'Enter' });
const spy2 = jest.spyOn(event2, 'preventDefault');
select.dispatchEvent(event2);
await tick();
expect(spy1).toHaveBeenCalledTimes(1);
expect(spy2).toHaveBeenCalledTimes(1);
const active3 = target.querySelector('.option-active')!;
expect(active3.getAttribute('value')).toBe('cn');
expect(component.isOpen).toBe(false);
spy1.mockRestore();
spy2.mockRestore();
});
it('typing in input filters the shown items', async () => {
expect.assertions(3);
const target = document.createElement('div');
new Select({
props: {
...selectOpts,
isOpen: true,
},
target,
});
const listbox1 = target.querySelector('.select-listbox')!;
expect(listbox1.childNodes).toHaveLength(5);
const select = target.querySelector<HTMLInputElement>('.select')!;
select.value = 'o'; // simulate input + event
const event = new Event('input');
select.dispatchEvent(event);
await tick();
const listbox2 = target.querySelector('.select-listbox')!;
expect(listbox2.childNodes).toHaveLength(2);
expect(listbox2.innerHTML).toMatchSnapshot();
});
it('shows feedback message when filter has no match', async () => {
expect.assertions(3);
const target = document.createElement('div');
new Select({
props: {
...selectOpts,
isOpen: true,
},
target,
});
const listbox1 = target.querySelector('.select-listbox')!;
expect(listbox1.childNodes).toHaveLength(5);
const select = target.querySelector<HTMLInputElement>('.select')!;
select.value = 'xxxxx'; // Simulate input + event
const event = new Event('input');
select.dispatchEvent(event);
await tick();
const listbox2 = target.querySelector('.select-listbox')!;
expect(listbox2.childNodes).toHaveLength(1);
expect(listbox2.innerHTML).toMatchSnapshot();
});
it('input is reset on ESC key press', async () => {
expect.assertions(4);
const target = document.createElement('div');
const component = new Select({
props: {
...selectOpts,
value: 'au',
},
target,
});
const select1 = target.querySelector<HTMLInputElement>('.select')!;
expect(select1.value).toBe('Australia');
select1.click();
await tick();
const select2 = target.querySelector<HTMLInputElement>('.select')!;
expect(select2.value).toBe('');
const event = new KeyboardEvent('keydown', { key: 'Escape' });
select2.dispatchEvent(event);
await tick();
expect(component.isOpen).toBe(false);
const select3 = target.querySelector<HTMLInputElement>('.select')!;
expect(select3.value).toBe('Australia');
});
it('can dynamically add items', async () => {
expect.assertions(4);
const target = document.createElement('div');
const component = new Select({
props: selectOpts,
target,
});
expect(component.items).toHaveLength(5);
component.$set({ items: [...items, { id: 'new', text: 'New' }] });
await tick();
expect(component.items).toHaveLength(6);
const newItem = target.querySelector('[value="new"]')!;
expect(newItem).toBeDefined();
expect(newItem.outerHTML).toMatchSnapshot();
});
}); | the_stack |
import React, { useMemo, useCallback, useEffect } from 'react';
import { bigNumberify } from 'ethers/utils';
import {
FormattedDateParts,
FormattedMessage,
defineMessages,
useIntl,
} from 'react-intl';
import { ColonyRoles } from '@colony/colony-js';
import { AddressZero } from 'ethers/constants';
import HookedUserAvatar from '~users/HookedUserAvatar';
import Numeral, { AbbreviatedNumeral } from '~core/Numeral';
import Icon from '~core/Icon';
import FriendlyName from '~core/FriendlyName';
import Tag, { Appearance as TagAppearance } from '~core/Tag';
import CountDownTimer from '~dashboard/ActionsPage/CountDownTimer';
import { getMainClasses, removeValueUnits } from '~utils/css';
import { getTokenDecimalsWithFallback } from '~utils/tokens';
import {
useUser,
Colony,
useColonyHistoricRolesQuery,
useTokenInfoLazyQuery,
} from '~data/index';
import { createAddress } from '~utils/web3';
import { FormattedAction, ColonyActions, ColonyMotions } from '~types/index';
import { useDataFetcher } from '~utils/hooks';
import { parseDomainMetadata } from '~utils/colonyActions';
import { useFormatRolesTitle } from '~utils/hooks/useFormatRolesTitle';
import { useEnabledExtensions } from '~utils/hooks/useEnabledExtensions';
import {
getUpdatedDecodedMotionRoles,
MotionState,
MOTION_TAG_MAP,
} from '~utils/colonyMotions';
import { ipfsDataFetcher } from '../../../core/fetchers';
import { ClickHandlerProps } from './ActionsList';
import styles, { popoverWidth, popoverDistance } from './ActionsListItem.css';
const displayName = 'ActionsList.ActionsListItem';
const UserAvatar = HookedUserAvatar();
const MSG = defineMessages({
domain: {
id: 'ActionsList.ActionsListItem.domain',
defaultMessage: 'Team {domainId}',
},
titleCommentCount: {
id: 'ActionsList.ActionsListItem.titleCommentCount',
defaultMessage: `{formattedCommentCount} {commentCount, plural,
one {comment}
other {comments}
}`,
},
});
export enum ItemStatus {
NeedAction = 'NeedAction',
NeedAttention = 'NeedAttention',
/*
* Default status, does not do anything
*/
Defused = 'Defused',
}
interface Props {
item: FormattedAction;
colony: Colony;
handleOnClick?: (handlerProps: ClickHandlerProps) => void;
}
const ActionsListItem = ({
item: {
id,
actionType,
initiator,
recipient,
amount,
symbol: colonyTokenSymbol,
decimals: colonyTokenDecimals,
fromDomain: fromDomainId,
toDomain: toDomainId,
transactionHash,
createdAt,
commentCount = 0,
metadata,
roles,
newVersion,
status = ItemStatus.Defused,
motionState,
motionId,
blockNumber,
totalNayStake,
requiredStake,
transactionTokenAddress,
},
colony,
handleOnClick,
}: Props) => {
const { formatMessage, formatNumber } = useIntl();
const { data: metadataJSON } = useDataFetcher(
ipfsDataFetcher,
[metadata as string],
[metadata],
);
const { isVotingExtensionEnabled } = useEnabledExtensions({
colonyAddress: colony.colonyAddress,
});
const { data: historicColonyRoles } = useColonyHistoricRolesQuery({
variables: {
colonyAddress: colony.colonyAddress,
blockNumber,
},
});
const [fetchTokenInfo, { data: tokenData }] = useTokenInfoLazyQuery();
useEffect(() => {
if (transactionTokenAddress) {
fetchTokenInfo({ variables: { address: transactionTokenAddress } });
}
}, [fetchTokenInfo, transactionTokenAddress]);
const initiatorUserProfile = useUser(createAddress(initiator || AddressZero));
const recipientAddress = createAddress(recipient);
const isColonyAddress = recipientAddress === colony.colonyAddress;
const fallbackRecipientProfile = useUser(
isColonyAddress ? '' : recipientAddress,
);
const fromDomain = colony.domains.find(
({ ethDomainId }) => ethDomainId === parseInt(fromDomainId, 10),
);
const toDomain = colony.domains.find(
({ ethDomainId }) => ethDomainId === parseInt(toDomainId, 10),
);
const updatedRoles = getUpdatedDecodedMotionRoles(
fallbackRecipientProfile,
parseInt(fromDomainId, 10),
(historicColonyRoles?.historicColonyRoles as unknown) as ColonyRoles,
roles || [],
);
const { roleMessageDescriptorId, roleTitle } = useFormatRolesTitle(
actionType === ColonyMotions.SetUserRolesMotion ? updatedRoles : roles,
actionType,
);
const popoverPlacement = useMemo(() => {
const offsetSkid = (-1 * removeValueUnits(popoverWidth)) / 2;
return [offsetSkid, removeValueUnits(popoverDistance)];
}, []);
const handleSyntheticEvent = useCallback(
() => handleOnClick && handleOnClick({ id, transactionHash }),
[handleOnClick, id, transactionHash],
);
const totalNayStakeValue = bigNumberify(totalNayStake || 0);
const isFullyNayStaked = totalNayStakeValue.gte(
bigNumberify(requiredStake || 0),
);
let domainName;
if (
metadataJSON &&
(actionType === ColonyActions.EditDomain ||
actionType === ColonyActions.CreateDomain ||
actionType === ColonyMotions.CreateDomainMotion)
) {
const domainObject = parseDomainMetadata(metadataJSON);
domainName = domainObject.domainName;
}
const motionStyles =
MOTION_TAG_MAP[
motionState ||
(isVotingExtensionEnabled &&
!actionType?.endsWith('Motion') &&
MotionState.Forced) ||
MotionState.Invalid
];
const decimals = tokenData?.tokenInfo?.decimals || colonyTokenDecimals;
const symbol = tokenData?.tokenInfo?.symbol || colonyTokenSymbol;
return (
<li>
<div
/*
* @NOTE This is non-interactive element to appease the DOM Nesting Validator
*
* We're using a lot of nested components here, which themselves render interactive
* elements.
* So if this were say... a button, it would try to render a button under a button
* and the validator would just yell at us some more.
*
* The other way to solve this, would be to make this list a table, and have the
* click handler on the table row.
* That isn't a option for us since I couldn't make the text ellipsis
* behave nicely (ie: work) while using our core <Table /> components
*/
role="button"
tabIndex={0}
className={getMainClasses({}, styles, {
noPointer: !handleOnClick,
[ItemStatus[status]]: !!status,
})}
onClick={handleSyntheticEvent}
onKeyPress={handleSyntheticEvent}
>
<div className={styles.avatar}>
{initiator && (
<UserAvatar
size="s"
address={initiator}
user={initiatorUserProfile}
notSet={false}
showInfo
popperProps={{
showArrow: false,
placement: 'bottom',
modifiers: [
{
name: 'offset',
options: {
offset: popoverPlacement,
},
},
],
}}
/>
)}
</div>
<div className={styles.content}>
<div className={styles.titleWrapper}>
<span className={styles.title}>
<FormattedMessage
id={roleMessageDescriptorId || 'action.title'}
values={{
actionType,
initiator: (
<span className={styles.titleDecoration}>
<FriendlyName
user={initiatorUserProfile}
autoShrinkAddress
/>
</span>
),
/*
* @TODO Add user mention popover back in
*/
recipient: (
<span className={styles.titleDecoration}>
<FriendlyName
user={fallbackRecipientProfile}
autoShrinkAddress
colony={colony}
/>
</span>
),
amount: (
<Numeral
value={amount}
unit={getTokenDecimalsWithFallback(decimals)}
/>
),
tokenSymbol: symbol,
decimals: getTokenDecimalsWithFallback(decimals),
fromDomain: domainName || fromDomain?.name || '',
toDomain: toDomain?.name || '',
roles: roleTitle,
newVersion: newVersion || '0',
}}
/>
</span>
{(motionState || isVotingExtensionEnabled) && (
<>
<div className={styles.motionTagWrapper}>
<Tag
text={motionStyles.name}
appearance={{
theme: motionStyles.theme as TagAppearance['theme'],
/*
* @NOTE Prettier is being stupid
*/
// eslint-disable-next-line max-len
colorSchema: motionStyles.colorSchema as TagAppearance['colorSchema'],
}}
/>
</div>
</>
)}
</div>
<div className={styles.meta}>
<FormattedDateParts value={createdAt} month="short" day="numeric">
{(parts) => (
<>
<span className={styles.day}>{parts[2].value}</span>
<span>{parts[0].value}</span>
</>
)}
</FormattedDateParts>
{fromDomain && (
<span className={styles.domain}>
{domainName || fromDomain.name ? (
domainName || fromDomain.name
) : (
<FormattedMessage
{...MSG.domain}
values={{ domainId: fromDomain.id }}
/>
)}
</span>
)}
{!!commentCount && (
<span className={styles.commentCount}>
<Icon
appearance={{ size: 'extraTiny' }}
className={styles.commentCountIcon}
name="comment"
title={formatMessage(MSG.titleCommentCount, {
commentCount,
formattedCommentCount: formatNumber(commentCount),
})}
/>
<AbbreviatedNumeral
formatOptions={{
notation: 'compact',
}}
value={commentCount}
title={formatMessage(MSG.titleCommentCount, {
commentCount,
formattedCommentCount: formatNumber(commentCount),
})}
/>
</span>
)}
</div>
</div>
{motionId && (
<div className={styles.countdownTimerContainer}>
<CountDownTimer
colony={colony}
state={motionState as MotionState}
motionId={Number(motionId)}
isFullyNayStaked={isFullyNayStaked}
/>
</div>
)}
</div>
</li>
);
};
ActionsListItem.displayName = displayName;
export default ActionsListItem; | the_stack |
import { connect } from 'react-redux'
import { push } from 'connected-react-router'
import { withRouter } from 'react-router-dom'
import { withStyles } from '@material-ui/core/styles'
import AddIcon from '@material-ui/icons/Add'
import Button from '@material-ui/core/Button'
import CloseIcon from '@material-ui/icons/Close'
import Fab from '@material-ui/core/Fab'
import Grid from '@material-ui/core/Grid'
import IconButton from '@material-ui/core/IconButton'
import InputBase from '@material-ui/core/InputBase'
import Paper from '@material-ui/core/Paper'
import Popover from '@material-ui/core/Popover'
import PropTypes from 'prop-types'
import React, { Component } from 'react'
import RemoveIcon from '@material-ui/icons/Remove'
import Table from '@material-ui/core/Table'
import TableBody from '@material-ui/core/TableBody'
import TableCell from '@material-ui/core/TableCell'
import TableHead from '@material-ui/core/TableHead'
import TableRow from '@material-ui/core/TableRow'
import Typography from '@material-ui/core/Typography'
import classNames from 'classnames'
import { Cart } from 'core/domain/cart'
import * as addToCartActions from 'store/actions/addToCartActions'
import { IAddToCartComponentProps } from './IAddToCartComponentProps'
import { IAddToCartComponentState } from './IAddToCartComponentState'
const styles = (theme: any) => ({
paper: {
top: '50px !important',
left: '650px !important'
},
itemcell: {
minWidth: 158,
fontSize: 12
},
button: {
textTransform: 'capitalize',
borderRadius: 30,
padding: `${15}px ${60}px`,
boxShadow: 'none'
},
dialogShoppingButton : {
backgroundColor: '#ffffff',
color: '#f62f5e'
},
bootstrapInput: {
borderRadius: 10,
position: 'relative',
backgroundColor: theme.palette.common.white,
border: '1px solid #ced4da',
fontSize: 12,
width: '20px',
padding: '5px 6px',
transition: theme.transitions.create(['border-color', 'box-shadow']),
// Use the system font instead of the default Roboto font.
},
noNotify: {
color: '#2e2e2e',
fontFamily: '"Montserrat", sans-serif',
justifyContent: 'center',
alignItems: 'center',
display: 'flex',
position: 'relative',
top: 60,
left: 130,
width: '100%'
},
borderbottom: {
borderBottom: 'none'
},
fab: {
background: 'transparent',
boxShadow: 'none',
color: '#f62f5e',
textTransform: 'capitalize',
'&:active, &:hover': {
color: '#ffffff'
},
},
quentityButton: {
margin: '5px',
width: '30px',
height: '30px',
minHeight: '30px',
boxShadow: 'none',
backgroundColor: '#efefef',
color: '#2e2e2e'
},
extendedIcon: {
marginRight: theme.spacing.unit,
},
table: {
minWidth: '700px',
minHeight: 400,
},
buttonWrapper : {
padding: 0
},
overflowHidden: {
overflow: 'hidden'
},
popperClose: {
pointerEvents: 'none'
},
popperOpen: {
zIndex: 1,
maxWidth: 500,
overflowY: 'auto'
},
popper: {
},
fullPageXs: {
[theme.breakpoints.down('xs')]: {
width: '100%',
height: '100%',
margin: 0,
overflowY: 'auto'
}
},
paperbuttons: {
backgroundColor: '#f7f7f7',
borderTopLeftRadius: 0,
borderTopRightRadius: 0,
padding: theme.spacing(2),
[theme.breakpoints.up(600 + theme.spacing(3) * 2)]: {
padding: `${24}px ${48}px`,
},
},
closeButton: {
position: 'absolute',
right: theme.spacing.unit,
top: 0,
color: '#6c6c6c',
fontSize: 26
},
formTitle: {
fontFamily: '"Montserrat", sans-serif',
fontSize: 16,
color: '#2e2e2e',
lineHeight: '150%',
textTransform: 'capitalize',
margin: 10
},
tablerow: {
verticalAlign: 'text-top'
}
})
/**
* Create component class
*/
export class AddToCartComponent extends Component<IAddToCartComponentProps,IAddToCartComponentState> {
static propTypes = {
/**
* It will be true if the notification is open
*/
open: PropTypes.bool,
/**
* Pass anchor element
*/
anchorEl: PropTypes.any,
/**
* Fire to close notificaion
*/
onRequestClose: PropTypes.func,
}
/**
* Component constructor
* @param {object} props is an object properties of component
*/
constructor (props: IAddToCartComponentProps) {
super(props)
// Defaul state
this.state = {
quantity: 1,
show: true,
max: 5,
min: 0
}
// Binding functions to `this`
this.cartList = this.cartList.bind(this)
this.incrementItem = this.incrementItem.bind(this)
this.decreaseItem = this.decreaseItem.bind(this)
this.handleChange = this.handleChange.bind(this)
this.toggleClick = this.toggleClick.bind(this)
this.handleClose = this.handleClose.bind(this)
}
incrementItem = (value: any , key: any) => {
this.setState(prevState => {
if (prevState.quantity < 9 ) {
return {
quantity: prevState.quantity + 1
}
} else {
return null
}
})
this.props.updateToCart!(value.get('itemId'), key,{
productThumbnail: value.get('productThumbnail'),
productName: value.get('productName'),
productPrice: value.get('productPrice'),
productId: value.get('productId'),
productColor: value.get('productColor'),
productQuantity: value.get('productQuantity') + 1,
productSize: value.get('productSize')
})
}
decreaseItem = (value: any , key: any) => {
this.setState(prevState => {
if (prevState.quantity > 0) {
return {
quantity: prevState.quantity - 1
}
} else {
return null
}
})
this.props.updateToCart!(value.get('itemId'), key, {
productThumbnail: value.get('productThumbnail'),
productName: value.get('productName'),
productPrice: value.get('productPrice'),
productId: value.get('productId'),
productColor: value.get('productColor'),
productQuantity: value.get('productQuantity') - 1 ,
productSize: value.get('productSize')
})
}
/**
* Handle Remove cart
*/
handleRemove = (value: any , key: any) => {
this.props.updateToCart!(value.get('itemId'), key, {
productThumbnail: value.get('productThumbnail'),
productName: value.get('productName'),
productPrice: value.get('productPrice'),
productId: value.get('productId'),
productColor: value.get('productColor'),
productQuantity: 0 ,
productSize: value.get('productSize')
})
}
/**
* Handle Dialog close
*/
handleShopping = () => {
this.setState({
})
}
/**
* Handle Dialog close
*/
handleClose = () => {
this.setState({
closecart: false
})
console.log('value of close', this.state.closecart)
}
/**
* Handle Dialog close
*/
handleCheckout = () => {
}
handleChange = (event: any) => {
this.setState({quantity: event.target.value})
}
toggleClick = () => {
this.setState({
show: !this.state.show
})
}
cartList = () => {
const {classes} = this.props
const allCartProducts = this.props.cartProducts
const cartProductsList: any[] = []
if (allCartProducts) {
allCartProducts.forEach((cartProduct: any, cartkey: string) => {
cartProduct.forEach((value: any, key: string) => {
cartProductsList.push(
<TableRow key={key} className={classes.tablerow}>
<TableCell scope='row' className={classNames(classes.itemcell, classes.borderbottom)}>
<Grid container direction='row' spacing={2}>
<Grid item xs>
<img
alt='productname'
src={`/images/${value.get('productThumbnail')}`}
/>
</Grid>
<Grid item xs>
<Typography gutterBottom>
{value.get('productName')}
</Typography>
<Typography gutterBottom>
Men BK3569
</Typography>
<Fab variant='extended' size='small' disableFocusRipple disableRipple aria-label='Remove' color='secondary' className={classes.fab} onClick={() => this.handleRemove(value, cartkey)}>
<CloseIcon className={classes.extendedIcon} />
Remove
</Fab>
</Grid>
</Grid>
</TableCell>
<TableCell align='center' className={classes.borderbottom}>{value.get('productSize')}</TableCell>
<TableCell align='right' className={classNames(classes.borderbottom, classes.buttonWrapper)}>
<Fab color='secondary' className={classes.quentityButton} size='small' aria-label='Add' onClick={() => this.incrementItem(value, cartkey)}>
<AddIcon />
</Fab>
<InputBase
id='bootstrap-input'
value={value.get('productQuantity')}
onChange={this.handleChange}
classes={{
input: classes.bootstrapInput,
}}
/>
<Fab color='secondary' aria-label='Add' className={classes.quentityButton} size='small' onClick={() => this.decreaseItem(value, cartkey)}>
<RemoveIcon />
</Fab>
</TableCell>
<TableCell align='left' className={classes.borderbottom}>£{value.get('productPrice')}</TableCell>
</TableRow>
)
})
})
}
return cartProductsList
}
/**
* Reneder component DOM
* @return {react element} return the DOM which rendered by component
*/
render () {
const { classes, open, anchorEl, onRequestClose, goTo} = this.props
const noCartItem = (
<div className={classes.noNotify}>
No items in the cart, Go and have some Products! </div>
)
const items = this.cartList()
return (
<React.Fragment>
<Popover
open={this.state.closecart ? this.state.closecart : open}
anchorEl={anchorEl}
onClose={onRequestClose}
classes={{
paper: classes.root
}}
PaperProps={{ className: classNames(classes.paper) }}
anchorOrigin={{
vertical: 'top',
horizontal: 'right',
}}
transformOrigin={{
vertical: 'top',
horizontal: 'center',
}}
>
<Paper className={classNames(classes.root, { [classes.overflowHidden]: !open })} elevation={4} >
<IconButton aria-label='Close' className={classes.closeButton} onClick={this.handleClose} >
<CloseIcon />
</IconButton>
<Grid container spacing={2}>
<Grid item xs>
<Table className={classes.table}>
<TableHead className={classes.head}>
<TableRow><Typography gutterBottom align='left' className={classes.formTitle}>{items.length} Items In Your Cart</Typography></TableRow>
<TableRow>
<TableCell className={classes.head}>Item</TableCell>
<TableCell className={classes.head}>Size</TableCell>
<TableCell align='right' className={classes.head}>Quanity</TableCell>
<TableCell align='right' className={classes.head}>Price</TableCell>
</TableRow>
</TableHead>
<TableBody>
{items.length > 0 ? this.cartList() : noCartItem}
</TableBody>
</Table>
</Grid>
</Grid>
</Paper>
<Paper className={classes.paperbuttons}>
<React.Fragment>
<Grid container spacing={8}>
<Grid item container xs={12} sm={6} direction='row' justify='flex-start' alignItems='center'>
<Button
onClick={evt => {
evt.preventDefault()
this.setState({
closecart: true
})
goTo!(`/products`)
}}
className={classNames(classes.dialogShoppingButton, classes.button)}
variant='contained'
>
Back to shop
</Button>
</Grid>
<Grid item xs={12} sm={6} container direction='row' justify='flex-end' alignItems='center' >
{items.length > 0 ? (
<Button
variant='contained'
color='secondary'
onClick={evt => {
evt.preventDefault()
goTo!(`/checkout`)
}}
className={classes.button}
>
Checkout
</Button>) : ''}
</Grid>
</Grid>
</React.Fragment>
</Paper>
</Popover>
</React.Fragment>
)
}
}
/**
* Map dispatch to props
* @param {func} dispatch is the function to dispatch action to reducers
* @param {object} ownProps is the props belong to component
* @return {object} props of component
*/
const mapDispatchToProps = (dispatch: Function, ownProps: IAddToCartComponentProps) => {
return {
goTo: (url: string) => dispatch(push(url)),
updateToCart: (itemId: string, cartId: string, cart: Cart) => {
dispatch(addToCartActions.dbUpdateCartItem(itemId,cartId,cart))
}
}
}
/**
* Map state to props
* @param {object} state is the obeject from redux store
* @param {object} ownProps is the props belong to component
* @return {object} props of component
*/
const mapStateToProps = (state: any, ownProps: IAddToCartComponentProps) => {
const uid = state.getIn(['authorize', 'uid'], 0)
const cartProducts = state.getIn(['addToCart', 'cartProducts'])
return {
uid,
cartProducts
}
}
export default withRouter<any>(connect(mapStateToProps, mapDispatchToProps)(withStyles(styles as any, { withTheme: true })(AddToCartComponent as any) as any)) as typeof AddToCartComponent | the_stack |
import httpStatusCodes from 'http-status';
import BoxClient from '../box-client';
import errors from '../util/errors';
import urlPath from '../util/url-path';
// -----------------------------------------------------------------------------
// Typedefs
// -----------------------------------------------------------------------------
/**
* Enum value of scope of the custom terms of services set to either managed by an enterprise or enternal to an enterprise
*
* @readonly
* @enum {TermsOfServicesType}
*/
enum TermsOfServicesType {
MANAGED = 'managed',
EXTERNAL = 'external',
}
/**
* Enum value of status of the custom terms of services, either currently enabled or currently disabled
*
* @readonly
* @enum {TermsOfServicesStatus}
*/
enum TermsOfServicesStatus {
ENABLED = 'enabled',
DISABLED = 'disabled',
}
// -----------------------------------------------------------------------------
// Private
// -----------------------------------------------------------------------------
// Base path for all terms of service endpoints
const BASE_PATH = '/terms_of_services',
USER_STATUSES_PATH = '/terms_of_service_user_statuses';
// ------------------------------------------------------------------------------
// Public
// ------------------------------------------------------------------------------
/**
* Simple manager for interacting with all 'Terms of Services' and 'Terms of Service User Statuses' endpoints and actions.
*
* @param {BoxClient} client The Box API Client that is responsible for making calls to the API
* @constructor
*/
class TermsOfService {
client: BoxClient;
type!: typeof TermsOfServicesType;
status!: typeof TermsOfServicesStatus;
constructor(client: BoxClient) {
// Attach the client, for making API calls
this.client = client;
}
/**
* Creates a custom terms of services with user specified values
*
* API Endpoint: '/terms_of_services'
* Method: POST
*
* @param {TermsOfServicesType} termsOfServicesType - Determine if the custom terms of service is scoped internall or externally to an enterprise
* @param {TermsOfServicesStatus} termsOfServicesStatus - Determine if the custom terms of service is enabled or disabled
* @param {string} termsOfServicesText - Text field for message associated with custom terms of services
* @param {Function} [callback] - Passed the terms of services information if successful, error otherwise
* @returns {Promise<Object>} A promise resolving to the terms of services object
*/
create(
termsOfServicesType: TermsOfServicesType,
termsOfServicesStatus: TermsOfServicesStatus,
termsOfServicesText: string,
callback?: Function
) {
var params = {
body: {
status: termsOfServicesStatus,
tos_type: termsOfServicesType,
text: termsOfServicesText,
},
};
var apiPath = urlPath(BASE_PATH);
return this.client.wrapWithDefaultHandler(this.client.post)(
apiPath,
params,
callback
);
}
/**
* Updates a custom terms of services with new specified values
*
* API Endpoint: '/terms_of_services/:termsOfServicesID'
* Method: PUT
*
* @param {string} termsOfServicesID - The id of the custom terms of services to update
* @param {Object} updates - Fields ot the Terms of Service to update
* @param {TermsOfServicesStatus} [updates.status] - Determine if the custom terms of service is scoped internall or externally to an enterprise
* @param {string} [updates.text] - Text field for message associated with custom terms of services
* @param {Function} [callback] - Passed the terms of services updated information if successful, error otherwise
* @returns {Promise<Object>} A promise resolving to the terms of services object
*/
update(
termsOfServicesID: string,
updates: {
status?: TermsOfServicesStatus;
text?: string;
},
callback?: Function
) {
var params = {
body: updates,
};
var apiPath = urlPath(BASE_PATH, termsOfServicesID);
return this.client.wrapWithDefaultHandler(this.client.put)(
apiPath,
params,
callback
);
}
/**
* Gets a specific custom terms of services with specified ID
*
* API Endpoint: '/terms_of_services/:termsOfServicesID'
* Method: GET
*
* @param {string} termsOfServicesID - The id of the custom terms of services to retrieve
* @param {Object} [options] - Additional options. Can be left null in most cases.
* @param {string} [options.fields] - Comma-separated list of fields to return on the collaboration objects
* @param {Function} [callback] - Passed the terms of services information with specified ID if successful, error otherwise
* @returns {Promise<Object>} A promise resolving to the terms of services object
*/
get(
termsOfServicesID: string,
options?: {
fields?: string;
},
callback?: Function
) {
var params = {
qs: options,
};
var apiPath = urlPath(BASE_PATH, termsOfServicesID);
return this.client.wrapWithDefaultHandler(this.client.get)(
apiPath,
params,
callback
);
}
/**
* Gets custom terms of services for the user's enterprise
*
* API Endpoint: '/terms_of_services'
* Method: GET
*
* @param {Object} [options] - Additional options. Can be left null in most cases.
* @param {TermsOfServiceType} [options.tos_type] - Optional, indicates whether the terms of service is set for external or managed under enterprise
* @param {string} [options.fields] - Comma-separated list of fields to return on the collaboration objects
* @param {Function} [callback] - Passed the terms of services information if successful, error otherwise
* @returns {Promise<Object>} A promise resolving to the terms of services object
*/
getAll(
options?: {
tos_type?: TermsOfServicesType;
fields?: string;
},
callback?: Function
) {
var params = {
qs: options,
};
var apiPath = urlPath(BASE_PATH);
return this.client.wrapWithDefaultHandler(this.client.get)(
apiPath,
params,
callback
);
}
/**
* Accepts/rejects custom terms of services for the user
*
* API Endpoint: '/terms_of_service_user_statuses'
* Method: POST
*
* @param {string} termsOfServicesID - Terms of services ID to retrieve user statuses on
* @param {boolean} isAccepted - Determines wehether the terms of services has been accepted or rejected
* @param {Object} [options] - Additional options. Can be left null in most cases.
* @param {string} [options.user_id] - Optional, user id to retrieve terms of service status on, default is current user
* @param {Function} [callback] - Passed the terms of service user status information if successful, error otherwise
* @returns {Promise<Object>} A promise resolving to the terms of service user status
*/
createUserStatus(
termsOfServicesID: string,
isAccepted: boolean,
options?: {
user_id?: string;
},
callback?: Function
) {
var params = {
body: {
tos: {
id: termsOfServicesID,
type: 'terms_of_service',
},
is_accepted: isAccepted,
} as Record<string, any>,
};
if (options && options.user_id) {
params.body.user = { id: options.user_id, type: 'user' };
}
var apiPath = urlPath(USER_STATUSES_PATH);
return this.client.wrapWithDefaultHandler(this.client.post)(
apiPath,
params,
callback
);
}
/**
* Gets a terms os service status given the terms of services id
*
* API Endpoint: '/terms_of_service_user_statuses'
* Method: GET
*
* @param {string} termsOfServicesID - The ID of the terms of services to retrieve status on
* @param {Object} [options] - Additional options. Can be left null in most cases
* @param {string} [options.user_id] - Optional, the id of the user to retrieve status of custom terms and service on
* @param {Function} [callback] - Passed the terms of service user status information if successful, error otherwise
* @returns {Promise<Object>} A promise resolving to the terms of service user status
*/
getUserStatus(
termsOfServicesID: string,
options?: {
user_id?: string;
},
callback?: Function
) {
var params = {
qs: {
tos_id: termsOfServicesID,
},
};
if (options) {
Object.assign(params.qs, options);
}
var apiPath = urlPath(USER_STATUSES_PATH);
return this.client
.get(apiPath, params)
.then((response: any /* FIXME */) => {
if (response.statusCode !== 200) {
throw errors.buildUnexpectedResponseError(response);
}
return response.body.entries[0];
})
.asCallback(callback);
}
/**
* Accepts/rejects custom terms of services for the user
*
* API Endpoint: '/terms_of_service_user_statuses'
* Method: PUT
*
* @param {string} termsOfServiceUserStatusID - Terms of service user status object ID
* @param {boolean} isAccepted - Determines wehether the terms of services has been accepted or rejected
* @param {Function} [callback] - Passed the terms of service user status updated information if successful, error otherwise
* @returns {Promise<Object>} A promise resolving to the updated terms of service user status
*/
updateUserStatus(
termsOfServiceUserStatusID: string,
isAccepted: boolean,
callback?: Function
) {
var params = {
body: {
is_accepted: isAccepted,
},
};
var apiPath = urlPath(USER_STATUSES_PATH, termsOfServiceUserStatusID);
return this.client.wrapWithDefaultHandler(this.client.put)(
apiPath,
params,
callback
);
}
/**
* Creates a user status for terms of service, if already exists then update existing user status for terms of service
*
* API Endpoint: '/terms_of_service_user_statuses'
* Method: POST/PUT
*
* @param {string} termsOfServicesID - Terms of services ID to retrieve user statuses on
* @param {boolean} isAccepted - Determines wehether the terms of services has been accepted or rejected
* @param {Object} [options] - Additional options. Can be left null in most cases.
* @param {string} [options.user_id] - Optional, user id to retrieve terms of service status on, default is current user
* @param {Function} [callback] - Passed the terms of service user status information if successful, error otherwise
* @returns {Promise<Object>} A promise resolving to the terms of service user status
*/
setUserStatus(
termsOfServicesID: string,
isAccepted: boolean,
options?: {
user_id?: string;
},
callback?: Function
) {
var params = {
body: {
tos: {
id: termsOfServicesID,
type: 'terms_of_service',
},
is_accepted: isAccepted,
} as Record<string, any>,
};
if (options && options.user_id) {
params.body.user = { id: options.user_id, type: 'user' };
}
var apiPath = urlPath(USER_STATUSES_PATH);
return this.client
.post(apiPath, params)
.then((response: any /* FIXME */) => {
switch (response.statusCode) {
// 200 - A user status has been successfully created on terms of service
// return the terms of service user status object
case httpStatusCodes.OK:
return response.body;
// 409 - Conflict
// Terms of Service already exists. Update the existing terms of service object
case httpStatusCodes.CONFLICT:
var getOptions = Object.assign({ fields: 'id' }, options);
return this.getUserStatus(termsOfServicesID, getOptions).then((
userStatus: any /* FIXME */
) => this.updateUserStatus(userStatus.id, isAccepted));
default:
throw errors.buildUnexpectedResponseError(response);
}
})
.asCallback(callback);
}
}
/**
* Enum value of scope of the custom terms of services set to either managed by an enterprise or enternal to an enterprise
*
* @readonly
* @enum {TermsOfServicesType}
*/
TermsOfService.prototype.type = TermsOfServicesType;
/**
* Enum value of status of the custom terms of services, either currently enabled or currently disabled
*
* @readonly
* @enum {TermsOfServicesStatus}
*/
TermsOfService.prototype.status = TermsOfServicesStatus;
/**
* @module box-node-sdk/lib/managers/terms-of-service
* @see {@Link TermsOfService}
*/
export = TermsOfService; | the_stack |
import * as React from 'react'
import { render, screen } from '@testing-library/react'
import { CheckboxField } from '.'
import userEvent from '@testing-library/user-event'
import { axe } from 'jest-axe'
describe('CheckboxField', () => {
function IndeterminateTestCase({ initialState }: { initialState: boolean[] }) {
const [state, setState] = React.useState<boolean[]>(initialState)
const checkedCount = state.filter(Boolean).length
const indeterminate = checkedCount > 0 && checkedCount < state.length
return (
<div>
<CheckboxField
data-testid="main-checkbox"
checked={checkedCount === state.length}
onChange={(event) => {
const { checked } = event.currentTarget
setState((state) => state.map(() => checked))
}}
indeterminate={indeterminate}
label={`Check/uncheck all (${checkedCount} / ${state.length})`}
/>
<div>
{state.map((checked, index) => (
<CheckboxField
key={`${index}-${String(checked)}`}
data-testid="checkbox-item"
label={String(index + 1)}
checked={checked}
onChange={(event) => {
const { checked } = event.currentTarget
setState((state) => {
const newState = [...state]
newState[index] = checked
return newState
})
}}
/>
))}
</div>
</div>
)
}
it('supports having an externally provided id attribute', () => {
render(
<CheckboxField data-testid="checkbox-field" id="custom-id" label="Show unread badge" />,
)
expect(screen.getByTestId('checkbox-field').id).toBe('custom-id')
// Makes sure that even with the custom id, the label is still associated to the input element
expect(screen.getByTestId('checkbox-field')).toHaveAccessibleName('Show unread badge')
})
it('is labelled by its label', () => {
render(<CheckboxField data-testid="checkbox-field" label="Show completed tasks" />)
expect(screen.getByTestId('checkbox-field')).toHaveAccessibleName('Show completed tasks')
})
it('issues a warning if no label is given', () => {
/* eslint-disable no-console */
const originalConsoleWarn = console.warn
console.warn = jest.fn()
render(<CheckboxField />)
expect(console.warn).toHaveBeenCalledWith(expect.stringMatching(/needs a label/))
console.warn = originalConsoleWarn
/* eslint-enable no-console */
})
it('is hidden when hidden={true}', () => {
const { rerender } = render(
<CheckboxField data-testid="checkbox-field" label="Show unread badge" hidden />,
)
const inputField = screen.getByTestId('checkbox-field')
// check that it is rendered but not visible
expect(inputField).not.toBeVisible()
expect(
screen.queryByRole('checkbox', { name: 'Show unread badge' }),
).not.toBeInTheDocument()
// check that it becomes visible when hidden is removed
rerender(<CheckboxField data-testid="checkbox-field" label="Show unread badge" />)
expect(inputField).toBeVisible()
expect(screen.getByRole('checkbox', { name: 'Show unread badge' })).toBeInTheDocument()
})
it('forwards to the input element any extra props provided to it', () => {
render(
<CheckboxField
label="Visual label"
aria-label="Non-visual label"
data-testid="checkbox-field"
data-something="whatever"
/>,
)
const switchElement = screen.getByTestId('checkbox-field')
expect(switchElement.tagName).toBe('INPUT')
expect(switchElement).toHaveAttribute('type', 'checkbox')
expect(switchElement).toHaveAttribute('aria-label', 'Non-visual label')
expect(switchElement).toHaveAttribute('data-testid', 'checkbox-field')
expect(switchElement).toHaveAttribute('data-something', 'whatever')
})
it('allows to be toggled on and off', () => {
render(<CheckboxField label="Accept terms and conditions" />)
const switchElement = screen.getByRole('checkbox', { name: 'Accept terms and conditions' })
expect(switchElement).not.toBeChecked()
userEvent.click(switchElement)
expect(switchElement).toBeChecked()
userEvent.click(switchElement)
expect(switchElement).not.toBeChecked()
})
it('can be disabled', () => {
render(<CheckboxField label="Accept terms and conditions" disabled />)
const switchElement = screen.getByRole('checkbox', { name: 'Accept terms and conditions' })
expect(switchElement).toBeDisabled()
expect(switchElement).not.toBeChecked()
userEvent.click(switchElement)
expect(switchElement).not.toBeChecked()
})
it('can be uncontrolled and set to true by default', () => {
render(<CheckboxField label="Accept terms and conditions" defaultChecked />)
const switchElement = screen.getByRole('checkbox', { name: 'Accept terms and conditions' })
expect(switchElement).toBeChecked()
userEvent.click(switchElement)
expect(switchElement).not.toBeChecked()
})
it('can be a controlled input field', () => {
function TestCase() {
const [checked, setChecked] = React.useState(false)
return (
<>
<CheckboxField
label="Accept terms and conditions"
checked={checked}
onChange={(event) => setChecked(event.currentTarget.checked)}
/>
<div data-testid="value">{checked ? 'on' : 'off'}</div>
</>
)
}
render(<TestCase />)
const switchElement = screen.getByRole('checkbox', { name: 'Accept terms and conditions' })
expect(switchElement).not.toBeChecked()
expect(screen.getByTestId('value')).toHaveTextContent('off')
userEvent.click(switchElement)
expect(switchElement).toBeChecked()
expect(screen.getByTestId('value')).toHaveTextContent('on')
userEvent.click(switchElement)
expect(switchElement).not.toBeChecked()
expect(screen.getByTestId('value')).toHaveTextContent('off')
})
describe('indeterminate', () => {
function getCheckboxItem(index: number) {
return screen.getAllByTestId('checkbox-item')[index]
}
it('can be set as indeterminate when it is a controlled component', () => {
render(<IndeterminateTestCase initialState={[false, true, false]} />)
const mainCheckbox = screen.getByTestId('main-checkbox')
// it's initially indeterminate
expect(mainCheckbox).toBePartiallyChecked()
// check two remaining unchecked checkboxes, and it ceases to be indeterminate
userEvent.click(getCheckboxItem(0))
userEvent.click(getCheckboxItem(2))
expect(mainCheckbox).toBeChecked()
// uncheck all checkboxes one by one, and gradually check main checkbox status along the way
userEvent.click(getCheckboxItem(0))
expect(mainCheckbox).toBePartiallyChecked()
expect(mainCheckbox).not.toBeChecked()
// …second one
userEvent.click(getCheckboxItem(1))
expect(mainCheckbox).toBePartiallyChecked()
expect(mainCheckbox).not.toBeChecked()
// …last one
userEvent.click(getCheckboxItem(2))
expect(mainCheckbox).not.toBePartiallyChecked()
expect(mainCheckbox).not.toBeChecked()
// check them all via the main checkbox
userEvent.click(mainCheckbox)
expect(mainCheckbox).toBeChecked()
expect(mainCheckbox).not.toBePartiallyChecked()
// uncheck a single checkbox item
userEvent.click(getCheckboxItem(2))
expect(mainCheckbox).not.toBeChecked()
expect(mainCheckbox).toBePartiallyChecked()
})
it('cannot be used as indeterminate when component is uncontrolled', () => {
/* eslint-disable no-console */
const originalConsoleWarn = console.warn
console.warn = jest.fn()
render(<CheckboxField label="Main checkbox" indeterminate={true} />)
expect(console.warn).toHaveBeenCalledWith(
expect.stringMatching(/indeterminate.+uncontrolled/),
)
console.warn = originalConsoleWarn
/* eslint-enable no-console */
})
})
describe('a11y', () => {
test('renders with no a11y violations', async () => {
const { container } = render(<CheckboxField label="Show completed tasks" />)
const results = await axe(container)
expect(results).toHaveNoViolations()
})
it('supports the `aria-label` attribute', () => {
render(
<CheckboxField
data-testid="checkbox-field"
label="Show completed tasks"
aria-label="Show completed tasks by default"
/>,
)
expect(screen.getByTestId('checkbox-field')).toHaveAccessibleName(
'Show completed tasks by default',
)
})
it('supports the `aria-labelledby` attribute', () => {
render(
<>
<CheckboxField
data-testid="checkbox-field"
label="Show completed tasks"
aria-labelledby="custom-label"
/>
<div id="custom-label">Show completed tasks by default</div>
</>,
)
expect(screen.getByTestId('checkbox-field')).toHaveAccessibleName(
'Show completed tasks by default',
)
})
it('supports the `aria-describedby` attribute', () => {
render(
<>
<CheckboxField
data-testid="checkbox-field"
label="Show completed tasks"
aria-describedby="custom-hint"
/>
<div id="custom-hint">Always show your completed tasks by default</div>
</>,
)
expect(screen.getByTestId('checkbox-field')).toHaveAccessibleDescription(
'Always show your completed tasks by default',
)
})
it('supports the `aria-controls` attribute', () => {
render(
<>
<CheckboxField
data-testid="checkbox-field"
label="Parent checkbox"
aria-controls="child-checkbox"
/>
<CheckboxField id="child-checkbox" label="Child checkbox" />
</>,
)
expect(screen.getByTestId('checkbox-field')).toHaveAttribute(
'aria-controls',
'child-checkbox',
)
})
it('updates the `aria-checked` attribute correctly', () => {
render(<IndeterminateTestCase initialState={[false, true, false]} />)
const mainCheckbox = screen.getByTestId('main-checkbox')
// it's initially indeterminate
expect(mainCheckbox).toHaveAttribute('aria-checked', 'mixed')
// updates to 'true' when clicked while mixed
userEvent.click(mainCheckbox)
expect(mainCheckbox).toHaveAttribute('aria-checked', 'true')
// updates to 'false' when clicked while true
userEvent.click(mainCheckbox)
expect(mainCheckbox).toHaveAttribute('aria-checked', 'false')
})
})
}) | the_stack |
import { AccuDrawHintBuilder, BeButtonEvent, DynamicsContext, ElementSetTool, FeatureOverrideProvider, FeatureSymbology, HitDetail, IModelApp, LengthDescription, LocateResponse, NotifyMessageDetails, OutputMessagePriority, ToolAssistanceInstruction, Viewport } from "@itwin/core-frontend";
import { BentleyError, Code, ElementGeometry, ElementGeometryInfo, ElementGeometryOpcode, FeatureAppearance, FlatBufferGeometryStream, GeometricElementProps, GeometryParams, JsonGeometryStream } from "@itwin/core-common";
import { EditTools } from "./EditTool";
import { AngleSweep, Arc3d, AxisOrder, CurveCollection, CurvePrimitive, FrameBuilder, Geometry, JointOptions, LineSegment3d, LineString3d, Loop, Matrix3d, Path, RegionOps, Vector3d } from "@itwin/core-geometry";
import { BasicManipulationCommandIpc, editorBuiltInCmdIds } from "@itwin/editor-common";
import { computeChordToleranceFromPoint, DynamicGraphicsProvider } from "./CreateElementTool";
import { DialogItem, DialogProperty, DialogPropertySyncItem, PropertyDescriptionHelper } from "@itwin/appui-abstract";
import { Id64, Id64String } from "@itwin/core-bentley";
/** @alpha */
export class CurveData {
public props: GeometricElementProps;
public params: GeometryParams;
public geom: CurveCollection | CurvePrimitive;
constructor(props: GeometricElementProps, params: GeometryParams, geom: CurveCollection | CurvePrimitive) {
this.props = props;
this.params = params;
this.geom = geom;
}
}
/** @alpha Base class for applying an offset to path and loops. */
export abstract class ModifyCurveTool extends ElementSetTool implements FeatureOverrideProvider {
protected _startedCmd?: string;
protected readonly _checkedIds = new Map<Id64String, boolean>();
protected curveData?: CurveData;
protected _graphicsProvider?: DynamicGraphicsProvider;
protected _firstResult = true;
protected _agendaAppearanceDefault?: FeatureAppearance;
protected _agendaAppearanceDynamic?: FeatureAppearance;
protected allowView(_vp: Viewport) { return true; }
public override isCompatibleViewport(vp: Viewport | undefined, isSelectedViewChange: boolean): boolean { return (super.isCompatibleViewport(vp, isSelectedViewChange) && undefined !== vp && this.allowView(vp)); }
protected async startCommand(): Promise<string> {
if (undefined !== this._startedCmd)
return this._startedCmd;
return EditTools.startCommand<string>(editorBuiltInCmdIds.cmdBasicManipulation, this.iModel.key);
}
public static callCommand<T extends keyof BasicManipulationCommandIpc>(method: T, ...args: Parameters<BasicManipulationCommandIpc[T]>): ReturnType<BasicManipulationCommandIpc[T]> {
return EditTools.callCommand(method, ...args) as ReturnType<BasicManipulationCommandIpc[T]>;
}
protected agendaAppearance(isDynamics: boolean): FeatureAppearance {
if (isDynamics) {
if (undefined === this._agendaAppearanceDynamic)
this._agendaAppearanceDynamic = FeatureAppearance.fromTransparency(0.0);
return this._agendaAppearanceDynamic;
}
if (undefined === this._agendaAppearanceDefault)
this._agendaAppearanceDefault = FeatureAppearance.fromTransparency(0.9);
return this._agendaAppearanceDefault;
}
protected get wantAgendaAppearanceOverride(): boolean { return false; }
public addFeatureOverrides(overrides: FeatureSymbology.Overrides, _vp: Viewport): void {
if (this.agenda.isEmpty)
return;
const appearance = this.agendaAppearance(false);
this.agenda.elements.forEach((elementId) => { overrides.override({ elementId, appearance }); });
}
protected updateAgendaAppearanceProvider(drop?: true): void {
if (!this.wantAgendaAppearanceOverride)
return;
for (const vp of IModelApp.viewManager) {
if (!this.allowView(vp))
continue;
if (drop || this.agenda.isEmpty)
vp.dropFeatureOverrideProvider(this);
else if (!vp.addFeatureOverrideProvider(this))
vp.setFeatureOverrideProviderChanged();
}
}
protected clearGraphics(): void {
if (undefined === this._graphicsProvider)
return;
this._graphicsProvider.cleanupGraphic();
this._graphicsProvider = undefined;
}
protected async createGraphics(ev: BeButtonEvent): Promise<void> {
if (!IModelApp.viewManager.inDynamicsMode)
return; // Don't need to create graphic if dynamics aren't yet active...
const geometry = this.getGeometryProps(ev, false);
if (undefined === geometry)
return;
const elemProps = this.getElementProps(ev);
if (undefined === elemProps?.placement)
return;
if (undefined === this._graphicsProvider) {
if (this._firstResult) {
this.updateAgendaAppearanceProvider();
this._firstResult = false;
}
this._graphicsProvider = new DynamicGraphicsProvider(this.iModel, this.toolId);
}
// Set chord tolerance for non-linear curve primitives...
if (ev.viewport)
this._graphicsProvider.chordTolerance = computeChordToleranceFromPoint(ev.viewport, ev.point);
await this._graphicsProvider.createGraphic(elemProps.category, elemProps.placement, geometry);
}
public static isSingleCurve(info: ElementGeometryInfo): { curve: CurveCollection | CurvePrimitive, params: GeometryParams } | undefined {
const it = new ElementGeometry.Iterator(info);
it.requestWorldCoordinates();
for (const entry of it) {
const geom = entry.toGeometryQuery();
if (undefined === geom)
return;
if ("curvePrimitive" === geom.geometryCategory) {
return { curve: geom as CurvePrimitive, params: entry.geomParams };
} else if ("curveCollection" === geom.geometryCategory) {
return { curve: geom as CurveCollection, params: entry.geomParams };
}
break;
}
return;
}
protected acceptCurve(_curve: CurveCollection | CurvePrimitive): boolean { return true; }
protected modifyCurve(_ev: BeButtonEvent, _isAccept: boolean): CurveCollection | CurvePrimitive | undefined { return undefined; }
protected async getCurveData(id: Id64String): Promise<CurveData | undefined> {
try {
this._startedCmd = await this.startCommand();
const reject: ElementGeometryOpcode[] = [ElementGeometryOpcode.Polyface, ElementGeometryOpcode.SolidPrimitive, ElementGeometryOpcode.BsplineSurface, ElementGeometryOpcode.BRep ];
const info = await ModifyCurveTool.callCommand("requestElementGeometry", id, { maxDisplayable: 1, reject, geometry: { curves: true, surfaces: true, solids: false } });
if (undefined === info)
return undefined;
const data = ModifyCurveTool.isSingleCurve(info);
if (undefined === data)
return undefined;
if (!this.acceptCurve(data.curve))
return undefined;
const props = await this.iModel.elements.loadProps(id) as GeometricElementProps;
if (undefined === props)
return undefined;
return new CurveData(props, data.params, data.curve);
} catch (err) {
IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Error, BentleyError.getErrorMessage(err)));
return undefined;
}
}
protected onGeometryFilterChanged(): void { this._checkedIds.clear(); }
protected async acceptElementForOperation(id: Id64String): Promise<boolean> {
if (Id64.isInvalid(id) || Id64.isTransient(id))
return false;
let accept = this._checkedIds.get(id);
if (undefined === accept) {
if (this.agenda.isEmpty && this._checkedIds.size > 1000)
this._checkedIds.clear(); // Limit auto-locate cache size to something reasonable...
accept = (undefined !== await this.getCurveData(id));
this._checkedIds.set(id, accept);
}
return accept;
}
protected override async isElementValidForOperation(hit: HitDetail, out?: LocateResponse): Promise<boolean> {
if (!await super.isElementValidForOperation(hit, out))
return false;
return this.acceptElementForOperation(hit.sourceId);
}
protected override async onAgendaModified(): Promise<void> {
this.curveData = undefined;
if (this.agenda.isEmpty)
return;
const id = this.agenda.elements[this.agenda.length-1];
this.curveData = await this.getCurveData(id);
}
public override onDynamicFrame(_ev: BeButtonEvent, context: DynamicsContext): void {
if (undefined !== this._graphicsProvider)
this._graphicsProvider.addGraphic(context);
}
public override async onMouseMotion(ev: BeButtonEvent): Promise<void> {
return this.createGraphics(ev);
}
protected setupAccuDraw(): void {
const hints = new AccuDrawHintBuilder();
hints.enableSmartRotation = true;
hints.sendHints(false);
}
protected override setupAndPromptForNextAction(): void {
this.setupAccuDraw();
super.setupAndPromptForNextAction();
}
protected getGeometryProps(ev: BeButtonEvent, isAccept: boolean): JsonGeometryStream | FlatBufferGeometryStream | undefined {
if (undefined === this.curveData)
return;
const offset = this.modifyCurve(ev, isAccept);
if (undefined === offset)
return;
const builder = new ElementGeometry.Builder();
builder.setLocalToWorldFromPlacement(this.curveData.props.placement!);
if (!builder.appendGeometryParamsChange(this.curveData.params))
return;
if (!builder.appendGeometryQuery(offset))
return;
return { format: "flatbuffer", data: builder.entries };
}
protected getElementProps(ev: BeButtonEvent): GeometricElementProps | undefined {
if (undefined === this.curveData)
return;
if (!this.wantModifyOriginal) {
// Create result as new element with same model and category as original...
const classFullName = (ev.viewport?.view.is3d() ? "Generic:PhysicalObject" : "BisCore:DrawingGraphic");
return { classFullName, model: this.curveData.props.model, category: this.curveData.props.category, code: Code.createEmpty(), placement: this.curveData.props.placement };
}
return this.curveData.props;
}
protected async applyAgendaOperation(ev: BeButtonEvent): Promise<boolean> {
const geometry = this.getGeometryProps(ev, true);
if (undefined === geometry)
return false;
const elemProps = this.getElementProps(ev);
if (undefined === elemProps)
return false;
if ("flatbuffer" === geometry.format)
elemProps.elementGeometryBuilderParams = { entryArray: geometry.data };
else
elemProps.geom = geometry.data;
try {
this._startedCmd = await this.startCommand();
if (undefined === elemProps.id) {
const repeatOperation = this.wantContinueWithPreviousResult;
if (repeatOperation)
this.agenda.clear();
const newId = await ModifyCurveTool.callCommand("insertGeometricElement", elemProps);
if (repeatOperation && this.agenda.add(newId))
await this.onAgendaModified();
} else {
await ModifyCurveTool.callCommand("updateGeometricElement", elemProps);
}
return true;
} catch (err) {
IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Error, BentleyError.getErrorMessage(err) || "An unknown error occurred."));
return false;
}
}
public override async processAgenda(ev: BeButtonEvent): Promise<void> {
if (await this.applyAgendaOperation(ev))
return this.saveChanges();
}
protected get wantModifyOriginal(): boolean { return true; }
protected get wantContinueWithPreviousResult(): boolean { return false; }
public override async onProcessComplete(): Promise<void> {
// Don't restart tool want to continue operation using previous result...
if (this.wantContinueWithPreviousResult && !this.agenda.isEmpty && undefined !== this.curveData)
return;
return super.onProcessComplete();
}
public override async onUnsuspend(): Promise<void> {
if (!this._firstResult)
this.updateAgendaAppearanceProvider();
return super.onUnsuspend();
}
public override async onSuspend(): Promise<void> {
if (!this._firstResult)
this.updateAgendaAppearanceProvider(true);
return super.onSuspend();
}
public override async onPostInstall(): Promise<void> {
await super.onPostInstall();
if (this.wantAgendaAppearanceOverride)
this.agenda.manageHiliteState = false;
}
public override async onCleanup(): Promise<void> {
this.clearGraphics();
this.updateAgendaAppearanceProvider(true);
return super.onCleanup();
}
}
/** @alpha Tool for applying an offset to paths and loops. */
export class OffsetCurveTool extends ModifyCurveTool {
public static override toolId = "OffsetCurve";
public static override iconSpec = "icon-scale"; // Need better icon...
protected override get wantAccuSnap(): boolean { return true; }
protected override get wantDynamics(): boolean { return true; }
private _useDistanceProperty: DialogProperty<boolean> | undefined;
public get useDistanceProperty() {
if (!this._useDistanceProperty)
this._useDistanceProperty = new DialogProperty<boolean>(PropertyDescriptionHelper.buildLockPropertyDescription("useOffsetDistance"), false);
return this._useDistanceProperty;
}
public get useDistance(): boolean { return this.useDistanceProperty.value; }
public set useDistance(value: boolean) { this.useDistanceProperty.value = value; }
private _distanceProperty: DialogProperty<number> | undefined;
public get distanceProperty() {
if (!this._distanceProperty)
this._distanceProperty = new DialogProperty<number>(new LengthDescription("offsetDistance", EditTools.translate("OffsetCurve.Label.Distance")), 0.1, undefined, !this.useDistance);
return this._distanceProperty;
}
public get distance(): number { return this.distanceProperty.value; }
public set distance(value: number) { this.distanceProperty.value = value; }
private _makeCopyProperty: DialogProperty<boolean> | undefined;
public get makeCopyProperty() {
if (!this._makeCopyProperty)
this._makeCopyProperty = new DialogProperty<boolean>(
PropertyDescriptionHelper.buildToggleDescription("offsetCopy", EditTools.translate("OffsetCurve.Label.MakeCopy")), false);
return this._makeCopyProperty;
}
public get makeCopy(): boolean { return this.makeCopyProperty.value; }
public set makeCopy(value: boolean) { this.makeCopyProperty.value = value; }
protected override getToolSettingPropertyLocked(property: DialogProperty<any>): DialogProperty<any> | undefined {
return (property === this.useDistanceProperty ? this.distanceProperty : undefined);
}
public override async applyToolSettingPropertyChange(updatedValue: DialogPropertySyncItem): Promise<boolean> {
return this.changeToolSettingPropertyValue(updatedValue);
}
public override supplyToolSettingsProperties(): DialogItem[] | undefined {
this.initializeToolSettingPropertyValues([this.makeCopyProperty, this.useDistanceProperty, this.distanceProperty]);
const toolSettings = new Array<DialogItem>();
// ensure controls are enabled/disabled based on current lock property state
this.distanceProperty.isDisabled = !this.useDistance;
const useDistanceLock = this.useDistanceProperty.toDialogItem({ rowPriority: 1, columnIndex: 0 });
toolSettings.push(this.distanceProperty.toDialogItem({ rowPriority: 1, columnIndex: 1 }, useDistanceLock));
toolSettings.push(this.makeCopyProperty.toDialogItem({ rowPriority: 2, columnIndex: 0 }));
return toolSettings;
}
protected override acceptCurve(curve: CurveCollection | CurvePrimitive): boolean {
if ("curvePrimitive" === curve.geometryCategory)
return true;
switch (curve.curveCollectionType) {
case "path":
case "loop":
return true;
default:
return false;
}
}
protected override modifyCurve(ev: BeButtonEvent, isAccept: boolean): CurveCollection | CurvePrimitive | undefined {
if (undefined === ev.viewport)
return undefined;
const geom = this.curveData?.geom;
if (undefined === geom)
return undefined;
const matrix = AccuDrawHintBuilder.getCurrentRotation(ev.viewport, true, true);
const localToWorld = FrameBuilder.createRightHandedFrame(matrix?.getColumn(2), geom);
if (undefined === localToWorld)
return undefined;
const worldToLocal = localToWorld.inverse();
if (undefined === worldToLocal)
return undefined;
const geomXY = ((geom instanceof CurvePrimitive) ? Path.create(geom) : geom).cloneTransformed(worldToLocal);
if (undefined === geomXY)
return undefined;
const spacePoint = AccuDrawHintBuilder.projectPointToPlaneInView(ev.point, localToWorld.getOrigin(), localToWorld.matrix.getColumn(2), ev.viewport);
if (undefined === spacePoint)
return undefined;
worldToLocal.multiplyPoint3d(spacePoint, spacePoint);
spacePoint.z = 0.0;
const closeDetail = geomXY.closestPoint(spacePoint);
if (undefined === closeDetail?.curve)
return undefined;
const unitZ = Vector3d.unitZ();
const unitX = closeDetail.curve.fractionToPointAndUnitTangent(closeDetail.fraction).direction;
const unitY = unitZ.unitCrossProduct(unitX);
if (undefined === unitY)
return undefined;
let distance = closeDetail.point.distance(spacePoint);
const refDir = Vector3d.createStartEnd(closeDetail.point, spacePoint);
if (refDir.dotProduct(unitY) < 0.0)
distance = -distance;
let offset = 0.0;
if (this.useDistance) {
offset = this.distance;
if ((offset < 0.0 && distance > 0.0) || (offset > 0.0 && distance < 0.0))
offset = -offset;
} else {
offset = distance;
}
if (Math.abs(offset) < Geometry.smallMetricDistance)
return undefined;
if (offset !== this.distance) {
this.distance = offset;
this.syncToolSettingPropertyValue(this.distanceProperty);
if (isAccept)
this.saveToolSettingPropertyValue(this.distanceProperty, this.distanceProperty.dialogItemValue);
}
const jointOptions = new JointOptions(offset);
jointOptions.preserveEllipticalArcs = true;
const offsetGeom = RegionOps.constructCurveXYOffset(geomXY as Path | Loop, jointOptions);
if (undefined === offsetGeom)
return undefined;
if (!offsetGeom.tryTransformInPlace(localToWorld))
return undefined;
if (geom instanceof CurvePrimitive && offsetGeom instanceof Path && 1 === offsetGeom.children.length)
return offsetGeom.getChild(0); // Don't create path for offset of single open curve...
return offsetGeom;
}
protected override get wantModifyOriginal(): boolean {
return !this.makeCopy;
}
protected override get wantContinueWithPreviousResult(): boolean {
return !this.wantModifyOriginal;
}
protected override setupAccuDraw(): void {
const hints = new AccuDrawHintBuilder();
if (this.agenda.isEmpty) {
hints.enableSmartRotation = true;
} else if (undefined !== this.anchorPoint && undefined !== this.targetView) {
const geom = this.curveData?.geom;
const closeDetail = (geom instanceof CurvePrimitive) ? geom.closestPoint(this.anchorPoint, false) : geom?.closestPoint(this.anchorPoint);
if (undefined !== closeDetail?.curve) {
const unitX = closeDetail.curve.fractionToPointAndUnitTangent(closeDetail.fraction).direction;
if (undefined !== unitX) {
const matrix = AccuDrawHintBuilder.getCurrentRotation(this.targetView, true, true);
const localToWorld = FrameBuilder.createRightHandedFrame(matrix?.getColumn(2), geom);
if (undefined !== localToWorld) {
const unitZ = localToWorld.matrix.getColumn(2);
const frame = Matrix3d.createRigidFromColumns(unitX, unitZ, AxisOrder.XZY);
if (undefined !== frame) {
hints.setOrigin(closeDetail.point);
hints.setMatrix(frame);
}
}
}
}
}
hints.sendHints(false);
}
protected override provideToolAssistance(_mainInstrText?: string, _additionalInstr?: ToolAssistanceInstruction[]): void {
let mainMsg;
if (!this.agenda.isEmpty)
mainMsg = EditTools.translate("OffsetCurve.Prompts.DefineOffset");
super.provideToolAssistance(mainMsg);
}
public async onRestartTool(): Promise<void> {
const tool = new OffsetCurveTool();
if (!await tool.run())
return this.exitTool();
}
}
/** @alpha Tool for opening loops and splitting paths. */
export class BreakCurveTool extends ModifyCurveTool {
public static override toolId = "BreakCurve";
public static override iconSpec = "icon-scale"; // Need better icon...
protected resultA?: CurveCollection | CurvePrimitive;
protected resultB?: CurveCollection | CurvePrimitive;
protected modifyOriginal = true;
protected override get wantAccuSnap(): boolean { return true; }
protected override get wantModifyOriginal(): boolean { return this.modifyOriginal; }
protected override acceptCurve(curve: CurveCollection | CurvePrimitive): boolean {
if ("curvePrimitive" === curve.geometryCategory)
return true;
switch (curve.curveCollectionType) {
case "path":
case "loop":
return true;
default:
return false;
}
}
protected doBreakCurve(ev: BeButtonEvent): void {
this.resultA = this.resultB = undefined;
if (undefined === ev.viewport)
return;
const geom = this.curveData?.geom;
if (undefined === geom)
return;
const closeDetail = (geom instanceof CurvePrimitive) ? geom.closestPoint(ev.point, false) : geom.closestPoint(ev.point);
if (undefined === closeDetail?.curve)
return;
const selectedStart = (closeDetail.fraction <= Geometry.smallFraction);
const selectedEnd = (closeDetail.fraction >= (1.0 - Geometry.smallFraction));
if (geom instanceof CurvePrimitive) {
if (selectedStart || selectedEnd)
return; // split is no-op...
this.resultA = geom.clonePartialCurve(0.0, closeDetail.fraction);
this.resultB = geom.clonePartialCurve(closeDetail.fraction, 1.0);
return;
} else if (geom instanceof Path) {
const firstCurve = geom.children[0];
const lastCurve = geom.children[geom.children.length-1];
if ((closeDetail.curve === firstCurve && selectedStart) || (closeDetail.curve === lastCurve && selectedEnd))
return; // split is no-op...
let beforeCurve = true;
const resultA = Path.create();
const resultB = Path.create();
for (const curve of geom.children) {
if (curve === closeDetail.curve) {
if (selectedStart) {
resultB.children.push(curve.clone());
} else if (selectedEnd) {
resultA.children.push(curve.clone());
} else {
const curveA = curve.clonePartialCurve(0.0, closeDetail.fraction);
if (undefined !== curveA)
resultA.children.push(curveA);
const curveB = curve.clonePartialCurve(closeDetail.fraction, 1.0);
if (undefined !== curveB)
resultB.children.push(curveB);
}
beforeCurve = false;
} else {
if (beforeCurve)
resultA.children.push(curve.clone());
else
resultB.children.push(curve.clone());
}
}
this.resultA = resultA;
this.resultB = resultB;
} else if (geom instanceof Loop) {
const closeIndex = geom.children.findIndex((child) => child === closeDetail.curve);
if (-1 === closeIndex)
return;
const endIndex = closeIndex + geom.children.length;
const resultA = Path.create(); // Result is always a single path...
if (selectedStart) {
resultA.children.push(closeDetail.curve.clone());
} else if (!selectedEnd) {
const curveB = closeDetail.curve.clonePartialCurve(closeDetail.fraction, 1.0);
if (undefined !== curveB)
resultA.children.push(curveB);
}
for (let index = closeIndex; index < endIndex; ++index) {
const curve = geom.cyclicCurvePrimitive(index);
if (undefined === curve || curve === closeDetail.curve)
continue;
resultA.children.push(curve.clone());
}
if (selectedEnd) {
resultA.children.push(closeDetail.curve.clone());
} else if (!selectedStart) {
const curveA = closeDetail.curve.clonePartialCurve(0.0, closeDetail.fraction);
if (undefined !== curveA)
resultA.children.push(curveA);
}
this.resultA = resultA;
}
}
protected override modifyCurve(_ev: BeButtonEvent, _isAccept: boolean): CurveCollection | CurvePrimitive | undefined {
return (this.wantModifyOriginal ? this.resultA : this.resultB);
}
public override async processAgenda(ev: BeButtonEvent): Promise<void> {
this.doBreakCurve(ev);
if (undefined === this.resultA || !await this.applyAgendaOperation(ev))
return;
if (undefined !== this.resultB) {
this.modifyOriginal = false;
await this.applyAgendaOperation(ev);
}
return this.saveChanges();
}
protected override provideToolAssistance(_mainInstrText?: string, _additionalInstr?: ToolAssistanceInstruction[]): void {
let mainMsg;
if (this.agenda.isEmpty)
mainMsg = EditTools.translate("BreakCurve.Prompts.IdentifyBreak");
super.provideToolAssistance(mainMsg);
}
public async onRestartTool(): Promise<void> {
const tool = new BreakCurveTool();
if (!await tool.run())
return this.exitTool();
}
}
/** @alpha Tool for extending/shortening curves. */
export class ExtendCurveTool extends ModifyCurveTool {
public static override toolId = "ExtendCurve";
public static override iconSpec = "icon-scale"; // Need better icon...
protected override get wantAccuSnap(): boolean { return true; }
protected override get wantDynamics(): boolean { return true; }
protected override get wantAgendaAppearanceOverride(): boolean { return true; }
protected override acceptCurve(curve: CurveCollection | CurvePrimitive): boolean {
if ("curvePrimitive" !== curve.geometryCategory)
return false;
return curve.isExtensibleFractionSpace;
}
protected override modifyCurve(ev: BeButtonEvent, _isAccept: boolean): CurveCollection | CurvePrimitive | undefined {
if (undefined === ev.viewport || undefined === this.anchorPoint)
return undefined;
const geom = this.curveData?.geom;
if (undefined === geom)
return undefined;
const matrix = AccuDrawHintBuilder.getCurrentRotation(ev.viewport, true, true);
const localToWorld = FrameBuilder.createRightHandedFrame(matrix?.getColumn(2), geom);
if (undefined === localToWorld)
return undefined;
const worldToLocal = localToWorld.inverse();
if (undefined === worldToLocal)
return undefined;
const spacePoint = AccuDrawHintBuilder.projectPointToPlaneInView(ev.point, localToWorld.getOrigin(), localToWorld.matrix.getColumn(2), ev.viewport);
if (undefined === spacePoint)
return undefined;
const pickDetail = geom.closestPoint(this.anchorPoint, false);
if (undefined === pickDetail?.curve)
return undefined;
const closeDetail = geom.closestPoint(spacePoint, true);
if (undefined === closeDetail?.curve)
return undefined;
if (closeDetail.curve instanceof Arc3d) {
if (pickDetail.fraction > 0.5 && closeDetail.fraction < 0.0) {
const smallArc = closeDetail.curve.clonePartialCurve(closeDetail.fraction, 0.0);
smallArc.sweep.cloneComplement(false, smallArc.sweep);
return smallArc;
} else if (pickDetail.fraction <= 0.5 && closeDetail.fraction > 1.0) {
const smallArc = closeDetail.curve.clonePartialCurve(1.0, closeDetail.fraction);
smallArc.sweep.cloneComplement(false, smallArc.sweep);
return smallArc;
} else if (Math.abs(pickDetail.fraction > 0.5 ? closeDetail.fraction : 1.0 - closeDetail.fraction) < Geometry.smallFraction) {
const fullArc = closeDetail.curve.clone();
fullArc.sweep = AngleSweep.create360();
return fullArc;
}
}
return closeDetail.curve.clonePartialCurve(pickDetail.fraction > 0.5 ? 0.0 : 1.0, closeDetail.fraction);
}
protected override setupAccuDraw(): void {
const hints = new AccuDrawHintBuilder();
if (this.agenda.isEmpty) {
hints.enableSmartRotation = true;
} else {
const geom = this.curveData?.geom;
if (undefined === geom || "curvePrimitive" !== geom.geometryCategory)
return;
if (geom instanceof Arc3d) {
const matrix = geom.matrixClone();
matrix.normalizeColumnsInPlace();
hints.setOrigin(geom.center);
hints.setMatrix(matrix);
hints.setModePolar();
} else if (geom instanceof LineSegment3d) {
const pickDetail = (undefined !== this.anchorPoint ? geom.closestPoint(this.anchorPoint, false) : undefined);
if (undefined !== pickDetail?.curve) {
hints.setOrigin(pickDetail.fraction > 0.5 ? geom.point0Ref : geom.point1Ref);
hints.setXAxis(Vector3d.createStartEnd(pickDetail.fraction > 0.5 ? geom.point0Ref : geom.point1Ref, pickDetail.fraction > 0.5 ? geom.point1Ref : geom.point0Ref));
}
hints.setModeRectangular();
} else if (geom instanceof LineString3d) {
const pickDetail = (undefined !== this.anchorPoint ? geom.closestPoint(this.anchorPoint, false) : undefined);
if (undefined !== pickDetail?.curve && geom.numPoints() > 1) {
hints.setOrigin(geom.packedPoints.getPoint3dAtUncheckedPointIndex(pickDetail.fraction > 0.5 ? geom.numPoints()-2 : 1));
hints.setXAxis(Vector3d.createStartEnd(geom.packedPoints.getPoint3dAtUncheckedPointIndex(pickDetail.fraction > 0.5 ? geom.numPoints()-2 : 1), geom.packedPoints.getPoint3dAtUncheckedPointIndex(pickDetail.fraction > 0.5 ? geom.numPoints()-1 : 0)));
}
hints.setModeRectangular();
}
}
hints.sendHints(false);
}
protected override provideToolAssistance(_mainInstrText?: string, _additionalInstr?: ToolAssistanceInstruction[]): void {
let mainMsg;
if (this.agenda.isEmpty)
mainMsg = EditTools.translate("ExtendCurve.Prompts.IdentifyEnd");
super.provideToolAssistance(mainMsg);
}
public async onRestartTool(): Promise<void> {
const tool = new ExtendCurveTool();
if (!await tool.run())
return this.exitTool();
}
} | the_stack |
import {Core} from "./Core";
import {Model} from "./Model";
import {Plugin} from "./Plugins";
import {CacheDirector} from "./CacheDirector";
import * as General from "./General";
import * as ModelInterfaces from "./ModelInterfaces";
import * as Index from "./Index";
import {Schema} from "./Schema";
import {Transforms} from "./Transforms";
import {DefaultValidators} from "./Validators";
import {Conditions} from "./Conditions";
import {Changes} from "./Changes";
import * as MapReduce from "./MapReduce";
import * as _ from "lodash";
import * as MongoDB from "mongodb";
import * as Bluebird from "bluebird";
import * as Skmatc from "skmatc";
/**
* The default Iridium Instance implementation which provides methods for saving, refreshing and
* removing the wrapped document from the collection, as well as integrating with Omnom, our
* built in document diff processor which allows clean, atomic, document updates to be performed
* without needing to write the update queries yourself.
*
* @param {any} TDocument The interface representing the structure of the documents in the collection.
* @param {any} TInstance The type of instance which wraps the documents, generally the subclass of this class.
*
* This class will be subclassed automatically by Iridium to create a model specific instance
* which takes advantage of some of v8's optimizations to boost performance significantly.
* The instance returned by the model, and all of this instance's methods, will be of type
* TInstance - which should represent the merger of TSchema and IInstance for best results.
*/
export class Instance<TDocument extends { _id?: any }, TInstance> {
/**
* Creates a new instance which represents the given document as a type of model
* @param {Model} model The model that dictates the collection the document originated from as well as how validations are performed.
* @param {Object} document The document which should be wrapped by this instance
* @param {Boolean} [isNew] Whether the document is new (doesn't exist in the database) or not
* @param {Boolean} [isPartial] Whether the document has only a subset of its fields populated
*
*/
constructor(model: Model<TDocument, TInstance>, document: TDocument, isNew: boolean = true, isPartial: boolean = false) {
this._model = model;
this._isNew = !!isNew;
this._isPartial = isPartial;
this._original = document;
this._modified = model.helpers.cloneDocument(document);
_.each(model.core.plugins, (plugin: Plugin) => {
if (plugin.newInstance) plugin.newInstance(this, model);
});
}
private _isNew: boolean;
private _isPartial: boolean;
private _model: Model<TDocument, TInstance>;
private _original: TDocument;
private _modified: TDocument;
/**
* Gets the underlying document representation of this instance
*/
get document(): TDocument {
return this._modified;
}
[name: string]: any;
/**
* A function which is called whenever a new document is in the process of being inserted into the database.
* @param {Object} document The document which will be inserted into the database.
*/
static onCreating: (document: { _id?: any }) => Promise<any> | PromiseLike<any> | void;
/**
* A function which is called whenever a document of this type is received from the database, prior to it being
* wrapped by an Instance object.
* @param {Object} document The document that was retrieved from the database.
*/
static onRetrieved: (document: { _id?: any }) => Promise<any> | PromiseLike<any> | void;
/**
* A function which is called whenever a new instance has been created to wrap a document.
* @param {Instance} instance The instance which has been created.
*/
static onReady: (instance: Instance<{ _id?: any }, Instance<{ _id?: any }, any>>) => Promise<any> | PromiseLike<any> | void;
/**
* A function which is called whenever an instance's save() method is called to allow you to interrogate and/or manipulate
* the changes which are being made.
*
* @param {Instance} instance The instance to which the changes are being made
* @param {Object} changes The MongoDB change object describing the changes being made to the document.
*/
static onSaving: (instance: Instance<{ _id?: any }, Instance<{ _id?: any }, any>>, changes: Changes) => Promise<any> | PromiseLike<any> | void;
/**
* The name of the collection into which documents of this type are stored.
*/
static collection: string;
/**
* The schema used to validate documents of this type before being stored in the database.
*/
static schema: Schema = {
_id: false
};
/**
* Additional which should be made available for use in the schema definition for this instance.
*/
static validators: Skmatc.Validator[] = DefaultValidators();
/**
* The transformations which should be applied to properties of documents of this type.
*/
static transforms: Transforms = {
};
/**
* The cache director used to derive unique cache keys for documents of this type.
*/
static cache: CacheDirector;
/**
* The indexes which should be managed by Iridium for the collection used by this type.
*/
static indexes: (Index.Index | Index.IndexSpecification)[] = [];
/**
* mapReduce Options
*/
static mapReduceOptions?: MapReduce.MapReduceFunctions<any,any,any>;
/**
* Saves any changes to this instance, using the built in diff algorithm to write the update query.
* @param {function} callback A callback which is triggered when the save operation completes
* @returns {Promise}
*/
save(callback?: General.Callback<TInstance>): Bluebird<TInstance>;
/**
* Saves the given changes to this instance and updates the instance to match the latest database document.
* @param {Object} changes The MongoDB changes object to be used when updating this instance
* @param {function} callback A callback which is triggered when the save operation completes
* @returns {Promise}
*/
save(changes: Changes, callback?: General.Callback<TInstance>): Bluebird<TInstance>;
/**
* Saves the given changes to this instance and updates the instance to match the latest database document.
* @param {Object} conditions The conditions under which the update will take place - these will be merged with an _id query
* @param {Object} changes The MongoDB changes object to be used when updating this instance
* @param {function} callback A callback which is triggered when the save operation completes
* @returns {Promise}
*/
save(conditions: Conditions, changes: Changes, callback?: General.Callback<TInstance>): Bluebird<TInstance>;
save(...args: any[]): Bluebird<TInstance> {
let callback: General.Callback<any>|undefined = undefined;
let changes: any = null;
let conditions: any = {};
Array.prototype.slice.call(args, 0).reverse().forEach((arg: General.Callback<any>|Object) => {
if (typeof arg == "function") callback = arg;
else if (typeof arg == "object") {
if (!changes) changes = arg;
else conditions = arg;
}
});
return Bluebird.resolve().then(() => {
conditions = this._model.helpers.cloneConditions(conditions);
_.merge(conditions, { _id: this._modified._id });
if (!changes) {
let validation = this._model.helpers.validate(this._modified);
if (validation.failed) return Bluebird.reject(validation.error).bind(this).nodeify(callback);
let original = this._model.helpers.cloneDocument(this._original);
let modified = this._model.helpers.cloneDocument(this._modified);
modified = this._model.helpers.transformToDB(modified, { document: true });
changes = this._model.helpers.diff(original, modified);
}
if (!_.keys(changes).length) return null;
return changes;
}).then((changes) => {
if (!changes && !this._isNew) return changes;
return this._model.handlers.savingDocument(<TInstance><any>this, changes).then(() => changes);
}).then((changes) => {
if (!changes && !this._isNew) return false;
if (this._isNew) {
return new Bluebird<boolean>((resolve, reject) => {
this._model.collection.insertOne(this._modified, { w: "majority" }, (err, doc) => {
if (err) return reject(err);
return resolve(<any>!!doc);
});
});
} else {
return new Bluebird<boolean>((resolve, reject) => {
this._model.collection.updateOne(conditions, changes, { w: "majority" }, (err, changed) => {
if(err) {
(<Error&{conditions: Object}>err)["conditions"] = conditions;
(<Error&{changes: Object}>err)["changes"] = changes;
return reject(err);
}
return resolve(!!changed.modifiedCount);
});
});
}
}).catch(err => {
err["original"] = this._original;
err["modified"] = this._modified;
return Bluebird.reject(err);
}).then((changed: boolean) => {
conditions = { _id: this._modified._id };
if (!changed) return this._modified;
return new Bluebird<TDocument>((resolve, reject) => {
this._model.collection.find(conditions).limit(1).next((err: Error, latest: TDocument) => {
if (err) return reject(err);
return resolve(latest);
});
});
}).then((latest: TDocument) => {
if(!latest) {
this._isNew = true;
this._original = this._model.helpers.cloneDocument(this._modified);
return Bluebird.resolve(<TInstance><any>this);
}
return this._model.handlers.documentReceived(conditions, latest, (value) => {
this._isPartial = false;
this._isNew = false;
this._modified = value;
this._original = this._model.helpers.cloneDocument(value);
return <TInstance><any>this;
});
}).nodeify(callback);
}
/**
* Updates this instance to match the latest document available in the backing collection
* @param {function(Error, IInstance)} callback A callback which is triggered when the update completes
* @returns {Promise<TInstance>}
*/
update(callback?: General.Callback<TInstance>): Bluebird<TInstance> {
return this.refresh(callback);
}
/**
* Updates this instance to match the latest document available in the backing collection
* @param {function(Error, IInstance)} callback A callback which is triggered when the update completes
* @returns {Promise<TInstance>}
*/
refresh(callback?: General.Callback<TInstance>): Bluebird<TInstance> {
let conditions = { _id: this._original._id };
return Bluebird.resolve().then(() => {
return new Bluebird<TDocument>((resolve, reject) => {
this._model.collection.find(conditions).limit(1).next((err: Error, doc: any) => {
if (err) return reject(err);
return resolve(doc);
});
});
}).then((newDocument) => {
if (!newDocument) {
this._isPartial = true;
this._isNew = true;
this._original = this._model.helpers.cloneDocument(this._modified);
return <Bluebird<TInstance>><any>this;
}
return this._model.handlers.documentReceived(conditions, newDocument, (doc) => {
this._isNew = false;
this._isPartial = false;
this._original = doc;
this._modified = this._model.helpers.cloneDocument(doc);
return <TInstance><any>this;
});
}).nodeify(callback);
}
/**
* Removes this instance's document from the backing collection
* @param {function(Error, IInstance)} callback A callback which is triggered when the operation completes
* @returns {Promise<TInstance>}
*/
delete(callback?: General.Callback<TInstance>): Bluebird<TInstance> {
return this.remove(callback);
}
/**
* Removes this instance's document from the backing collection
* @param {function(Error, IInstance)} callback A callback which is triggered when the operation completes
* @returns {Promise<TInstance>}
*/
remove(callback?: General.Callback<TInstance>): Bluebird<TInstance> {
let conditions = { _id: this._original._id };
return Bluebird.resolve().then(() => {
if (this._isNew) return 0;
return new Bluebird<number>((resolve, reject) => {
this._model.collection.deleteOne(conditions, { w: "majority" }, (err: Error, removed?: any) => {
if (err) return reject(err);
return resolve(removed);
});
});
}).then((removed) => {
if (removed) return this._model.cache.clear(conditions);
return false;
}).then(() => {
this._isNew = true;
return <TInstance><any>this;
}).nodeify(callback);
}
/**
* Retrieves the first element in an enumerable collection which matches the predicate
* @param collection The collection from which to retrieve the element
* @param predicate The function which determines whether to select an element
* @returns The first element in the array which matched the predicate.
*/
first<T>(collection: T[], predicate: General.Predicate<this, T>): T|null;
/**
* Retrieves the first element in an enumerable collection which matches the predicate
* @param collection The collection from which to retrieve the element
* @param predicate The function which determines whether to select an element
* @returns The first element in the object which matched the predicate.
*/
first<T>(collection: { [key: string]: T }, predicate: General.Predicate<this, T>): T|null;
first<T>(collection: T[]| { [key: string]: T }, predicate: General.Predicate<this, T>): T|null {
let result: T|null = null;
_.each(collection, (value: T, key: string) => {
if (predicate.call(this, value, key)) {
result = value;
return false;
}
});
return result;
}
/**
* Retrieves a number of elements from an enumerable collection which match the predicate
* @param collection The collection from which elements will be plucked
* @param predicate The function which determines the elements to be plucked
* @returns A new array containing the elements in the array which matched the predicate.
*/
select<T>(collection: T[], predicate: General.Predicate<this, T>): T[];
/**
* Retrieves a number of elements from an enumerable collection which match the predicate
* @param collection The collection from which elements will be plucked
* @param predicate The function which determines the elements to be plucked
* @returns An object with the properties from the collection which matched the predicate.
*/
select<T>(collection: { [key: string]: T }, predicate: General.Predicate<this, T>): { [key: string]: T };
select<T>(collection: T[]| { [key: string]: T }, predicate: General.Predicate<this, T>): any {
let isArray = Array.isArray(collection);
let results: any = isArray ? [] : {};
_.each(collection, (value: T, key: string) => {
if (predicate.call(this, value, key)) {
if (isArray) results.push(value);
else results[key] = value;
}
});
return results;
}
/**
* Gets the JSON representation of this instance
* @returns {TDocument}
*/
toJSON(): any {
return this.document;
}
/**
* Gets a string representation of this instance
* @returns {String}
*/
toString(): string {
return JSON.stringify(this.document, null, 2);
}
} | the_stack |
import * as webpack from 'webpack'
import * as path from 'path'
import * as autoprefixer from 'autoprefixer'
import * as postcssPluginPx2rem from 'postcss-plugin-px2rem'
import * as weexVuePrecompiler from 'weex-vue-precompiler'
import * as webpackMerge from 'webpack-merge'
import * as postcssPluginWeex from 'postcss-plugin-weex'
import * as UglifyJsPlugin from 'uglifyjs-webpack-plugin'
import * as os from 'os'
import * as fse from 'fs-extra'
import * as DEBUG from 'debug'
import { exist } from './utils'
import { vueLoader } from './vueLoader'
import WebpackBuilder from './WebpackBuilder'
const debug = DEBUG('weex:compile')
export class WeexBuilder extends WebpackBuilder {
private vueTemplateFloder: string = '.temp'
private defaultWeexConfigName: string = 'weex.config.js'
private entryFileName: string = 'entry.js'
private routerFileName: string = 'router.js'
private pluginFileName: string = 'plugins/plugins.js'
private pluginConfigFileName: string = 'plugins/plugins.json'
private isWin: boolean = /^win/.test(process.platform)
private isSigleWebRender: boolean = false
constructor(source: string, dest: string, options: any) {
super(source, dest, options)
}
private nodeConfiguration: any = {
global: false,
Buffer: false,
__filename: false,
__dirname: false,
setImmediate: false,
clearImmediate: false,
// see: https://github.com/webpack/node-libs-browser
assert: false,
buffer: false,
child_process: false,
cluster: false,
console: false,
constants: false,
crypto: false,
dgram: false,
dns: false,
domain: false,
events: false,
fs: false,
http: false,
https: false,
module: false,
net: false,
os: false,
path: false,
process: false,
punycode: false,
querystring: false,
readline: false,
repl: false,
stream: false,
string_decoder: false,
sys: false,
timers: false,
tls: false,
tty: false,
url: false,
util: false,
vm: false,
zlib: false,
}
async resolveConfig() {
const destExt = path.extname(this.dest)
const sourceExt = path.extname(this.rawSource)
let outputPath
let outputFilename
const plugins = [
/*
* Plugin: BannerPlugin
* Description: Adds a banner to the top of each generated chunk.
* See: https://webpack.js.org/plugins/banner-plugin/
*/
new webpack.BannerPlugin({
banner: '// { "framework": "Vue"}\n',
raw: true,
exclude: 'Vue',
}),
/**
* Plugin: webpack.DefinePlugin
* Description: The DefinePlugin allows you to create global constants which can be configured at compile time.
*
* See: https://webpack.js.org/plugins/define-plugin/
*/
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(this.options.prod ? 'production' : 'development'),
},
}),
]
// ./bin/weex-builder.js test dest --filename=[name].web.js
if (this.options.filename) {
outputFilename = this.options.filename
} else {
outputFilename = '[name].js'
}
// Call like: ./bin/weex-builder.js test/index.vue dest/test.js
// Need to rename the filename of
if (destExt && this.dest[this.dest.length - 1] !== '/' && sourceExt) {
outputPath = path.dirname(this.dest)
outputFilename = path.basename(this.dest)
} else {
outputPath = this.dest
}
if (this.options.onProgress) {
plugins.push(new webpack.ProgressPlugin(this.options.onProgress))
}
const hasVueRouter = (content: string) => {
return /(\.\/)?router/.test(content)
}
const getEntryFileContent = (source, routerpath) => {
const hasPluginInstalled = fse.existsSync(path.resolve(this.pluginFileName))
let dependence = `import Vue from 'vue'\n`
dependence += `import weex from 'weex-vue-render'\n`
let relativePluginPath = path.resolve(this.pluginConfigFileName)
let entryContents = fse.readFileSync(source).toString()
let contents = ''
entryContents = dependence + entryContents
entryContents = entryContents.replace(/\/\* weex initialized/, match => `weex.init(Vue)\n${match}`)
if (this.isWin) {
relativePluginPath = relativePluginPath.replace(/\\/g, '\\\\')
}
if (hasPluginInstalled) {
contents += `\n// If detact plugins/plugin.js is exist, import and the plugin.js\n`
contents += `import plugins from '${relativePluginPath}';\n`
contents += `plugins.forEach(function (plugin) {\n\tweex.install(plugin)\n});\n\n`
entryContents = entryContents.replace(/\.\/router/, routerpath)
entryContents = entryContents.replace(/weex\.init/, match => `${contents}${match}`)
}
return entryContents
}
const getRouterFileContent = source => {
const dependence = `import Vue from 'vue'\n`
let routerContents = fse.readFileSync(source).toString()
routerContents = dependence + routerContents
return routerContents
}
const getWebRouterEntryFile = (entry: string, router: string) => {
const entryFile = path.resolve(this.vueTemplateFloder, this.entryFileName)
const routerFile = path.resolve(this.vueTemplateFloder, this.routerFileName)
fse.outputFileSync(entryFile, getEntryFileContent(entry, routerFile))
fse.outputFileSync(routerFile, getRouterFileContent(router))
return {
index: entryFile,
}
}
// Wraping the entry file for web.
const getWebEntryFileContent = (entryPath: string, vueFilePath: string, base: string) => {
const hasPluginInstalled = fse.existsSync(path.resolve(this.pluginFileName))
let relativeVuePath = path.relative(path.join(entryPath, '../'), vueFilePath)
let relativeEntryPath = path.resolve(base, this.entryFileName)
let relativePluginPath = path.resolve(this.pluginConfigFileName)
let contents = ''
let entryContents = ''
if (fse.existsSync(relativeEntryPath)) {
entryContents = fse.readFileSync(relativeEntryPath, 'utf8')
}
if (this.isWin) {
relativeVuePath = relativeVuePath.replace(/\\/g, '\\\\')
relativePluginPath = relativePluginPath.replace(/\\/g, '\\\\')
}
if (hasPluginInstalled) {
contents += `\n// If detact plugins/plugin.js is exist, import and the plugin.js\n`
contents += `import plugins from '${relativePluginPath}';\n`
contents += `plugins.forEach(function (plugin) {\n\tweex.install(plugin)\n});\n\n`
entryContents = entryContents.replace(/weex\.init/, match => `${contents}${match}`)
contents = ''
}
contents += `
const App = require('${relativeVuePath}');
new Vue(Vue.util.extend({el: '#root'}, App));
`
return entryContents + contents
}
// Wraping the entry file for native.
const getWeexEntryFileContent = (entryPath: string, vueFilePath: string) => {
let relativeVuePath = path.relative(path.join(entryPath, '../'), vueFilePath)
let contents = ''
if (this.isWin) {
relativeVuePath = relativeVuePath.replace(/\\/g, '\\\\')
}
contents += `import App from '${relativeVuePath}'
App.el = '#root'
new Vue(App)
`
return contents
}
const getNormalEntryFile = (entries: string[], base: string, isweb: boolean): any => {
let result = {}
entries.forEach(entry => {
const extname = path.extname(entry)
const basename = entry.replace(`${base}${this.isWin ? '\\' : '/'}`, '').replace(extname, '')
const templatePathForWeb = path.resolve(this.vueTemplateFloder, basename + '.web.js')
const templatePathForNative = path.resolve(this.vueTemplateFloder, basename + '.js')
if (isweb) {
fse.outputFileSync(templatePathForWeb, getWebEntryFileContent(templatePathForWeb, entry, base))
result[basename] = templatePathForWeb
} else {
fse.outputFileSync(templatePathForNative, getWeexEntryFileContent(templatePathForNative, entry))
result[basename] = templatePathForNative
}
})
return result
}
const resolveSourceEntry = async (source: string[], base: string, options: any) => {
const entryFile = path.join(base, this.entryFileName)
const routerFile = path.join(base, this.routerFileName)
const existEntry = await fse.pathExists(entryFile)
let entrys: any = {}
if (existEntry) {
const content = await fse.readFile(entryFile, 'utf8')
if (hasVueRouter(content)) {
if (options.web) {
entrys = getWebRouterEntryFile(entryFile, routerFile)
} else {
entrys = {
index: entryFile,
}
}
} else {
entrys = getNormalEntryFile(source, base, options.web)
}
} else {
this.isSigleWebRender = true
entrys = getNormalEntryFile(source, base, options.web)
}
return entrys
}
const webpackConfig = async () => {
const entrys = await resolveSourceEntry(this.source, this.base, this.options)
let configs: any = {
entry: entrys,
output: {
path: outputPath,
filename: outputFilename,
},
watch: this.options.watch || false,
watchOptions: {
aggregateTimeout: 300,
ignored: /\.temp/,
},
devtool: this.options.devtool || 'eval-source-map',
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'@': this.base || path.resolve('src'),
},
},
/*
* Options affecting the resolving of modules.
*
* See: http://webpack.github.io/docs/configuration.html#module
*/
module: {
rules: [
{
test: /\.js$/,
use: [
{
loader: 'babel-loader',
options: {
presets: [
path.join(__dirname, '../node_modules/babel-preset-es2015'),
path.join(__dirname, '../node_modules/babel-preset-stage-0'),
],
},
},
],
},
{
test: /\.we$/,
use: [
{
loader: 'weex-loader',
},
],
},
],
},
/**
* See: https://webpack.js.org/configuration/resolve/#resolveloader
*/
resolveLoader: {
modules: [path.join(__dirname, '../node_modules'), path.resolve('node_modules')],
extensions: ['.js', '.json'],
mainFields: ['loader', 'main'],
moduleExtensions: ['-loader'],
},
/*
* Add additional plugins to the compiler.
*
* See: http://webpack.github.io/docs/configuration.html#plugins
*/
plugins: plugins,
}
if (this.options.web) {
configs.module.rules.push({
test: /\.vue(\?[^?]+)?$/,
use: [
{
loader: 'vue-loader',
options: Object.assign(vueLoader({ useVue: true, usePostCSS: false }), {
/**
* important! should use postTransformNode to add $processStyle for
* inline style prefixing.
*/
optimizeSSR: false,
postcss: [
// to convert weex exclusive styles.
postcssPluginWeex(),
autoprefixer({
browsers: ['> 0.1%', 'ios >= 8', 'not ie < 12'],
}),
postcssPluginPx2rem({
// base on 750px standard.
rootValue: 75,
// to leave 1px alone.
minPixelValue: 1.01,
}),
],
compilerModules: [
{
postTransformNode: el => {
// to convert vnode for weex components.
weexVuePrecompiler()(el)
},
},
],
}),
},
],
})
} else {
configs.module.rules.push({
test: /\.(we|vue)(\?[^?]+)?$/,
use: [
{
loader: 'weex-loader',
options: vueLoader({ useVue: false }),
},
],
})
configs.node = this.nodeConfiguration
}
if (this.options.min) {
/*
* Plugin: UglifyJsPlugin
* Description: Minimize all JavaScript output of chunks.
* Loaders are switched into minimizing mode.
*
* See: https://webpack.js.org/configuration/optimization/#optimization-minimizer
*/
configs.plugins.unshift(
new UglifyJsPlugin({
sourceMap: true,
parallel: os.cpus().length - 1,
}),
)
}
return configs
}
let config = await webpackConfig()
return config
}
async build(callback) {
let configs = await this.resolveConfig()
debug(this.options.web ? 'web -->' : 'weex -->', JSON.stringify(configs, null, 2))
let mergeConfigs
if (this.source.length === 0) {
return callback('no ' + (this.options.ext || '') + ' files found in source "' + this.rawSource + '"')
}
if (this.options.config) {
if (exist(this.options.config)) {
try {
mergeConfigs = require(path.resolve(this.options.config))
if (mergeConfigs.web && this.options.web) {
configs = webpackMerge(configs, mergeConfigs.web)
} else if (mergeConfigs.weex && !this.options.web) {
configs = webpackMerge(configs, mergeConfigs.weex)
} else if (!mergeConfigs.web && !mergeConfigs.weex) {
configs = webpackMerge(configs, mergeConfigs)
}
} catch (e) {
debug('read config error --> ', e)
}
}
} else {
let defatultConfig = path.resolve(this.defaultWeexConfigName)
if (exist(defatultConfig)) {
try {
mergeConfigs = require(path.resolve(defatultConfig))
if (mergeConfigs.web && this.options.web) {
configs = webpackMerge(configs, mergeConfigs.web)
} else if (mergeConfigs.weex && !this.options.web) {
configs = webpackMerge(configs, mergeConfigs.weex)
} else if (!mergeConfigs.web && !mergeConfigs.weex) {
configs = webpackMerge(configs, mergeConfigs)
}
} catch (e) {
debug('read config error --> ', e)
}
}
}
if (this.options.outputConfig) {
console.log(JSON.stringify(configs, null, 2))
}
const compiler = webpack(configs)
const formatResult = (err, stats) => {
const result = {
toString: () =>
stats.toString({
// Add warnings
warnings: false,
// Add webpack version information
version: false,
// Add the hash of the compilation
hash: false,
// Add asset Information
assets: true,
modules: false,
// Add built modules information to chunk information
chunkModules: false,
// Add the origins of chunks and chunk merging info
chunkOrigins: false,
children: false,
// Makes the build much quieter
chunks: false,
// Shows colors in the console
colors: true,
}),
}
if (err) {
console.error(err.stack || err)
if (err.details) {
console.error(err.details)
}
return callback && callback(err)
}
const info = stats.toJson()
if (stats.hasErrors()) {
return callback && callback(info.errors)
}
// use for preview module
info['isSigleWebRender'] = this.isSigleWebRender
callback && callback(err, result, info)
}
if (configs.watch) {
compiler.watch(
{
ignored: /node_modules/,
poll: 1000,
},
formatResult,
)
} else {
compiler.run(formatResult)
}
}
}
export default WeexBuilder | the_stack |
import { PdfFont } from './pdf-font';
import { PdfStringFormat } from './pdf-string-format';
import { SizeF, RectangleF, PointF } from './../../drawing/pdf-drawing';
import { PdfWordWrapType } from './enum';
import { StringTokenizer } from './string-tokenizer';
/**
* Class `lay outing the text`.
*/
export class PdfStringLayouter {
// Fields
/**
* `Text` data.
* @private
*/
private text : string;
/**
* Pdf `font`.
* @private
*/
private font : PdfFont;
/**
* String `format`.
* @private
*/
private format : PdfStringFormat;
/**
* `Size` of the text.
* @private
*/
private size : SizeF;
/**
* `Bounds` of the text.
* @private
*/
private rectangle : RectangleF;
/**
* Pdf page `height`.
* @private
*/
private pageHeight : number;
/**
* String `tokenizer`.
* @private
*/
private reader : StringTokenizer;
/**
* Specifies if [`isTabReplaced`].
* @private
*/
private isTabReplaced : boolean;
/**
* Count of tab `occurance`.
* @private
*/
private tabOccuranceCount : number;
/**
* Checks whether the x co-ordinate is need to set as client size or not.
* @hidden
* @private
*/
private isOverloadWithPosition : boolean = false;
/**
* Stores client size of the page if the layout method invoked with `PointF` overload.
* @hidden
* @private
*/
private clientSize : SizeF;
// Constructors
/**
* Initializes a new instance of the `StringLayouter` class.
* @private
*/
public constructor() {
//
}
//Public methods
/**
* `Layouts` the text.
* @private
*/
public layout(text : string, font : PdfFont, format : PdfStringFormat, rectangle : RectangleF,
pageHeight : number, recalculateBounds : boolean, clientSize : SizeF) : PdfStringLayoutResult
public layout(text : string, font : PdfFont, format : PdfStringFormat, size : SizeF,
recalculateBounds : boolean, clientSize : SizeF) : PdfStringLayoutResult
public layout(arg1 : string, arg2 : PdfFont, arg3 : PdfStringFormat, arg4 : SizeF|RectangleF,
arg5 : number | boolean, arg6 : boolean | SizeF, arg7 ?: SizeF) : PdfStringLayoutResult {
if (arg4 instanceof RectangleF) {
this.initialize(arg1, arg2, arg3, <RectangleF>arg4, arg5 as number);
this.isOverloadWithPosition = arg6 as boolean;
this.clientSize = arg7 as SizeF;
let result : PdfStringLayoutResult = this.doLayout();
this.clear();
return result;
} else {
this.initialize(arg1, arg2, arg3, arg4 as SizeF);
this.isOverloadWithPosition = arg5 as boolean;
this.clientSize = arg6 as SizeF;
let result : PdfStringLayoutResult = this.doLayout();
this.clear();
return result;
}
}
// recalculateBounds : boolean, clientSize : SizeF
//Implementation
/**
* `Initializes` internal data.
* @private
*/
private initialize(text : string, font : PdfFont, format : PdfStringFormat, rectangle : RectangleF, pageHeight : number) : void
private initialize(text : string, font : PdfFont, format : PdfStringFormat, size : SizeF) : void
private initialize(text : string, font : PdfFont, format : PdfStringFormat, rectSize : SizeF|RectangleF,
pageHeight ?: number) : void {
if (typeof pageHeight === 'number') {
if (text == null) {
throw new Error('ArgumentNullException:text');
}
if (font == null) {
throw new Error('ArgumentNullException:font');
}
this.text = text;
this.font = font;
this.format = format;
this.size = new SizeF(rectSize.width, rectSize.height);
this.rectangle = <RectangleF>rectSize;
this.pageHeight = pageHeight;
this.reader = new StringTokenizer(text);
} else {
this.initialize(text, font, format, new RectangleF(new PointF(0, 0), <SizeF>rectSize), 0);
}
}
/**
* `Clear` all resources.
* @private
*/
private clear() : void {
this.font = null;
this.format = null;
this.reader.close();
this.reader = null;
this.text = null;
}
/**
* `Layouts` the text.
* @private
*/
private doLayout() : PdfStringLayoutResult {
let result : PdfStringLayoutResult = new PdfStringLayoutResult();
let lineResult : PdfStringLayoutResult = new PdfStringLayoutResult();
let lines : LineInfo[] = [];
let line : string = this.reader.peekLine();
let lineIndent : number = this.getLineIndent(true);
while (line != null) {
lineResult = this.layoutLine(line, lineIndent);
if (lineResult !== null || typeof lineResult !== 'undefined') {
let numSymbolsInserted : number = 0;
/* tslint:disable */
let returnedValue : { success : boolean, numInserted : number } = this.copyToResult(result, lineResult, lines, /*out*/ numSymbolsInserted);
/* tslint:enable */
let success : boolean = returnedValue.success;
numSymbolsInserted = returnedValue.numInserted;
if (!success) {
this.reader.read(numSymbolsInserted);
break;
}
}
// if (lineResult.textRemainder != null && lineResult.textRemainder.length > 0 ) {
// break;
// }
this.reader.readLine();
line = this.reader.peekLine();
lineIndent = this.getLineIndent(false);
}
this.finalizeResult(result, lines);
return result;
}
/**
* Returns `line indent` for the line.
* @private
*/
private getLineIndent(firstLine : boolean) : number {
let lineIndent : number = 0;
if (this.format != null) {
lineIndent = (firstLine) ? this.format.firstLineIndent : this.format.paragraphIndent;
lineIndent = (this.size.width > 0) ? Math.min(this.size.width, lineIndent) : lineIndent;
}
return lineIndent;
}
/**
* Calculates `height` of the line.
* @private
*/
private getLineHeight() : number {
let height : number = this.font.height;
if (this.format != null && this.format.lineSpacing !== 0) {
height = this.format.lineSpacing + this.font.height;
}
return height;
}
/**
* Calculates `width` of the line.
* @private
*/
private getLineWidth(line : string) : number {
let width : number = this.font.getLineWidth(line, this.format);
return width;
}
// tslint:disable
/**
* `Layouts` line.
* @private
*/
private layoutLine(line : string, lineIndent : number) : PdfStringLayoutResult {
let lineResult : PdfStringLayoutResult = new PdfStringLayoutResult();
lineResult.layoutLineHeight = this.getLineHeight();
let lines : LineInfo[] = [];
let maxWidth : number = this.size.width;
let lineWidth : number = this.getLineWidth(line) + lineIndent;
let lineType : LineType = LineType.FirstParagraphLine;
let readWord : boolean = true;
// line is in bounds.
if (maxWidth <= 0 || Math.round(lineWidth) <= Math.round(maxWidth)) {
this.addToLineResult(lineResult, lines, line, lineWidth, LineType.NewLineBreak | lineType);
} else {
let builder : string = '';
let curLine : string = '';
lineWidth = lineIndent;
let curIndent : number = lineIndent;
let reader : StringTokenizer = new StringTokenizer(line);
let word : string = reader.peekWord();
let isSingleWord : boolean = false;
if (word.length !== reader.length) {
if (word === ' ') {
curLine = curLine + word;
builder = builder + word;
reader.position += 1;
word = reader.peekWord();
}
}
while (word != null) {
curLine = curLine + word;
let curLineWidth : number = /*Utils.Round(*/ this.getLineWidth(curLine.toString()) + curIndent /*)*/;
if (curLine.toString() === ' ') {
curLine = '';
curLineWidth = 0;
}
if (curLineWidth > maxWidth) {
if (this.getWrapType() === PdfWordWrapType.None) {
break;
}
if (curLine.length === word.length) {
// Character wrap is disabled or one symbol is greater than bounds.
if (this.getWrapType() === PdfWordWrapType.WordOnly) {
lineResult.textRemainder = line.substring(reader.position);
break;
} else if (curLine.length === 1) {
builder = builder + word;
break;
} else {
readWord = false;
curLine = '';
word = reader.peek().toString();
continue;
}
} else {
if (this.getLineWidth(word.toString()) > maxWidth) {
this.format.wordWrap = PdfWordWrapType.Character;
} else {
if (typeof this.format !== 'undefined' && this.format !== null ) {
this.format.wordWrap = PdfWordWrapType.Word;
}
}
if (this.getWrapType() !== PdfWordWrapType.Character || !readWord) {
let ln : string = builder.toString();
// if (ln.indexOf(' ') === -1) {
// isSingleWord = true;
// this.addToLineResult(lineResult, lines, curLine, lineWidth, LineType.LayoutBreak | lineType);
// } else {
// this.addToLineResult(lineResult, lines, ln, lineWidth, LineType.LayoutBreak | lineType);
// }
if (ln !== ' ') {
this.addToLineResult(lineResult, lines, ln, lineWidth, LineType.LayoutBreak | lineType);
}
if (this.isOverloadWithPosition) {
maxWidth = this.clientSize.width;
}
curLine = '';
builder = '';
lineWidth = 0;
curIndent = 0;
curLineWidth = 0;
lineType = LineType.None;
// if (isSingleWord) {
// reader.readWord();
// readWord = false;
// }
word = (readWord) ? word : reader.peekWord();
//isSingleWord = false;
readWord = true;
} else {
readWord = false;
curLine = '';
curLine = curLine + builder.toString();
word = reader.peek().toString();
}
continue;
}
}
/*tslint:disable:max-func-body-length */
builder = builder + word;
lineWidth = curLineWidth;
if (readWord) {
reader.readWord();
word = reader.peekWord();
//isSingleWord = false;
} else {
reader.read();
word = reader.peek().toString();
}
}
if (builder.length > 0) {
let ln : string = builder.toString();
this.addToLineResult(lineResult, lines, ln, lineWidth, LineType.NewLineBreak | LineType.LastParagraphLine);
}
reader.close();
}
lineResult.layoutLines = [];
for (let index : number = 0; index < lines.length; index++) {
lineResult.layoutLines.push(lines[index]);
}
lines = [];
return lineResult;
}
/**
* `Adds` line to line result.
* @private
*/
private addToLineResult(lineResult : PdfStringLayoutResult, lines : LineInfo[], line : string,
lineWidth : number, breakType : LineType) : void {
let info : LineInfo = new LineInfo();
info.text = line;
info.width = lineWidth;
info.lineType = breakType;
lines.push(info);
let size : SizeF = lineResult.actualSize;
size.height += this.getLineHeight();
size.width = Math.max(size.width, lineWidth);
lineResult.size = size;
}
/**
* `Copies` layout result from line result to entire result. Checks whether we can proceed lay outing or not.
* @private
*/
private copyToResult(result : PdfStringLayoutResult, lineResult : PdfStringLayoutResult, lines : LineInfo[],
/*out*/ numInserted : number) : { success : boolean, numInserted : number } {
let success : boolean = true;
let allowPartialLines : boolean = (this.format != null && !this.format.lineLimit);
let height : number = result.actualSize.height;
let maxHeight : number = this.size.height;
if ((this.pageHeight > 0) && (maxHeight + this.rectangle.y > this.pageHeight)) {
maxHeight = this.rectangle.y - this.pageHeight;
maxHeight = Math.max(maxHeight, -maxHeight);
}
numInserted = 0;
if (lineResult.lines != null) {
for (let i : number = 0, len : number = lineResult.lines.length; i < len; i++) {
let expHeight : number = height + lineResult.lineHeight;
if (expHeight <= maxHeight || maxHeight <= 0 || allowPartialLines)
{
let info : LineInfo = lineResult.lines[i];
numInserted += info.text.length;
info = this.trimLine(info, (lines.length === 0));
lines.push(info);
// Update width.
let size : SizeF = result.actualSize;
size.width = Math.max(size.width, info.width);
result.size = size;
// The part of the line fits only and it's allowed to use partial lines.
// if (expHeight >= maxHeight && maxHeight > 0 && allowPartialLines)
// {
// let shouldClip : boolean = (this.format == null || !this.format.noClip);
// if (shouldClip)
// {
// let exceededHeight : number = expHeight - maxHeight;
// let fitHeight : number = /*Utils.Round(*/ lineResult.lineHeight - exceededHeight /*)*/;
// height = /*Utils.Round(*/ height + fitHeight /*)*/;
// }
// else
// {
// height = expHeight;
// }
// success = false;
// break;
// } else {
height = expHeight;
// }
}
else
{
success = false;
break;
}
}
}
if (height != result.size.height)
{
let size1 : SizeF= result.actualSize;
size1.height = height;
result.size = size1;
}
return {success : success, numInserted : numInserted};
}
/**
* `Finalizes` final result.
* @private
*/
private finalizeResult(result : PdfStringLayoutResult, lines : LineInfo[]) : void {
result.layoutLines = [];
for (let index : number = 0; index < lines.length ; index++) {
result.layoutLines.push(lines[index]);
}
result.layoutLineHeight = this.getLineHeight();
if (!this.reader.end)
{
result.textRemainder = this.reader.readToEnd();
}
lines = [];
}
/**
* `Trims` whitespaces at the line.
* @private
*/
private trimLine(info : LineInfo, firstLine : boolean) : LineInfo {
let line : string = info.text;
let lineWidth : number = info.width;
// Trim start whitespaces if the line is not a start of the paragraph only.
let trimStartSpaces : boolean = ((info.lineType & LineType.FirstParagraphLine) === 0);
let start : boolean = (this.format == null || !this.format.rightToLeft);
let spaces : string[] = StringTokenizer.spaces;
line = (start) ? line.trim() : line.trim();
// Recalculate line width.
if (line.length !== info.text.length) {
lineWidth = this.getLineWidth(line);
if ((info.lineType & LineType.FirstParagraphLine) > 0) {
lineWidth += this.getLineIndent(firstLine);
}
}
info.text = line;
info.width = lineWidth;
return info;
}
/**
* Returns `wrap` type.
* @private
*/
private getWrapType() : PdfWordWrapType {
let wrapType : PdfWordWrapType = (this.format != null) ? this.format.wordWrap : PdfWordWrapType.Word;
return wrapType;
}
}
//Internal declaration
export class PdfStringLayoutResult {
//Fields
/**
* Layout `lines`.
* @private
*/
public layoutLines : LineInfo[];
/**
* The `text` wasn`t lay outed.
* @private
*/
public textRemainder : string;
/**
* Actual layout text `bounds`.
* @private
*/
public size : SizeF;
/**
* `Height` of the line.
* @private
*/
public layoutLineHeight : number;
// Properties
/**
* Gets the `text` which is not lay outed.
* @private
*/
public get remainder() : string {
return this.textRemainder;
}
/**
* Gets the actual layout text `bounds`.
* @private
*/
public get actualSize() : SizeF {
if ( typeof this.size === 'undefined' ) {
this.size = new SizeF(0, 0);
}
return this.size;
}
/**
* Gets layout `lines` information.
* @private
*/
public get lines() : LineInfo[] {
return this.layoutLines;
}
/**
* Gets the `height` of the line.
* @private
*/
public get lineHeight() : number {
return this.layoutLineHeight;
}
/**
* Gets value that indicates whether any layout text [`empty`].
* @private
*/
public get empty() : boolean {
return (this.layoutLines == null || this.layoutLines.length === 0);
}
/**
* Gets `number of` the layout lines.
* @private
*/
public get lineCount() : number {
let count : number = (!this.empty) ? this.layoutLines.length : 0;
return count;
}
}
export class LineInfo {
//Fields
/**
* Line `text`.
* @private
*/
public content : string;
/**
* `Width` of the text.
* @private
*/
public lineWidth : number;
/**
* `Breaking type` of the line.
* @private
*/
public type : LineType;
//Properties
/**
* Gets the `type` of the line text.
* @private
*/
public get lineType() : LineType {
return this.type;
}
public set lineType(value : LineType) {
this.type = value;
}
/**
* Gets the line `text`.
* @private
*/
public get text() : string {
return this.content;
}
public set text(value : string) {
this.content = value;
}
/**
* Gets `width` of the line text.
* @private
*/
public get width() : number {
return this.lineWidth;
}
public set width(value : number) {
this.lineWidth = value;
}
}
/**
* Break type of the `line`.
* @private
*/
export enum LineType {
/**
* Specifies the type of `None`.
* @private
*/
None = 0,
/**
* Specifies the type of `NewLineBreak`.
* @private
*/
NewLineBreak = 0x0001,
/**
* Specifies the type of `LayoutBreak`.
* @private
*/
LayoutBreak = 0x0002,
/**
* Specifies the type of `FirstParagraphLine`.
* @private
*/
FirstParagraphLine = 0x0004,
/**
* Specifies the type of `LastParagraphLine`.
* @private
*/
LastParagraphLine = 0x0008
} | the_stack |
namespace Kurve {
export enum EndpointVersion {
v1=1,
v2=2
}
export enum Mode {
Client = 1,
Node = 2
}
class CachedToken {
constructor(
public id: string,
public scopes: string[],
public resource: string,
public token: string,
public expiry: Date) {};
public get isExpired() {
return this.expiry <= new Date(new Date().getTime() + 60000);
}
public hasScopes(requiredScopes: string[]) {
if (!this.scopes) {
return false;
}
return requiredScopes.every(requiredScope => {
return this.scopes.some(actualScope => requiredScope === actualScope);
});
}
}
interface CachedTokenDictionary {
[index: string]: CachedToken;
}
export interface TokenStorage {
add(key: string, token: any);
remove(key: string);
getAll(): any[];
clear();
}
class TokenCache {
private cachedTokens: CachedTokenDictionary;
constructor(private tokenStorage?: TokenStorage) {
this.cachedTokens = {};
if (tokenStorage) {
tokenStorage.getAll().forEach(({ id, scopes, resource, token, expiry }) => {
var cachedToken = new CachedToken(id, scopes, resource, token, new Date(expiry));
if (cachedToken.isExpired) {
this.tokenStorage.remove(cachedToken.id);
} else {
this.cachedTokens[cachedToken.id] = cachedToken;
}
});
}
}
public add(token: CachedToken) {
this.cachedTokens[token.id] = token;
this.tokenStorage && this.tokenStorage.add(token.id, token);
}
public getForResource(resource: string): CachedToken {
var cachedToken = this.cachedTokens[resource];
if (cachedToken && cachedToken.isExpired) {
this.remove(resource);
return null;
}
return cachedToken;
}
public getForScopes(scopes: string[]): CachedToken {
for (var key in this.cachedTokens) {
var cachedToken = this.cachedTokens[key];
if (cachedToken.hasScopes(scopes)) {
if (cachedToken.isExpired) {
this.remove(key);
} else {
return cachedToken;
}
}
}
return null;
}
public clear() {
this.cachedTokens = {};
this.tokenStorage && this.tokenStorage.clear();
}
private remove(key) {
this.tokenStorage && this.tokenStorage.remove(key);
delete this.cachedTokens[key];
}
}
export class IdToken {
public Token: string;
public IssuerIdentifier: string;
public SubjectIdentifier: string;
public Audience: string;
public Expiry: Date;
public UPN: string;
public TenantId: string;
public FamilyName: string;
public GivenName: string;
public Name: string;
public PreferredUsername: string;
public FullToken: any;
}
export interface IdentitySettings {
endpointVersion?: EndpointVersion;
mode?: Mode;
appSecret?: string;
tokenStorage?: TokenStorage;
}
export class Identity {
private state: string;
private nonce: string;
private idToken: IdToken;
private loginCallback: (error: Error) => void;
private getTokenCallback: (token: string, error: Error) => void;
private tokenCache: TokenCache;
private refreshTimer: any;
private policy: string = "";
private appSecret: string;
private NodePersistDataCallBack: (key: string, value: string, expiry: Date) => void;
private NodeRetrieveDataCallBack: (key: string) => string;
private req: any;
private res: any;
// these are public so that Kurve.Graph can access them
endpointVersion: EndpointVersion = EndpointVersion.v1;
mode: Mode = Mode.Client;
https: any;
constructor(public clientId:string, public tokenProcessorUrl: string, options?: IdentitySettings) {
// this.req = new XMLHttpRequest();
if (options && options.endpointVersion)
this.endpointVersion = options.endpointVersion;
if (options && options.appSecret)
this.appSecret=options.appSecret;
if (options && options.mode)
this.mode = options.mode;
if (this.mode === Mode.Client) {
this.tokenCache = new TokenCache(options && options.tokenStorage);
//Callback handler from other windows
window.addEventListener("message", event => {
if (event.data.type === "id_token") {
if (event.data.error) {
var e: Error = new Error();
e.text = event.data.error;
this.loginCallback(e);
} else {
//check for state
if (this.state !== event.data.state) {
var error = new Error();
error.statusText = "Invalid state";
this.loginCallback(error);
} else {
this.decodeIdToken(event.data.token);
this.loginCallback(null);
}
}
} else if (event.data.type === "access_token") {
if (event.data.error) {
var e: Error = new Error();
e.text = event.data.error;
this.getTokenCallback(null, e);
} else {
var token: string = event.data.token;
var iframe = document.getElementById("tokenIFrame");
iframe.parentNode.removeChild(iframe);
if (event.data.state !== this.state) {
var error = new Error();
error.statusText = "Invalid state";
this.getTokenCallback(null, error);
}
else {
this.getTokenCallback(token, null);
}
}
}
});
}
}
private parseQueryString(str: string) {
var queryString = str || window.location.search || '';
var keyValPairs: any[] = [];
var params: any = {};
queryString = queryString.replace(/.*?\?/, "");
if (queryString.length) {
keyValPairs = queryString.split('&');
for (var pairNum in keyValPairs) {
var key = keyValPairs[pairNum].split('=')[0];
if (!key.length) continue;
if (typeof params[key] === 'undefined')
params[key] = [];
params[key].push(keyValPairs[pairNum].split('=')[1]);
}
}
return params;
}
private token(s: string, url: string) {
var start = url.indexOf(s);
if (start < 0) return null;
var end = url.indexOf("&", start + s.length);
return url.substring(start, ((end > 0) ? end : url.length));
}
public checkForIdentityRedirect(): boolean {
var params = this.parseQueryString(window.location.href);
var idToken = this.token("#id_token=", window.location.href);
var accessToken = this.token("#access_token", window.location.href);
if (idToken) {
if (true || this.state === params["state"][0]) { //BUG? When you are in a pure redirect system you don't remember your state or nonce so don't check.
this.decodeIdToken(idToken);
this.loginCallback && this.loginCallback(null);
} else {
var error = new Error();
error.statusText = "Invalid state";
this.loginCallback && this.loginCallback(error);
}
return true;
}
else if (accessToken) {
throw "Should not get here. This should be handled via the iframe approach."
}
return false;
}
private decodeIdToken(idToken: string): void {
var decodedToken = this.base64Decode(idToken.substring(idToken.indexOf('.') + 1, idToken.lastIndexOf('.')));
var decodedTokenJSON = JSON.parse(decodedToken);
var expiryDate = new Date(new Date('01/01/1970 0:0 UTC').getTime() + parseInt(decodedTokenJSON.exp) * 1000);
this.idToken = new IdToken();
this.idToken.FullToken = decodedTokenJSON;
this.idToken.Token = idToken;
this.idToken.Expiry = expiryDate;
this.idToken.UPN = decodedTokenJSON.upn;
this.idToken.TenantId = decodedTokenJSON.tid;
this.idToken.FamilyName = decodedTokenJSON.family_name;
this.idToken.GivenName = decodedTokenJSON.given_name;
this.idToken.Name = decodedTokenJSON.name;
this.idToken.PreferredUsername = decodedTokenJSON.preferred_username;
var expiration: Number = expiryDate.getTime() - new Date().getTime() - 300000;
this.refreshTimer = setTimeout((() => {
this.renewIdToken();
}), expiration);
}
private decodeAccessToken(accessToken: string, resource?:string, scopes?:string[]): CachedToken {
var decodedToken = this.base64Decode(accessToken.substring(accessToken.indexOf('.') + 1, accessToken.lastIndexOf('.')));
var decodedTokenJSON = JSON.parse(decodedToken);
var expiryDate = new Date(new Date('01/01/1970 0:0 UTC').getTime() + parseInt(decodedTokenJSON.exp) * 1000);
var key = resource || scopes.join(" ");
var token = new CachedToken(key, scopes, resource, accessToken, expiryDate);
return token;
}
public getIdToken(): any {
return this.idToken;
}
public isLoggedIn(): boolean {
if (!this.idToken) return false;
return (this.idToken.Expiry > new Date());
}
private renewIdToken(): void {
clearTimeout(this.refreshTimer);
this.login(() => { });
}
public getAccessTokenAsync(resource: string): Promise<string,Error> {
var d = new Deferred<string,Error>();
this.getAccessToken(resource, ((error, token) => {
if (error) {
d.reject(error);
} else {
d.resolve(token);
}
}));
return d.promise;
}
public getAccessToken(resource: string, callback: PromiseCallback<string>): void {
if (this.endpointVersion !== EndpointVersion.v1) {
var e = new Error();
e.statusText = "Currently this identity class is using v2 OAuth mode. You need to use getAccessTokenForScopes() method";
callback(e);
return;
}
if (this.mode === Mode.Client) {
var token = this.tokenCache.getForResource(resource);
if (token) {
return callback(null, token.token);
}
//If we got this far, we need to go get this token
//Need to create the iFrame to invoke the acquire token
this.getTokenCallback = ((token: string, error: Error) => {
if (error) {
callback(error);
}
else {
var t = this.decodeAccessToken(token, resource);
this.tokenCache.add(t);
callback(null, token);
}
});
this.nonce = "token" + this.generateNonce();
this.state = "token" + this.generateNonce();
var iframe = document.createElement('iframe');
iframe.style.display = "none";
iframe.id = "tokenIFrame";
iframe.src = this.tokenProcessorUrl + "?clientId=" + encodeURIComponent(this.clientId) +
"&resource=" + encodeURIComponent(resource) +
"&redirectUri=" + encodeURIComponent(this.tokenProcessorUrl) +
"&state=" + encodeURIComponent(this.state) +
"&version=" + encodeURIComponent(this.endpointVersion.toString()) +
"&nonce=" + encodeURIComponent(this.nonce) +
"&op=token";
document.body.appendChild(iframe);
} else {
var cookies = this.parseNodeCookies(this.req);
var upn = this.NodeRetrieveDataCallBack("session|" + cookies["kurveSession"]);
var code = this.NodeRetrieveDataCallBack("code|" + upn);
var post_data = "grant_type=authorization_code" +
"&client_id=" + encodeURIComponent(this.clientId) +
"&code=" + encodeURIComponent(code) +
"&redirect_uri=" + encodeURIComponent(this.tokenProcessorUrl) +
"&resource=" + encodeURIComponent(resource) +
"&client_secret=" + encodeURIComponent(this.appSecret);
var post_options = {
host: 'login.microsoftonline.com',
port: '443',
path: '/common/oauth2/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': post_data.length,
accept: '*/*'
}
};
var post_req = this.https.request(post_options, (response) => {
response.setEncoding('utf8');
response.on('data', (chunk) => {
var chunkJson = JSON.parse(chunk);
var t = this.decodeAccessToken(chunkJson.access_token, resource);
// this.tokenCache.add(t); //TODO: Persist/retrieve token cache no server
callback(null, chunkJson.access_token);
});
});
post_req.write(post_data);
post_req.end();
}
}
private parseNodeCookies(req) {
var list = {};
var rc = req.headers.cookie;
rc && rc.split(';').forEach(function (cookie) {
var parts = cookie.split('=');
list[parts.shift().trim()] = decodeURI(parts.join('='));
});
return list;
}
public handleNodeCallback(req: any, res: any, https: any, crypto: any, persistDataCallback: (key: string, value: string, expiry: Date) => void, retrieveDataCallback: (key: string) => string): Promise<boolean, Error> {
this.NodePersistDataCallBack = persistDataCallback;
this.NodeRetrieveDataCallBack = retrieveDataCallback;
var url: string = <string>req.url;
this.req = req;
this.res = res;
this.https = https;
var params = this.parseQueryString(url);
var code = this.token("code=", url);
var accessToken = this.token("#access_token", url);
var cookies = this.parseNodeCookies(req);
var d = new Deferred<boolean, Error>();
if (this.endpointVersion === EndpointVersion.v1) {
if (code) {
var codeFromRequest = params["code"][0];
var stateFromRequest = params["state"][0];
var cachedState = retrieveDataCallback("state|" + stateFromRequest);
if (cachedState) {
if (cachedState === "waiting") {
var expiry = new Date(new Date().getTime() + 86400000);
persistDataCallback("state|" + stateFromRequest, "done", expiry);
var post_data = "grant_type=authorization_code" +
"&client_id=" + encodeURIComponent(this.clientId) +
"&code=" + encodeURIComponent(codeFromRequest) +
"&redirect_uri=" + encodeURIComponent(this.tokenProcessorUrl) +
"&resource=" + encodeURIComponent("https://graph.microsoft.com") +
"&client_secret=" + encodeURIComponent(this.appSecret);
var post_options = {
host: 'login.microsoftonline.com',
port: '443',
path: '/common/oauth2/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': post_data.length,
accept: '*/*'
}
};
var post_req = https.request(post_options, (response) => {
response.setEncoding('utf8');
response.on('data', (chunk) => {
var chunkJson = JSON.parse(chunk);
var decodedToken = JSON.parse(this.base64Decode(chunkJson.access_token.substring(chunkJson.access_token.indexOf('.') + 1, chunkJson.access_token.lastIndexOf('.'))));
var upn = decodedToken.upn;
var sha = crypto.createHash('sha256');
sha.update(Math.random().toString());
var sessionID = sha.digest('hex');
var expiry = new Date(new Date().getTime() + 30 * 60 * 1000);
persistDataCallback("session|" + sessionID, upn, expiry);
persistDataCallback("code|" + upn, codeFromRequest, expiry);
res.writeHead(302, {
'Set-Cookie': 'kurveSession=' + sessionID,
'Location': '/'
});
res.end();
d.resolve(false);
});
});
post_req.write(post_data);
post_req.end();
} else {
//same state has been reused, not allowed
res.writeHead(500, "Replay detected", { 'content-type': 'text/plain' });
res.end("Replay detected");
d.resolve(false);
}
}
else {
//state doesn't match any of our cached ones
res.writeHead(500, "State doesn't match", { 'content-type': 'text/plain' });
res.end("State doesn't match");
d.resolve(false);
}
return d.promise;
} else {
if (cookies["kurveSession"]) {
var upn = retrieveDataCallback("session|" + cookies["kurveSession"]);
if (upn) {
d.resolve(true);
return d.promise;
}
}
var state: string = this.generateNonce();
var expiry = new Date(new Date().getTime() + 900000);
persistDataCallback("state|" + state, "waiting", expiry);
var url = "https://login.microsoftonline.com/common/oauth2/authorize?response_type=code&client_id=" +
encodeURIComponent(this.clientId) +
"&redirect_uri=" + encodeURIComponent(this.tokenProcessorUrl) +
"&state=" + encodeURIComponent(state);
res.writeHead(302, { 'Location': url });
res.end();
d.resolve(false);
return d.promise;
}
} else {
//TODO: v2
d.resolve(false);
return d.promise;
}
}
public getAccessTokenForScopesAsync(scopes: string[], promptForConsent = false): Promise<string, Error> {
var d = new Deferred<string, Error>();
this.getAccessTokenForScopes(scopes, promptForConsent, (token, error) => {
if (error) {
d.reject(error);
} else {
d.resolve(token);
}
});
return d.promise;
}
public getAccessTokenForScopes(scopes: string[], promptForConsent, callback: (token: string, error: Error) => void): void {
if (this.endpointVersion !== EndpointVersion.v2) {
var e = new Error();
e.statusText = "Dynamic scopes require v2 mode. Currently this identity class is using v1";
callback(null, e);
return;
}
var token = this.tokenCache.getForScopes(scopes);
if (token) {
return callback(token.token, null);
}
//If we got this far, we don't have a valid cached token, so will need to get one.
//Need to create the iFrame to invoke the acquire token
this.getTokenCallback = ((token: string, error: Error) => {
if (error) {
if (promptForConsent || !error.text) {
callback(null, error);
} else if (error.text.indexOf("AADSTS65001")>=0) {
//We will need to try getting the consent
this.getAccessTokenForScopes(scopes, true, this.getTokenCallback);
} else {
callback(null, error);
}
}
else {
var t = this.decodeAccessToken(token, null, scopes);
this.tokenCache.add(t);
callback(token, null);
}
});
this.nonce = "token" + this.generateNonce();
this.state = "token" + this.generateNonce();
if (!promptForConsent) {
var iframe = document.createElement('iframe');
iframe.style.display = "none";
iframe.id = "tokenIFrame";
iframe.src = this.tokenProcessorUrl + "?clientId=" + encodeURIComponent(this.clientId) +
"&scopes=" + encodeURIComponent(scopes.join(" ")) +
"&redirectUri=" + encodeURIComponent(this.tokenProcessorUrl) +
"&version=" + encodeURIComponent(this.endpointVersion.toString()) +
"&state=" + encodeURIComponent(this.state) +
"&nonce=" + encodeURIComponent(this.nonce) +
"&login_hint=" + encodeURIComponent(this.idToken.PreferredUsername) +
"&domain_hint=" + encodeURIComponent(this.idToken.TenantId === "9188040d-6c67-4c5b-b112-36a304b66dad" ? "consumers" : "organizations") +
"&op=token";
document.body.appendChild(iframe);
} else {
window.open(this.tokenProcessorUrl + "?clientId=" + encodeURIComponent(this.clientId) +
"&scopes=" + encodeURIComponent(scopes.join(" ")) +
"&redirectUri=" + encodeURIComponent(this.tokenProcessorUrl) +
"&version=" + encodeURIComponent(this.endpointVersion.toString()) +
"&state=" + encodeURIComponent(this.state) +
"&nonce=" + encodeURIComponent(this.nonce) +
"&op=token"
, "_blank");
}
}
public loginAsync(loginSettings?: { scopes?: string[], policy?: string, tenant?: string }): Promise<void, Error> {
//TODO: Not node compatible
var d = new Deferred<void, Error>();
this.login((error) => {
if (error) {
d.reject(error);
}
else {
d.resolve(null);
}
}, loginSettings);
return d.promise;
}
public login(callback: (error: Error) => void, loginSettings?: { scopes?: string[], policy?: string, tenant?: string }): void {
//TODO: Not node compatible
this.loginCallback = callback;
if (!loginSettings) loginSettings = {};
if (loginSettings.policy) this.policy = loginSettings.policy;
if (loginSettings.scopes && this.endpointVersion === EndpointVersion.v1) {
var e = new Error();
e.text = "Scopes can only be used with OAuth v2.";
callback(e);
return;
}
if (loginSettings.policy && !loginSettings.tenant) {
var e = new Error();
e.text = "In order to use policy (AAD B2C) a tenant must be specified as well.";
callback(e);
return;
}
this.state = "login" + this.generateNonce();
this.nonce = "login" + this.generateNonce();
var loginURL = this.tokenProcessorUrl + "?clientId=" + encodeURIComponent(this.clientId) +
"&redirectUri=" + encodeURIComponent(this.tokenProcessorUrl) +
"&state=" + encodeURIComponent(this.state) +
"&nonce=" + encodeURIComponent(this.nonce) +
"&version=" + encodeURIComponent(this.endpointVersion.toString()) +
"&op=login" +
"&p=" + encodeURIComponent(this.policy);
if (loginSettings.tenant) {
loginURL += "&tenant=" + encodeURIComponent(loginSettings.tenant);
}
if (this.endpointVersion === EndpointVersion.v2) {
if (!loginSettings.scopes) loginSettings.scopes = [];
if (loginSettings.scopes.indexOf("profile") < 0)
loginSettings.scopes.push("profile");
if (loginSettings.scopes.indexOf("openid") < 0)
loginSettings.scopes.push("openid");
loginURL += "&scopes=" + encodeURIComponent(loginSettings.scopes.join(" "));
}
window.open(loginURL, "_blank");
}
public loginNoWindowAsync(toUrl?: string): Promise<void, Error> {
//TODO: Not node compatible
var d = new Deferred<void, Error>();
this.loginNoWindow((error) => {
if (error) {
d.reject(error);
}
else {
d.resolve(null);
}
}, toUrl);
return d.promise;
}
public loginNoWindow(callback: (error: Error) => void, toUrl?: string): void {
//TODO: Not node compatible
this.loginCallback = callback;
this.state = "clientId=" + this.clientId + "&" + "tokenProcessorUrl=" + this.tokenProcessorUrl
this.nonce = this.generateNonce();
var redirected = this.checkForIdentityRedirect();
if (!redirected) {
var redirectUri = (toUrl) ? toUrl : window.location.href.split("#")[0]; // default the no login window scenario to return to the current page
var url = "https://login.microsoftonline.com/common/oauth2/authorize?response_type=id_token" +
"&client_id=" + encodeURIComponent(this.clientId) +
"&redirect_uri=" + encodeURIComponent(redirectUri) +
"&state=" + encodeURIComponent(this.state) +
"&nonce=" + encodeURIComponent(this.nonce);
window.location.href = url;
}
}
public logOut(): void {
//TODO: Not node compatible
this.tokenCache.clear();
var url = "https://login.microsoftonline.com/common/oauth2/logout?post_logout_redirect_uri=" + encodeURI(window.location.href);
window.location.href = url;
}
private base64Decode(encodedString: string): string {
var e: any = {}, i: number, b = 0, c: number, x: number, l = 0, a: any, r = '', w = String.fromCharCode, L = encodedString.length;
var A = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
for (i = 0; i < 64; i++) { e[A.charAt(i)] = i; }
for (x = 0; x < L; x++) {
c = e[encodedString.charAt(x)];
b = (b << 6) + c;
l += 6;
while (l >= 8) {
((a = (b >>> (l -= 8)) & 0xff) || (x < (L - 2))) && (r += w(a));
}
}
return r;
}
private generateNonce(): string {
var text = "";
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 32; i++) {
text += chars.charAt(Math.floor(Math.random() * chars.length));
}
return text;
}
}
} | the_stack |
import isEmpty from 'lodash/isEmpty';
import escapeRegExp from 'lodash/escapeRegExp';
import tokenTypes from './tokenTypes';
export default class Tokenizer {
private readonly WHITESPACE_REGEX: RegExp;
private readonly NUMBER_REGEX: RegExp;
private readonly OPERATOR_REGEX: RegExp;
private readonly BLOCK_COMMENT_REGEX: RegExp;
private readonly LINE_COMMENT_REGEX: RegExp;
private readonly RESERVED_TOPLEVEL_REGEX: RegExp;
private readonly RESERVED_NEWLINE_REGEX: RegExp;
private readonly RESERVED_PLAIN_REGEX: RegExp;
private readonly WORD_REGEX: RegExp;
private readonly STRING_REGEX: RegExp;
private readonly OPEN_PAREN_REGEX: RegExp;
private readonly CLOSE_PAREN_REGEX: RegExp;
private readonly INDEXED_PLACEHOLDER_REGEX: RegExp | false;
private readonly IDENT_NAMED_PLACEHOLDER_REGEX: RegExp | false;
private readonly STRING_NAMED_PLACEHOLDER_REGEX: RegExp | false;
// private readonly SPECIAL_TOKENS: RegExp | false = false;
private readonly upperCase: boolean = false;
/**
* @param {Object} cfg
* @param {String[]} cfg.reservedWords Reserved words in SQL
* @param {String[]} cfg.reservedToplevelWords Words that are set to new line separately
* @param {String[]} cfg.reservedNewlineWords Words that are set to newline
* @param {String[]} cfg.stringTypes String types to enable: "", '', ``, [], N''
* @param {String[]} cfg.openParens Opening parentheses to enable, like (, [
* @param {String[]} cfg.closeParens Closing parentheses to enable, like ), ]
* @param {String[]} cfg.indexedPlaceholderTypes Prefixes for indexed placeholders, like ?
* @param {String[]} cfg.namedPlaceholderTypes Prefixes for named placeholders, like @ and :
* @param {String[]} cfg.lineCommentTypes Line comments to enable, like # and --
* @param {String[]} cfg.specialWordChars Special chars that can be found inside of words, like @ and #
* @param {boolean} cfg.upperCase
*/
constructor(cfg: any) {
this.WHITESPACE_REGEX = /^(\s+)/;
this.NUMBER_REGEX = /^((-\s*)?[0-9]+(\.[0-9]+)?|0x[0-9a-fA-F]+|0b[01]+)\b/;
this.OPERATOR_REGEX = /^(!=|<>|==|<=|>=|!<|!>|\|\||::|->>|->|~~\*|~~|!~~\*|!~~|~\*|!~\*|!~|.)/;
this.BLOCK_COMMENT_REGEX = /^(\/\*[^]*?(?:\*\/|$))/;
this.LINE_COMMENT_REGEX = this.createLineCommentRegex(cfg.lineCommentTypes);
this.RESERVED_TOPLEVEL_REGEX = this.createReservedWordRegex(cfg.reservedToplevelWords);
this.RESERVED_NEWLINE_REGEX = this.createReservedWordRegex(cfg.reservedNewlineWords);
this.RESERVED_PLAIN_REGEX = this.createReservedWordRegex(cfg.reservedWords);
this.WORD_REGEX = this.createWordRegex(cfg.specialWordChars);
this.STRING_REGEX = this.createStringRegex(cfg.stringTypes);
this.OPEN_PAREN_REGEX = this.createParenRegex(cfg.openParens);
this.CLOSE_PAREN_REGEX = this.createParenRegex(cfg.closeParens);
this.INDEXED_PLACEHOLDER_REGEX = this.createPlaceholderRegex(cfg.indexedPlaceholderTypes, '[0-9]*');
this.IDENT_NAMED_PLACEHOLDER_REGEX = this.createPlaceholderRegex(cfg.namedPlaceholderTypes, '[a-zA-Z0-9._$]+');
this.STRING_NAMED_PLACEHOLDER_REGEX = this.createPlaceholderRegex(
cfg.namedPlaceholderTypes,
this.createStringPattern(cfg.stringTypes),
);
this.upperCase = !!cfg.upperCase;
}
createLineCommentRegex(lineCommentTypes) {
return new RegExp(`^((?:${lineCommentTypes.map(c => escapeRegExp(c)).join('|')}).*?(?:\n|$))`);
}
createReservedWordRegex(reservedWords) {
const reservedWordsPattern = reservedWords.join('|').replace(/ /g, '\\s+');
return new RegExp(`^(${reservedWordsPattern})\\b`, 'i');
}
createWordRegex(specialChars = []) {
return new RegExp(`^([\\w${specialChars.join('')}]+)`);
}
createStringRegex(stringTypes) {
return new RegExp('^(' + this.createStringPattern(stringTypes) + ')');
}
// This enables the following string patterns:
// 1. backtick quoted string using `` to escape
// 2. square bracket quoted string (SQL Server) using ]] to escape
// 3. double quoted string using "" or \" to escape
// 4. single quoted string using '' or \' to escape
// 5. national character quoted string using N'' or N\' to escape
createStringPattern(stringTypes) {
const patterns = {
'``': '((`[^`]*($|`))+)',
'[]': '((\\[[^\\]]*($|\\]))(\\][^\\]]*($|\\]))*)',
'""': '(("[^"\\\\]*(?:\\\\.[^"\\\\]*)*("|$))+)',
"''": "(('[^'\\\\]*(?:\\\\.[^'\\\\]*)*('|$))+)",
"N''": "((N'[^N'\\\\]*(?:\\\\.[^N'\\\\]*)*('|$))+)",
};
return stringTypes.map(t => patterns[t]).join('|');
}
createParenRegex(parens) {
return new RegExp('^(' + parens.map(p => this.escapeParen(p)).join('|') + ')', 'i');
}
escapeParen(paren) {
if (paren.length === 1) {
// A single punctuation character
return escapeRegExp(paren);
}
// longer word
return '\\b' + paren + '\\b';
}
createPlaceholderRegex(types, pattern) {
if (isEmpty(types)) {
return false;
}
const typesRegex = types.map(escapeRegExp).join('|');
return new RegExp(`^((?:${typesRegex})(?:${pattern}))`);
}
/**
* Takes a SQL string and breaks it into tokens.
* Each token is an object with type and value.
*
* @param {String} input The SQL string
* @return {Object[]} tokens An array of tokens.
* @return {String} token.type
* @return {String} token.value
*/
tokenize(input) {
const tokens = [];
let token;
// Keep processing the string until it is empty
while (input.length) {
// Get the next token and the token type
token = this.getNextToken(input, token);
// Advance the string
input = input.substring(token.value.length);
tokens.push(token);
}
return tokens;
}
getNextToken(input, previousToken) {
return (
this.getWhitespaceToken(input) ||
this.getCommentToken(input) ||
this.getStringToken(input) ||
this.getOpenParenToken(input) ||
this.getCloseParenToken(input) ||
this.getPlaceholderToken(input) ||
this.getNumberToken(input) ||
this.getReservedWordToken(input, previousToken) ||
this.getWordToken(input) ||
this.getOperatorToken(input)
);
}
getWhitespaceToken(input) {
return this.getTokenOnFirstMatch({
input,
type: tokenTypes.WHITESPACE,
regex: this.WHITESPACE_REGEX,
});
}
getCommentToken(input) {
return this.getLineCommentToken(input) || this.getBlockCommentToken(input);
}
getLineCommentToken(input) {
return this.getTokenOnFirstMatch({
input,
type: tokenTypes.LINE_COMMENT,
regex: this.LINE_COMMENT_REGEX,
});
}
getBlockCommentToken(input) {
return this.getTokenOnFirstMatch({
input,
type: tokenTypes.BLOCK_COMMENT,
regex: this.BLOCK_COMMENT_REGEX,
});
}
getStringToken(input) {
return this.getTokenOnFirstMatch({
input,
type: tokenTypes.STRING,
regex: this.STRING_REGEX,
});
}
getOpenParenToken(input) {
return this.getTokenOnFirstMatch({
input,
type: tokenTypes.OPEN_PAREN,
regex: this.OPEN_PAREN_REGEX,
});
}
getCloseParenToken(input) {
return this.getTokenOnFirstMatch({
input,
type: tokenTypes.CLOSE_PAREN,
regex: this.CLOSE_PAREN_REGEX,
});
}
getPlaceholderToken(input) {
return (
this.getIdentNamedPlaceholderToken(input) ||
this.getStringNamedPlaceholderToken(input) ||
this.getIndexedPlaceholderToken(input)
);
}
getIdentNamedPlaceholderToken(input) {
return this.getPlaceholderTokenWithKey({
input,
regex: this.IDENT_NAMED_PLACEHOLDER_REGEX,
parseKey: v => v.slice(1),
});
}
getStringNamedPlaceholderToken(input) {
return this.getPlaceholderTokenWithKey({
input,
regex: this.STRING_NAMED_PLACEHOLDER_REGEX,
parseKey: v => this.getEscapedPlaceholderKey({key: v.slice(2, -1), quoteChar: v.slice(-1)}),
});
}
getIndexedPlaceholderToken(input) {
return this.getPlaceholderTokenWithKey({
input,
regex: this.INDEXED_PLACEHOLDER_REGEX,
parseKey: v => v.slice(1),
});
}
getPlaceholderTokenWithKey({input, regex, parseKey}) {
const token = this.getTokenOnFirstMatch({input, regex, type: tokenTypes.PLACEHOLDER});
if (token) {
token.key = parseKey(token.value);
}
return token;
}
getEscapedPlaceholderKey({key, quoteChar}) {
return key.replace(new RegExp(escapeRegExp('\\') + quoteChar, 'g'), quoteChar);
}
// Decimal, binary, or hex numbers
getNumberToken(input) {
return this.getTokenOnFirstMatch({
input,
type: tokenTypes.NUMBER,
regex: this.NUMBER_REGEX,
});
}
// Punctuation and symbols
getOperatorToken(input) {
return this.getTokenOnFirstMatch({
input,
type: tokenTypes.OPERATOR,
regex: this.OPERATOR_REGEX,
});
}
getReservedWordToken(input, previousToken) {
// A reserved word cannot be preceded by a "."
// this makes it so in "mytable.from", "from" is not considered a reserved word
if (previousToken && previousToken.value && previousToken.value === '.') {
return;
}
return (
this.getToplevelReservedToken(input) || this.getNewlineReservedToken(input) || this.getPlainReservedToken(input)
);
}
getToplevelReservedToken(input) {
return this.getTokenOnFirstMatch({
input,
type: tokenTypes.RESERVED_TOPLEVEL,
regex: this.RESERVED_TOPLEVEL_REGEX,
});
}
getNewlineReservedToken(input) {
return this.getTokenOnFirstMatch({
input,
type: tokenTypes.RESERVED_NEWLINE,
regex: this.RESERVED_NEWLINE_REGEX,
});
}
getPlainReservedToken(input) {
return this.getTokenOnFirstMatch({
input,
type: tokenTypes.RESERVED,
regex: this.RESERVED_PLAIN_REGEX,
});
}
getWordToken(input) {
return this.getTokenOnFirstMatch({
input,
type: tokenTypes.WORD,
regex: this.WORD_REGEX,
});
}
getTokenOnFirstMatch({input, type, regex}): any {
const matches = input.match(regex);
if (matches) {
let value: string = matches[1];
if (
this.upperCase &&
(type === tokenTypes.RESERVED || type === tokenTypes.RESERVED_TOPLEVEL || type === tokenTypes.RESERVED_NEWLINE)
) {
value = value.toLocaleUpperCase();
}
return {type, value};
}
}
} | the_stack |
import * as nls from 'vs/nls';
import * as Objects from 'vs/base/common/objects';
import { Task, ContributedTask, CustomTask, ConfiguringTask, TaskSorter, KeyedTaskIdentifier } from 'vs/workbench/contrib/tasks/common/tasks';
import { IWorkspace, IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import * as Types from 'vs/base/common/types';
import { ITaskService, IWorkspaceFolderTaskResult } from 'vs/workbench/contrib/tasks/common/taskService';
import { IQuickPickItem, QuickPickInput, IQuickPick, IQuickInputButton } from 'vs/base/parts/quickinput/common/quickInput';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput';
import { Disposable } from 'vs/base/common/lifecycle';
import { Event } from 'vs/base/common/event';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import { Codicon } from 'vs/base/common/codicons';
import { IThemeService, ThemeIcon } from 'vs/platform/theme/common/themeService';
import { registerIcon } from 'vs/platform/theme/common/iconRegistry';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { getColorClass, getColorStyleElement } from 'vs/workbench/contrib/terminal/browser/terminalIcon';
import { TaskQuickPickEntryType } from 'vs/workbench/contrib/tasks/browser/abstractTaskService';
export const QUICKOPEN_DETAIL_CONFIG = 'task.quickOpen.detail';
export const QUICKOPEN_SKIP_CONFIG = 'task.quickOpen.skip';
export function isWorkspaceFolder(folder: IWorkspace | IWorkspaceFolder): folder is IWorkspaceFolder {
return 'uri' in folder;
}
export interface ITaskQuickPickEntry extends IQuickPickItem {
task: Task | undefined | null;
}
export interface ITaskTwoLevelQuickPickEntry extends IQuickPickItem {
task: Task | ConfiguringTask | string | undefined | null;
settingType?: string;
}
const SHOW_ALL: string = nls.localize('taskQuickPick.showAll', "Show All Tasks...");
export const configureTaskIcon = registerIcon('tasks-list-configure', Codicon.gear, nls.localize('configureTaskIcon', 'Configuration icon in the tasks selection list.'));
const removeTaskIcon = registerIcon('tasks-remove', Codicon.close, nls.localize('removeTaskIcon', 'Icon for remove in the tasks selection list.'));
export class TaskQuickPick extends Disposable {
private _sorter: TaskSorter;
private _topLevelEntries: QuickPickInput<ITaskTwoLevelQuickPickEntry>[] | undefined;
constructor(
private _taskService: ITaskService,
private _configurationService: IConfigurationService,
private _quickInputService: IQuickInputService,
private _notificationService: INotificationService,
private _themeService: IThemeService,
private _dialogService: IDialogService) {
super();
this._sorter = this._taskService.createSorter();
}
private _showDetail(): boolean {
// Ensure invalid values get converted into boolean values
return !!this._configurationService.getValue(QUICKOPEN_DETAIL_CONFIG);
}
private _guessTaskLabel(task: Task | ConfiguringTask): string {
if (task._label) {
return TaskQuickPick.getTaskLabelWithIcon(task);
}
if (ConfiguringTask.is(task)) {
let label: string = task.configures.type;
const configures: Partial<KeyedTaskIdentifier> = Objects.deepClone(task.configures);
delete configures['_key'];
delete configures['type'];
Object.keys(configures).forEach(key => label += `: ${configures[key]}`);
return label;
}
return '';
}
public static getTaskLabelWithIcon(task: Task | ConfiguringTask): string {
const icon = task.configurationProperties.icon;
if (!icon) {
return `${task._label}`;
}
return icon.id ? `$(${icon.id}) ${task._label}` : `$(${Codicon.tools.id}) ${task._label}`;
}
public static applyColorStyles(task: Task | ConfiguringTask, entry: TaskQuickPickEntryType | ITaskTwoLevelQuickPickEntry, themeService: IThemeService): void {
if (task.configurationProperties.icon?.color) {
const colorTheme = themeService.getColorTheme();
const styleElement = getColorStyleElement(colorTheme);
entry.iconClasses = [getColorClass(task.configurationProperties.icon.color)];
document.body.appendChild(styleElement);
}
}
private _createTaskEntry(task: Task | ConfiguringTask, extraButtons: IQuickInputButton[] = []): ITaskTwoLevelQuickPickEntry {
const entry: ITaskTwoLevelQuickPickEntry = { label: this._guessTaskLabel(task), description: this._taskService.getTaskDescription(task), task, detail: this._showDetail() ? task.configurationProperties.detail : undefined };
entry.buttons = [];
entry.buttons.push({ iconClass: ThemeIcon.asClassName(configureTaskIcon), tooltip: nls.localize('configureTask', "Configure Task") });
entry.buttons.push(...extraButtons);
TaskQuickPick.applyColorStyles(task, entry, this._themeService);
return entry;
}
private _createEntriesForGroup(entries: QuickPickInput<ITaskTwoLevelQuickPickEntry>[], tasks: (Task | ConfiguringTask)[],
groupLabel: string, extraButtons: IQuickInputButton[] = []) {
entries.push({ type: 'separator', label: groupLabel });
tasks.forEach(task => {
entries.push(this._createTaskEntry(task, extraButtons));
});
}
private _createTypeEntries(entries: QuickPickInput<ITaskTwoLevelQuickPickEntry>[], types: string[]) {
entries.push({ type: 'separator', label: nls.localize('contributedTasks', "contributed") });
types.forEach(type => {
entries.push({ label: `$(folder) ${type}`, task: type, ariaLabel: nls.localize('taskType', "All {0} tasks", type) });
});
entries.push({ label: SHOW_ALL, task: SHOW_ALL, alwaysShow: true });
}
private _handleFolderTaskResult(result: Map<string, IWorkspaceFolderTaskResult>): (Task | ConfiguringTask)[] {
const tasks: (Task | ConfiguringTask)[] = [];
Array.from(result).forEach(([key, folderTasks]) => {
if (folderTasks.set) {
tasks.push(...folderTasks.set.tasks);
}
if (folderTasks.configurations) {
for (const configuration in folderTasks.configurations.byIdentifier) {
tasks.push(folderTasks.configurations.byIdentifier[configuration]);
}
}
});
return tasks;
}
private _dedupeConfiguredAndRecent(recentTasks: (Task | ConfiguringTask)[], configuredTasks: (Task | ConfiguringTask)[]): { configuredTasks: (Task | ConfiguringTask)[]; recentTasks: (Task | ConfiguringTask)[] } {
let dedupedConfiguredTasks: (Task | ConfiguringTask)[] = [];
const foundRecentTasks: boolean[] = Array(recentTasks.length).fill(false);
for (let j = 0; j < configuredTasks.length; j++) {
const workspaceFolder = configuredTasks[j].getWorkspaceFolder()?.uri.toString();
const definition = configuredTasks[j].getDefinition()?._key;
const type = configuredTasks[j].type;
const label = configuredTasks[j]._label;
const recentKey = configuredTasks[j].getRecentlyUsedKey();
const findIndex = recentTasks.findIndex((value) => {
return (workspaceFolder && definition && value.getWorkspaceFolder()?.uri.toString() === workspaceFolder
&& ((value.getDefinition()?._key === definition) || (value.type === type && value._label === label)))
|| (recentKey && value.getRecentlyUsedKey() === recentKey);
});
if (findIndex === -1) {
dedupedConfiguredTasks.push(configuredTasks[j]);
} else {
recentTasks[findIndex] = configuredTasks[j];
foundRecentTasks[findIndex] = true;
}
}
dedupedConfiguredTasks = dedupedConfiguredTasks.sort((a, b) => this._sorter.compare(a, b));
const prunedRecentTasks: (Task | ConfiguringTask)[] = [];
for (let i = 0; i < recentTasks.length; i++) {
if (foundRecentTasks[i] || ConfiguringTask.is(recentTasks[i])) {
prunedRecentTasks.push(recentTasks[i]);
}
}
return { configuredTasks: dedupedConfiguredTasks, recentTasks: prunedRecentTasks };
}
public async getTopLevelEntries(defaultEntry?: ITaskQuickPickEntry): Promise<{ entries: QuickPickInput<ITaskTwoLevelQuickPickEntry>[]; isSingleConfigured?: Task | ConfiguringTask }> {
if (this._topLevelEntries !== undefined) {
return { entries: this._topLevelEntries };
}
let recentTasks: (Task | ConfiguringTask)[] = (await this._taskService.readRecentTasks()).reverse();
const configuredTasks: (Task | ConfiguringTask)[] = this._handleFolderTaskResult(await this._taskService.getWorkspaceTasks());
const extensionTaskTypes = this._taskService.taskTypes();
this._topLevelEntries = [];
// Dedupe will update recent tasks if they've changed in tasks.json.
const dedupeAndPrune = this._dedupeConfiguredAndRecent(recentTasks, configuredTasks);
const dedupedConfiguredTasks: (Task | ConfiguringTask)[] = dedupeAndPrune.configuredTasks;
recentTasks = dedupeAndPrune.recentTasks;
if (recentTasks.length > 0) {
const removeRecentButton: IQuickInputButton = {
iconClass: ThemeIcon.asClassName(removeTaskIcon),
tooltip: nls.localize('removeRecent', 'Remove Recently Used Task')
};
this._createEntriesForGroup(this._topLevelEntries, recentTasks, nls.localize('recentlyUsed', 'recently used'), [removeRecentButton]);
}
if (configuredTasks.length > 0) {
if (dedupedConfiguredTasks.length > 0) {
this._createEntriesForGroup(this._topLevelEntries, dedupedConfiguredTasks, nls.localize('configured', 'configured'));
}
}
if (defaultEntry && (configuredTasks.length === 0)) {
this._topLevelEntries.push({ type: 'separator', label: nls.localize('configured', 'configured') });
this._topLevelEntries.push(defaultEntry);
}
if (extensionTaskTypes.length > 0) {
this._createTypeEntries(this._topLevelEntries, extensionTaskTypes);
}
return { entries: this._topLevelEntries, isSingleConfigured: configuredTasks.length === 1 ? configuredTasks[0] : undefined };
}
public async handleSettingOption(selectedType: string) {
const noButton = nls.localize('TaskQuickPick.changeSettingNo', "No");
const yesButton = nls.localize('TaskQuickPick.changeSettingYes', "Yes");
const changeSettingResult = await this._dialogService.show(Severity.Warning,
nls.localize('TaskQuickPick.changeSettingDetails',
"Task detection for {0} tasks causes files in any workspace you open to be run as code. Enabling {0} task detection is a user setting and will apply to any workspace you open. Do you want to enable {0} task detection for all workspaces?", selectedType),
[noButton, yesButton]);
if (changeSettingResult.choice === 1) {
await this._configurationService.updateValue(`${selectedType}.autoDetect`, 'on');
await new Promise<void>(resolve => setTimeout(() => resolve(), 100));
return this.show(nls.localize('TaskService.pickRunTask', 'Select the task to run'), undefined, selectedType);
}
return undefined;
}
public async show(placeHolder: string, defaultEntry?: ITaskQuickPickEntry, startAtType?: string): Promise<Task | undefined | null> {
const picker: IQuickPick<ITaskTwoLevelQuickPickEntry> = this._quickInputService.createQuickPick();
picker.placeholder = placeHolder;
picker.matchOnDescription = true;
picker.ignoreFocusOut = false;
picker.show();
picker.onDidTriggerItemButton(async (context) => {
const task = context.item.task;
if (context.button.iconClass === ThemeIcon.asClassName(removeTaskIcon)) {
const key = (task && !Types.isString(task)) ? task.getRecentlyUsedKey() : undefined;
if (key) {
this._taskService.removeRecentlyUsedTask(key);
}
const indexToRemove = picker.items.indexOf(context.item);
if (indexToRemove >= 0) {
picker.items = [...picker.items.slice(0, indexToRemove), ...picker.items.slice(indexToRemove + 1)];
}
} else {
this._quickInputService.cancel();
if (ContributedTask.is(task)) {
this._taskService.customize(task, undefined, true);
} else if (CustomTask.is(task) || ConfiguringTask.is(task)) {
let canOpenConfig: boolean = false;
try {
canOpenConfig = await this._taskService.openConfig(task);
} catch (e) {
// do nothing.
}
if (!canOpenConfig) {
this._taskService.customize(task, undefined, true);
}
}
}
});
let firstLevelTask: Task | ConfiguringTask | string | undefined | null = startAtType;
if (!firstLevelTask) {
// First show recent tasks configured tasks. Other tasks will be available at a second level
const topLevelEntriesResult = await this.getTopLevelEntries(defaultEntry);
if (topLevelEntriesResult.isSingleConfigured && this._configurationService.getValue<boolean>(QUICKOPEN_SKIP_CONFIG)) {
picker.dispose();
return this._toTask(topLevelEntriesResult.isSingleConfigured);
}
const taskQuickPickEntries: QuickPickInput<ITaskTwoLevelQuickPickEntry>[] = topLevelEntriesResult.entries;
firstLevelTask = await this._doPickerFirstLevel(picker, taskQuickPickEntries);
}
do {
if (Types.isString(firstLevelTask)) {
// Proceed to second level of quick pick
const selectedEntry = await this._doPickerSecondLevel(picker, firstLevelTask);
if (selectedEntry && !selectedEntry.settingType && selectedEntry.task === null) {
// The user has chosen to go back to the first level
firstLevelTask = await this._doPickerFirstLevel(picker, (await this.getTopLevelEntries(defaultEntry)).entries);
} else if (selectedEntry && Types.isString(selectedEntry.settingType)) {
picker.dispose();
return this.handleSettingOption(selectedEntry.settingType);
} else {
picker.dispose();
return (selectedEntry?.task && !Types.isString(selectedEntry?.task)) ? this._toTask(selectedEntry?.task) : undefined;
}
} else if (firstLevelTask) {
picker.dispose();
return this._toTask(firstLevelTask);
} else {
picker.dispose();
return firstLevelTask;
}
} while (1);
return;
}
private async _doPickerFirstLevel(picker: IQuickPick<ITaskTwoLevelQuickPickEntry>, taskQuickPickEntries: QuickPickInput<ITaskTwoLevelQuickPickEntry>[]): Promise<Task | ConfiguringTask | string | null | undefined> {
picker.items = taskQuickPickEntries;
const firstLevelPickerResult = await new Promise<ITaskTwoLevelQuickPickEntry | undefined | null>(resolve => {
Event.once(picker.onDidAccept)(async () => {
resolve(picker.selectedItems ? picker.selectedItems[0] : undefined);
});
});
return firstLevelPickerResult?.task;
}
private async _doPickerSecondLevel(picker: IQuickPick<ITaskTwoLevelQuickPickEntry>, type: string) {
picker.busy = true;
if (type === SHOW_ALL) {
const items = (await this._taskService.tasks()).sort((a, b) => this._sorter.compare(a, b)).map(task => this._createTaskEntry(task));
items.push(...TaskQuickPick.allSettingEntries(this._configurationService));
picker.items = items;
} else {
picker.value = '';
picker.items = await this._getEntriesForProvider(type);
}
picker.busy = false;
const secondLevelPickerResult = await new Promise<ITaskTwoLevelQuickPickEntry | undefined | null>(resolve => {
Event.once(picker.onDidAccept)(async () => {
resolve(picker.selectedItems ? picker.selectedItems[0] : undefined);
});
});
return secondLevelPickerResult;
}
public static allSettingEntries(configurationService: IConfigurationService): (ITaskTwoLevelQuickPickEntry & { settingType: string })[] {
const entries: (ITaskTwoLevelQuickPickEntry & { settingType: string })[] = [];
const gruntEntry = TaskQuickPick.getSettingEntry(configurationService, 'grunt');
if (gruntEntry) {
entries.push(gruntEntry);
}
const gulpEntry = TaskQuickPick.getSettingEntry(configurationService, 'gulp');
if (gulpEntry) {
entries.push(gulpEntry);
}
const jakeEntry = TaskQuickPick.getSettingEntry(configurationService, 'jake');
if (jakeEntry) {
entries.push(jakeEntry);
}
return entries;
}
public static getSettingEntry(configurationService: IConfigurationService, type: string): (ITaskTwoLevelQuickPickEntry & { settingType: string }) | undefined {
if (configurationService.getValue(`${type}.autoDetect`) === 'off') {
return {
label: nls.localize('TaskQuickPick.changeSettingsOptions', "$(gear) {0} task detection is turned off. Enable {1} task detection...",
type[0].toUpperCase() + type.slice(1), type),
task: null,
settingType: type,
alwaysShow: true
};
}
return undefined;
}
private async _getEntriesForProvider(type: string): Promise<QuickPickInput<ITaskTwoLevelQuickPickEntry>[]> {
const tasks = (await this._taskService.tasks({ type })).sort((a, b) => this._sorter.compare(a, b));
let taskQuickPickEntries: QuickPickInput<ITaskTwoLevelQuickPickEntry>[];
if (tasks.length > 0) {
taskQuickPickEntries = tasks.map(task => this._createTaskEntry(task));
taskQuickPickEntries.push({
type: 'separator'
}, {
label: nls.localize('TaskQuickPick.goBack', 'Go back ↩'),
task: null,
alwaysShow: true
});
} else {
taskQuickPickEntries = [{
label: nls.localize('TaskQuickPick.noTasksForType', 'No {0} tasks found. Go back ↩', type),
task: null,
alwaysShow: true
}];
}
const settingEntry = TaskQuickPick.getSettingEntry(this._configurationService, type);
if (settingEntry) {
taskQuickPickEntries.push(settingEntry);
}
return taskQuickPickEntries;
}
private async _toTask(task: Task | ConfiguringTask): Promise<Task | undefined> {
if (!ConfiguringTask.is(task)) {
return task;
}
const resolvedTask = await this._taskService.tryResolveTask(task);
if (!resolvedTask) {
this._notificationService.error(nls.localize('noProviderForTask', "There is no task provider registered for tasks of type \"{0}\".", task.type));
}
return resolvedTask;
}
static async show(taskService: ITaskService, configurationService: IConfigurationService,
quickInputService: IQuickInputService, notificationService: INotificationService,
dialogService: IDialogService, themeService: IThemeService, placeHolder: string, defaultEntry?: ITaskQuickPickEntry) {
const taskQuickPick = new TaskQuickPick(taskService, configurationService, quickInputService, notificationService, themeService, dialogService);
return taskQuickPick.show(placeHolder, defaultEntry);
}
} | the_stack |
import * as assert from 'assert';
import {beforeEach, describe, it, afterEach} from 'mocha';
import * as Long from 'long';
import * as sinon from 'sinon';
import {IMutateRowRequest, Mutation, IMutation} from '../src/mutation.js';
const sandbox = sinon.createSandbox();
describe('Bigtable/Mutation', () => {
afterEach(() => {
sandbox.restore();
});
describe('instantiation', () => {
const fakeData = {
key: 'a',
method: 'b',
data: 'c',
};
it('should localize all the mutation properties', () => {
const mutation = new Mutation(fakeData);
assert.strictEqual(mutation.key, fakeData.key);
assert.strictEqual(mutation.method, fakeData.method);
assert.strictEqual(mutation.data, fakeData.data);
});
});
describe('convertFromBytes', () => {
describe('isPossibleNumber', () => {
it('should convert a base64 encoded number when true', () => {
const num = 10;
const encoded = Buffer.from(Long.fromNumber(num).toBytesBE()).toString(
'base64'
);
const decoded = Mutation.convertFromBytes(encoded, {
isPossibleNumber: true,
});
assert.strictEqual(num, decoded);
});
it('should convert a base64 encoded MIN_SAFE_INTEGER number when true', () => {
const num = Number.MIN_SAFE_INTEGER;
const encoded = Buffer.from(Long.fromNumber(num).toBytesBE()).toString(
'base64'
);
const decoded = Mutation.convertFromBytes(encoded, {
isPossibleNumber: true,
});
assert.strictEqual(num, decoded);
});
it('should convert a base64 encoded MAX_SAFE_INTEGER number when true', () => {
const num = Number.MAX_SAFE_INTEGER;
const encoded = Buffer.from(Long.fromNumber(num).toBytesBE()).toString(
'base64'
);
const decoded = Mutation.convertFromBytes(encoded, {
isPossibleNumber: true,
});
assert.strictEqual(num, decoded);
});
it('should not convert a base64 encoded smaller than MIN_SAFE_INTEGER number when true', () => {
const num = Number.MIN_SAFE_INTEGER - 100;
const encoded = Buffer.from(Long.fromNumber(num).toBytesBE()).toString(
'base64'
);
const decoded = Mutation.convertFromBytes(encoded, {
isPossibleNumber: true,
});
assert.notStrictEqual(num, decoded);
});
it('should not convert a base64 encoded larger than MAX_SAFE_INTEGER number when true', () => {
const num = Number.MAX_SAFE_INTEGER + 100;
const encoded = Buffer.from(Long.fromNumber(num).toBytesBE()).toString(
'base64'
);
const decoded = Mutation.convertFromBytes(encoded, {
isPossibleNumber: true,
});
assert.notStrictEqual(num, decoded);
});
it('should not convert a base64 encoded number when false', () => {
const num = 10;
const encoded = Buffer.from(Long.fromNumber(num).toBytesBE()).toString(
'base64'
);
const decoded = Mutation.convertFromBytes(encoded);
assert.notStrictEqual(num, decoded);
});
});
it('should convert a base64 encoded string', () => {
const message = 'Hello!';
const encoded = Buffer.from(message).toString('base64');
const decoded = Mutation.convertFromBytes(encoded);
assert.strictEqual(message, decoded);
});
it('should allow using a custom encoding scheme', () => {
const message = 'æ';
const encoded = Buffer.from(message, 'binary').toString('base64');
const decoded = Mutation.convertFromBytes(encoded, {
userOptions: {encoding: 'binary'},
});
assert.strictEqual(message, decoded);
});
it('should return a buffer if decode is set to false', () => {
const message = 'Hello!';
const encoded = Buffer.from(message).toString('base64');
const userOptions = {decode: false};
const decoded = Mutation.convertFromBytes(encoded, {
userOptions,
});
assert(decoded instanceof Buffer);
assert.strictEqual(decoded.toString(), message);
});
it('should not create a new Buffer needlessly', () => {
const message = 'Hello!';
const encoded = Buffer.from(message);
const stub = sandbox.stub(Buffer, 'from');
const decoded = Mutation.convertFromBytes(encoded);
assert.strictEqual(stub.called, false);
assert.strictEqual(decoded.toString(), message);
});
});
describe('convertToBytes', () => {
it('should not re-wrap buffers', () => {
const buf = Buffer.from('hello');
const encoded = Mutation.convertToBytes(buf);
assert.strictEqual(buf, encoded);
});
it('should pack numbers into int64 values', () => {
const num = 10;
const encoded = Mutation.convertToBytes(num);
const decoded = Long.fromBytes(encoded as number[]).toNumber();
assert.strictEqual(num, decoded);
});
it('should wrap the value in a buffer', () => {
const message = 'Hello!';
const encoded = Mutation.convertToBytes(message);
assert(encoded instanceof Buffer);
assert.strictEqual(encoded.toString(), message);
});
it('should simply return the value if it cannot wrap it', () => {
const message = true;
const notEncoded = Mutation.convertToBytes(message);
assert(!(notEncoded instanceof Buffer));
assert.strictEqual(message, notEncoded);
});
});
describe('createTimeRange', () => {
it('should create a time range', () => {
const timestamp = Date.now();
const dateObj = new Date(timestamp);
const range = Mutation.createTimeRange(dateObj, dateObj);
assert.strictEqual(range.startTimestampMicros, timestamp * 1000);
assert.strictEqual(range.endTimestampMicros, timestamp * 1000);
});
});
describe('encodeSetCell', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let convertCalls: any[];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const fakeTime = new Date('2018-1-1') as any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const realTimestamp = new Date() as any;
beforeEach(() => {
sandbox.stub(global, 'Date').returns(fakeTime);
convertCalls = [];
sandbox.stub(Mutation, 'convertToBytes').callsFake(value => {
convertCalls.push(value);
return value;
});
});
it('should encode a setCell mutation', () => {
const fakeMutation = {
follows: {
gwashington: 1,
alincoln: 1,
},
};
const cells = Mutation.encodeSetCell(fakeMutation);
assert.strictEqual(cells.length, 2);
assert.deepStrictEqual(cells, [
{
setCell: {
familyName: 'follows',
columnQualifier: 'gwashington',
timestampMicros: fakeTime * 1000, // Convert ms to μs
value: 1,
},
},
{
setCell: {
familyName: 'follows',
columnQualifier: 'alincoln',
timestampMicros: fakeTime * 1000, // Convert ms to μs
value: 1,
},
},
]);
assert.strictEqual(convertCalls.length, 4);
assert.deepStrictEqual(convertCalls, ['gwashington', 1, 'alincoln', 1]);
});
it('should optionally accept a timestamp', () => {
const fakeMutation = {
follows: {
gwashington: {
value: 1,
timestamp: realTimestamp,
},
},
};
const cells = Mutation.encodeSetCell(fakeMutation);
assert.deepStrictEqual(cells, [
{
setCell: {
familyName: 'follows',
columnQualifier: 'gwashington',
timestampMicros: realTimestamp * 1000, // Convert ms to μs
value: 1,
},
},
]);
assert.strictEqual(convertCalls.length, 2);
assert.deepStrictEqual(convertCalls, ['gwashington', 1]);
});
it('should accept buffers', () => {
const val = Buffer.from('hello');
const fakeMutation = {
follows: {
gwashington: val,
},
};
const cells = Mutation.encodeSetCell(fakeMutation);
assert.deepStrictEqual(cells, [
{
setCell: {
familyName: 'follows',
columnQualifier: 'gwashington',
timestampMicros: fakeTime * 1000, // Convert ms to μs
value: val,
},
},
]);
assert.strictEqual(convertCalls.length, 2);
assert.deepStrictEqual(convertCalls, ['gwashington', val]);
});
});
describe('encodeDelete', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let convertCalls: any[] = [];
beforeEach(() => {
convertCalls = [];
sandbox.stub(Mutation, 'convertToBytes').callsFake(value => {
convertCalls.push(value);
return value;
});
});
it('should create a delete row mutation', () => {
const mutation = Mutation.encodeDelete();
assert.deepStrictEqual(mutation, [
{
deleteFromRow: {},
},
]);
});
it('should array-ify the input', () => {
const fakeKey = 'follows';
const mutation = Mutation.encodeDelete(fakeKey);
assert.deepStrictEqual(mutation, [
{
deleteFromFamily: {
familyName: fakeKey,
},
},
]);
});
it('should create a delete family mutation', () => {
const fakeColumnName = {
family: 'followed',
qualifier: null,
};
sandbox.stub(Mutation, 'parseColumnName').returns(fakeColumnName);
const mutation = Mutation.encodeDelete(['follows']);
assert.deepStrictEqual(mutation, [
{
deleteFromFamily: {
familyName: fakeColumnName.family,
},
},
]);
});
it('should create a delete column mutation', () => {
const mutation = Mutation.encodeDelete(['follows:gwashington']);
assert.deepStrictEqual(mutation, [
{
deleteFromColumn: {
familyName: 'follows',
columnQualifier: 'gwashington',
timeRange: undefined,
},
},
]);
assert.strictEqual(convertCalls.length, 1);
assert.strictEqual(convertCalls[0], 'gwashington');
});
it('should optionally accept a timerange for column requests', () => {
const createTimeRange = Mutation.createTimeRange;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const timeCalls: any[] = [];
const fakeTimeRange = {a: 'a'};
const fakeMutationData = {
column: 'follows:gwashington',
time: {
start: 1,
end: 2,
},
};
Mutation.createTimeRange = (start, end) => {
timeCalls.push({
start,
end,
});
return fakeTimeRange;
};
const mutation = Mutation.encodeDelete(fakeMutationData);
assert.deepStrictEqual(mutation, [
{
deleteFromColumn: {
familyName: 'follows',
columnQualifier: 'gwashington',
timeRange: fakeTimeRange,
},
},
]);
assert.strictEqual(timeCalls.length, 1);
assert.deepStrictEqual(timeCalls[0], fakeMutationData.time);
Mutation.createTimeRange = createTimeRange;
});
});
describe('parse', () => {
let toProtoCalled = false;
const fakeData = {a: 'a'} as IMutateRowRequest;
beforeEach(() => {
sandbox.stub(Mutation.prototype, 'toProto').callsFake(() => {
toProtoCalled = true;
return fakeData;
});
});
it('should create a new mutation object and parse it', () => {
const fakeMutationData = {
key: 'a',
method: 'b',
data: 'c',
} as Mutation;
const mutation = Mutation.parse(fakeMutationData);
assert.strictEqual(toProtoCalled, true);
assert.strictEqual(mutation, fakeData);
});
it('should parse a pre-existing mutation object', () => {
const data = new Mutation({
key: 'a',
method: 'b',
data: [],
});
const mutation = Mutation.parse(data);
assert.strictEqual(toProtoCalled, true);
assert.strictEqual(mutation, fakeData);
});
});
describe('parseColumnName', () => {
it('should parse a column name', () => {
const parsed = Mutation.parseColumnName('a:b');
assert.strictEqual(parsed.family, 'a');
assert.strictEqual(parsed.qualifier, 'b');
});
it('should parse a family name', () => {
const parsed = Mutation.parseColumnName('a');
assert.strictEqual(parsed.family, 'a');
assert.strictEqual(parsed.qualifier, undefined);
});
});
describe('toProto', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let convertCalls: any[] = [];
beforeEach(() => {
sandbox.stub(Mutation, 'convertToBytes').callsFake(value => {
convertCalls.push(value);
return value;
});
convertCalls = [];
});
it('should encode set cell mutations when method is insert', () => {
const fakeEncoded = [{a: 'a'}];
const data = {
key: 'a',
method: 'insert',
data: [],
};
const mutation = new Mutation(data);
Mutation.encodeSetCell = _data => {
assert.strictEqual(_data, data.data);
return fakeEncoded;
};
const mutationProto = mutation.toProto();
assert.strictEqual(mutationProto.mutations, fakeEncoded);
assert.strictEqual(mutationProto.rowKey, data.key);
assert.strictEqual(convertCalls[0], data.key);
});
it('should encode delete mutations when method is delete', () => {
const fakeEncoded = [{b: 'b'}] as {} as IMutation[];
const data = {
key: 'b',
method: 'delete',
data: [],
};
sandbox.stub(Mutation, 'encodeDelete').callsFake(_data => {
assert.strictEqual(_data, data.data);
return fakeEncoded;
});
const mutation = new Mutation(data).toProto();
assert.strictEqual(mutation.mutations, fakeEncoded);
assert.strictEqual(mutation.rowKey, data.key);
assert.strictEqual(convertCalls[0], data.key);
});
});
}); | the_stack |
import TypeUtils = require("utils/types");
var _formatProviders = [];
/**
* Stores the value for a "new line".
*/
export var NewLine: string = "\n";
/**
* Describes a format provider context.
*/
export interface IFormatProviderContext {
/**
* The format expression.
*/
expression: string;
/**
* Gets if the expression has been handled or not.
*/
handled: boolean;
/**
* Gets the underlying value.
*/
value: any;
}
class FormatProviderContext implements IFormatProviderContext {
_expression: string;
_value: any;
constructor(expr: string, val: any) {
this._expression = expr;
this._value = val;
}
handled: boolean = false;
public get expression(): string {
return this._expression;
}
public get value(): any {
return this._value;
}
}
/**
* Builds a string.
*/
export class StringBuilder {
/**
* Stores the internal buffer.
*/
protected _buffer: string;
/**
* Store the value for a "new line".
*/
protected _newLine: string;
/**
* Initializes a new instance of that class.
*
* @param any [initialVal] The initial value.
*/
constructor(initialVal?: any) {
this._newLine = this.valueToString(NewLine);
this._buffer = this.valueToString(initialVal);
}
/**
* Appends a value.
*
* @chainable
*
* @param any value The value to append.
*/
public append(value: any): StringBuilder {
this._buffer += this.valueToString(value);
return this;
}
/**
* Appends a formatted string.
*
* @chainable
*
* @param {String} formatStr The format string.
* @param any ...args One or more argument for the format string.
*/
public appendFormat(formatStr: string, ...args: any[]): StringBuilder {
return this.appendFormatArray(formatStr, args);
}
/**
* Appends a formatted string.
*
* @chainable
*
* @param {String} formatStr The format string.
* @param {Array} [args] One or more argument for the format string.
*/
public appendFormatArray(formatStr: string, args?: any[]): StringBuilder {
return this.append(formatArray(formatStr, args));
}
/**
* Appends a new line by appending an optional value.
*
* @chainable
*
* @param any [value] The optional value to append.
*/
public appendLine(value?: any): StringBuilder {
return this.append(value)
.append(this._newLine);
}
/**
* Resets the string.
*
* @chainable
*/
public clear(): StringBuilder {
this._buffer = '';
return this;
}
/**
* Checks if another string and the string of that builder are equal.
*
* @param any other The other string.
*
* @return {Boolean} Are equal or not.
*/
public equals(other: string | StringBuilder): boolean {
if (TypeUtils.isNullOrUndefined(other)) {
return false;
}
if (other instanceof StringBuilder) {
return other.toString() === this._buffer;
}
return other === this._buffer;
}
/**
* Executes a search on a string using a regular expression pattern,
* and returns an array containing the results of that search.
*
* @param RegExp regEx The rehular expression to use.
*
* @return {RegExpExecArray} The result of the search.
*/
public exec(regEx: RegExp): RegExpExecArray {
return regEx.exec(this._buffer);
}
/**
* Inserts a value.
*
* @chainable
*
* @param {Number} index The zero based index where to insert the value to.
* @param any value The value to insert.
*/
public insert(index: number, value: any): StringBuilder {
this._buffer = this._buffer.substr(0, index) +
this.valueToString(value) +
this._buffer.substr(index + 1);
return this;
}
/**
* Inserts a formatted string.
*
* @chainable
*
* @param {Number} index The zero based index where to insert the formatted string to.
* @param {String} formatStr The format string.
* @param any ...args One or more argument for the format string.
*/
public insertFormat(index: number, formatStr: string, ...args: any[]): StringBuilder {
return this.insertFormatArray(index,
formatStr, args);
}
/**
* Inserts a formatted string.
*
* @chainable
*
* @param {Number} index The zero based index where to insert the formatted string to.
* @param {String} formatStr The format string.
* @param {Array} [args] One or more argument for the format string.
*/
public insertFormatArray(index: number, formatStr: string, args: any[]): StringBuilder {
return this.insert(index,
formatArray(formatStr, args));
}
/**
* Gets the current length of the current string.
*/
public get length(): number {
return this._buffer.length;
}
/**
* Gets or sets the value for a "new line".
*/
public get newLine(): string {
return this._newLine;
}
public set newLine(value: string) {
this._newLine = this.valueToString(value);
}
/**
* Prepends a value.
*
* @chainable
*
* @param any value The value to prepend.
*/
public prepend(value: any): StringBuilder {
this._buffer = this.valueToString(value) + this._buffer;
return this;
}
/**
* Prepends a formatted string.
*
* @chainable
*
* @param {String} formatStr The format string.
* @param any ...args One or more argument for the format string.
*/
public prependFormat(formatStr: string, ...args: any[]): StringBuilder {
return this.prependFormatArray(formatStr, args);
}
/**
* Prepends a formatted string.
*
* @chainable
*
* @param {String} formatStr The format string.
* @param {Array} [args] One or more argument for the format string.
*/
public prependFormatArray(formatStr: string, args?: any[]): StringBuilder {
return this.prepend(formatArray(formatStr, args));
}
/**
* Prepends a new line by prepending an optional value.
*
* @chainable
*
* @param any [value] The optional value to prepend.
*/
public prependLine(value?: any): StringBuilder {
return this.prepend(this._newLine)
.prepend(value);
}
/**
* Removes the specified range of characters from this instance.
*
* @chainable
*
* @param {Number} startIndex The zero-based position where removal begins.
* @param {Number} [length] The number of characters to remove.
* If NOT defined: Anything behind startIndex is removed.
*/
public remove(startIndex: number, length?: number): StringBuilder {
if (arguments.length > 1) {
this._buffer = this._buffer.substr(0, startIndex) +
this._buffer.substr(startIndex + length);
}
else {
this._buffer = this._buffer
.substr(0, startIndex);
}
return this;
}
/**
* Replaces parts of the string.
*
* @chainable
*
* @param {String|RegExp} searchValue The string or the regular expression to search for.
* @param {String|RegExp} replacerOrValue The value or callback that replaces the matches.
* @param {Number} startIndex The optional start index that defines where replacements starts.
* @param {Number} count The optional number of chars (beginning at start index) that should be replaced.
*/
public replace(searchValue: string | RegExp,
replacerOrValue: string | ((substring: string, ...args: any[]) => string),
startIndex?: number, count?: number): StringBuilder {
if (TypeUtils.isNullOrUndefined(startIndex)) {
startIndex = 0;
}
if (TypeUtils.isNullOrUndefined(count)) {
count = this._buffer.length - startIndex;
}
var replacedStr = this._buffer
.substr(startIndex, count)
.replace(<any>searchValue, <any>replacerOrValue);
this._buffer = this._buffer.substr(0, startIndex) +
replacedStr +
this._buffer.substr(startIndex + 1);
return this;
}
/**
* Checks if a pattern exists in a searched string.
*
* @param {RegExp} regEx The regular expression.
*
* @return {Boolean} Pattern exists or not.
*/
public test(regEx: RegExp): boolean {
return regEx.test(this._buffer);
}
/**
* Returns that string as an char array.
*
* @return {Array} The array of chars.
*/
public toCharArray(): string[] {
var arr: string[];
for (var i = 0; i < this._buffer.length; i++) {
arr.push(this._buffer[i]);
}
return arr;
}
/**
* Creates the string representation of that builder.
*
* @return {String} The string representation.
*/
public toString(): string {
return this._buffer;
}
/**
* Converts a value to a string.
*
* @param any value The input value.
*
* @return {String} The value as string.
*/
protected valueToString(value?: any): string {
if (TypeUtils.isNullOrUndefined(value)) {
return '';
}
return '' + value;
}
}
/**
* Adds a format provider.
*
* @function addFormatProvider
*
* @param {Function} providerCallback The provider callback.
*/
export function addFormatProvider(providerCallback: (ctx: IFormatProviderContext) => any) {
_formatProviders.push(providerCallback);
}
/**
* Compares two strings.
*
* @function compare
*
* @param {String} x The left string.
* @param {String} y The right string.
*
* @return {Number} The compare value (0: are equal; 1: x is greater than y; 2: x is less than y)
*/
export function compare(x: string, y: string) : number {
if (x < y) {
return -1;
}
if (x > y) {
return 1;
}
return 0;
}
/**
* Joins items to one string.
*
* @function concat
*
* @param {Array} itemList The list of items.
*
* @return {String} The joined string.
*/
export function concat(itemList: any[]) : string {
return join("", itemList);
}
/**
* Formats a string.
*
* @function format
*
* @param {String} formatStr The format string.
* @param ...any args One or more argument for the format string.
*
* @return {String} The formatted string.
*/
export function format(formatStr: string, ...args: any[]) : string {
return formatArray(formatStr, args);
}
/**
* Formats a string.
*
* @function formatArray
*
* @param {String} formatStr The format string.
* @param {Array} args The list of arguments for the format string.
*
* @return {String} The formatted string.
*/
export function formatArray(formatStr: string, args: any[]) : string {
if (!formatStr) {
return formatStr;
}
if (!args) {
args = [];
}
return formatStr.replace(/{(\d+)(\:)?([^}]*)}/g, function(match, index, formatSeparator, formatExpr) {
var resultValue = args[index];
if (resultValue === undefined) {
return match;
}
var funcDepth = 0;
while (typeof resultValue === "function") {
resultValue = resultValue(index, args, match, formatExpr, funcDepth++);
}
if (formatSeparator === ':') {
// use format providers
for (var i = 0; i < _formatProviders.length; i++) {
var fp = _formatProviders[i];
var fpCtx = new FormatProviderContext(formatExpr, resultValue);
var fpResult;
try {
fpResult = fp(fpCtx);
}
catch (e) {
continue;
}
if (fpCtx.handled) {
// handled: first wins
resultValue = fpResult;
break;
}
}
}
if (resultValue !== undefined) {
return resultValue;
}
// not defined => return whole match string
return match;
});
}
/**
* Checks if a string is (null), undefined or empty.
*
* @function isEmpty
*
* @param {String} str The string to check.
*
* @return {Boolean} Is (null) / undefined / empty or not.
*/
export function isEmpty(str: string) {
return null === str ||
undefined === str ||
"" === str;
}
/**
* Checks if a string is (null), undefined, empty or contains whitespaces only.
*
* @function isEmptyOrWhitespace
*
* @param {String} str The string to check.
*
* @return {Boolean} Is (null) / undefined / empty / contains whitespaces only or not.
*/
export function isEmptyOrWhitespace(str: string) {
return isEmpty(str) ||
isWhitespace(str);
}
/**
* Checks if a string is (null) or empty.
*
* @function isNullOrEmpty
*
* @param {String} str The string to check.
*
* @return {Boolean} Is (null) / empty or not.
*/
export function isNullOrEmpty(str: string) : boolean {
return null === str ||
"" === str;
}
/**
* Checks if a string is (null) or undefined.
*
* @function isNullOrUndefined
*
* @param {String} str The string to check.
*
* @return {Boolean} Is (null) / undefined or not.
*/
export function isNullOrUndefined(str: string) : boolean {
return null === str ||
undefined === str;
}
/**
* Checks if a string is (null), empty or contains whitespaces only.
*
* @function isNullOrWhitespace
*
* @param {String} str The string to check.
*
* @return {Boolean} Is (null) / empty / contains whitespaces or not.
*/
export function isNullOrWhitespace(str: string) : boolean {
if (null === str) {
return true;
}
return isWhitespace(str);
}
/**
* Checks if a string is empty or contains whitespaces only.
*
* @function isWhitespace
*
* @param {String} str The string to check.
*
* @return {Boolean} Is empty / contains whitespaces only or not.
*/
export function isWhitespace(str: string) : boolean {
return !isNullOrUndefined(str) &&
"" === str.trim();
}
/**
* Joins items to one string.
*
* @function join
*
* @param {String} separator The separator.
* @param {Array} itemList The list of items.
*
* @return {String} The joined string.
*/
export function join(separator: string, itemList: any[]) : string {
var result = "";
for (var i = 0; i < itemList.length; i++) {
if (i > 0) {
result += separator;
}
result += itemList[i];
}
return result;
}
/**
* Returns the similarity of strings.
*
* @function similarity
*
* @param {string} left The "left" string.
* @param {string} right The "right" string.
* @param {boolean} [ignoreCase] Compare case insensitive or not.
* @param {boolean} [trim] Trim both strings before comparison or not.
*
* @return {Number} The similarity between 0 (0 %) and 1 (100 %).
*/
export function similarity(left : string, right : string, ignoreCase? : boolean, trim? : boolean) : number {
if (left === right) {
return 1;
}
if (TypeUtils.isNullOrUndefined(left) ||
TypeUtils.isNullOrUndefined(right)) {
return 0;
}
if (arguments.length < 4) {
if (arguments.length < 3) {
ignoreCase = false;
}
trim = false;
}
if (ignoreCase) {
left = left.toLowerCase();
right = right.toLowerCase();
}
if (trim) {
left = left.trim();
right = right.trim();
}
var distance = 0;
if (left !== right) {
var matrix = new Array(left.length + 1);
for (var i = 0; i < matrix.length; i++) {
matrix[i] = new Array(right.length + 1);
for (var ii = 0; ii < matrix[i].length; ii++) {
matrix[i][ii] = 0;
}
}
for (var i = 0; i <= left.length; i++) {
// delete
matrix[i][0] = i;
}
for (var j = 0; j <= right.length; j++) {
// insert
matrix[0][j] = j;
}
for (var i = 0; i < left.length; i++) {
for (var j = 0; j < right.length; j++) {
if (left[i] === right[j]) {
matrix[i + 1][j + 1] = matrix[i][j];
}
else {
// delete or insert
matrix[i + 1][j + 1] = Math.min(matrix[i][j + 1] + 1,
matrix[i + 1][j] + 1);
// substitution
matrix[i + 1][j + 1] = Math.min(matrix[i + 1][j + 1],
matrix[i][j] + 1);
}
}
distance = matrix[left.length][right.length];
}
}
return 1.0 - distance / Math.max(left.length,
right.length);
} | the_stack |
import { createApiService,
ApplicationsUtil,
LoginPage, ModelsActions,
UserFiltersUtil,
UserModel,
UsersActions
} from '@alfresco/adf-testing';
import { NavigationBarPage } from '../../core/pages/navigation-bar.page';
import { ProcessServicesPage } from './../pages/process-services.page';
import { TasksPage } from './../pages/tasks.page';
import { TasksListPage } from './../pages/tasks-list.page';
import { TaskDetailsPage } from './../pages/task-details.page';
import { ProcessServiceTabBarPage } from './../pages/process-service-tab-bar.page';
import { AppSettingsTogglesPage } from './../pages/dialog/app-settings-toggles.page';
import { TaskFiltersDemoPage } from './../pages/task-filters-demo.page';
import { UserProcessInstanceFilterRepresentation } from '@alfresco/js-api';
import { browser } from 'protractor';
describe('Task', () => {
describe('Filters', () => {
const app = browser.params.resources.Files.APP_WITH_DATE_FIELD_FORM;
const loginPage = new LoginPage();
const navigationBarPage = new NavigationBarPage();
const processServicesPage = new ProcessServicesPage();
const tasksPage = new TasksPage();
const tasksListPage = new TasksListPage();
const taskDetailsPage = new TaskDetailsPage();
const taskFiltersDemoPage = new TaskFiltersDemoPage();
const apiService = createApiService();
const usersActions = new UsersActions(apiService);
const modelsActions = new ModelsActions(apiService);
let appId: number, user: UserModel;
beforeEach(async () => {
await apiService.loginWithProfile('admin');
user = await usersActions.createUser();
await apiService.login(user.username, user.password);
const applicationsService = new ApplicationsUtil(apiService);
const { id } = await applicationsService.importPublishDeployApp(app.file_path);
appId = id;
await loginPage.login(user.username, user.password);
await navigationBarPage.navigateToProcessServicesPage();
await processServicesPage.checkApsContainer();
await processServicesPage.goToApp(app.title);
});
afterEach(async () => {
await modelsActions.deleteModel(appId);
await apiService.loginWithProfile('admin');
await usersActions.deleteTenant(user.tenantId);
await navigationBarPage.clickLogoutButton();
});
it('[C279967] Should display default filters when an app is deployed', async () => {
await taskFiltersDemoPage.involvedTasksFilter().checkTaskFilterIsDisplayed();
await taskFiltersDemoPage.myTasksFilter().checkTaskFilterIsDisplayed();
await taskFiltersDemoPage.queuedTasksFilter().checkTaskFilterIsDisplayed();
await taskFiltersDemoPage.completedTasksFilter().checkTaskFilterIsDisplayed();
});
it('[C260330] Should display Task Filter List when app is in Task Tab', async () => {
await tasksPage.createTask({ name: 'Test' });
await taskFiltersDemoPage.myTasksFilter().clickTaskFilter();
await tasksListPage.checkContentIsDisplayed('Test');
await expect(await taskFiltersDemoPage.checkActiveFilterActive()).toBe('My Tasks');
await expect(await taskDetailsPage.checkTaskDetailsDisplayed()).toBeDefined();
await taskFiltersDemoPage.queuedTasksFilter().clickTaskFilter();
await expect(await taskFiltersDemoPage.checkActiveFilterActive()).toBe('Queued Tasks');
await tasksListPage.checkContentIsNotDisplayed('Test');
await expect(await taskDetailsPage.checkTaskDetailsEmpty()).toBeDefined();
await taskFiltersDemoPage.involvedTasksFilter().clickTaskFilter();
await expect(await taskFiltersDemoPage.checkActiveFilterActive()).toBe('Involved Tasks');
await tasksListPage.checkContentIsDisplayed('Test');
await expect(await taskDetailsPage.checkTaskDetailsDisplayed()).toBeDefined();
await taskFiltersDemoPage.completedTasksFilter().clickTaskFilter();
await expect(await taskFiltersDemoPage.checkActiveFilterActive()).toBe('Completed Tasks');
await tasksListPage.checkContentIsNotDisplayed('Test');
await expect(await taskDetailsPage.checkTaskDetailsEmpty()).toBeDefined();
});
it('[C260348] Should display task in Complete Tasks List when task is completed', async () => {
await taskFiltersDemoPage.myTasksFilter().checkTaskFilterIsDisplayed();
await taskFiltersDemoPage.queuedTasksFilter().checkTaskFilterIsDisplayed();
await taskFiltersDemoPage.involvedTasksFilter().checkTaskFilterIsDisplayed();
await taskFiltersDemoPage.completedTasksFilter().checkTaskFilterIsDisplayed();
const task = await tasksPage.createNewTask();
await task.addName('Test');
await task.clickStartButton();
await taskFiltersDemoPage.myTasksFilter().clickTaskFilter();
await tasksListPage.checkContentIsDisplayed('Test');
await expect(await taskFiltersDemoPage.checkActiveFilterActive()).toBe('My Tasks');
await expect(await taskDetailsPage.checkTaskDetailsDisplayed()).toBeDefined();
await taskFiltersDemoPage.queuedTasksFilter().clickTaskFilter();
await expect(await taskFiltersDemoPage.checkActiveFilterActive()).toBe('Queued Tasks');
await expect(await tasksListPage.getNoTasksFoundMessage()).toBe('No Tasks Found');
await expect(await taskDetailsPage.getEmptyTaskDetailsMessage()).toBe('No task details found');
await taskFiltersDemoPage.involvedTasksFilter().clickTaskFilter();
await expect(await taskFiltersDemoPage.checkActiveFilterActive()).toBe('Involved Tasks');
await tasksListPage.checkContentIsDisplayed('Test');
await expect(await taskDetailsPage.checkTaskDetailsDisplayed()).toBeDefined();
await taskFiltersDemoPage.completedTasksFilter().clickTaskFilter();
await expect(await taskFiltersDemoPage.checkActiveFilterActive()).toBe('Completed Tasks');
await expect(await tasksListPage.getNoTasksFoundMessage()).toBe('No Tasks Found');
await expect(await taskDetailsPage.getEmptyTaskDetailsMessage()).toBe('No task details found');
});
it('[C260349] Should sort task by name when Name sorting is clicked', async () => {
await tasksPage.createTask({ name: 'Test1' });
await taskDetailsPage.clickCompleteTask();
await tasksPage.createTask({ name: 'Test2' });
await taskDetailsPage.clickCompleteTask();
await tasksPage.createTask({ name: 'Test3' });
await tasksPage.createTask({ name: 'Test4' });
await tasksListPage.checkContentIsDisplayed('Test4');
await tasksListPage.checkRowIsSelected('Test4');
await tasksListPage.checkContentIsDisplayed('Test3');
await taskDetailsPage.checkTaskDetailsDisplayed();
await tasksPage.clickSortByNameAsc();
await expect(await tasksListPage.getDataTable().contentInPosition(1)).toBe('Test3');
await tasksPage.clickSortByNameDesc();
await expect(await tasksListPage.getDataTable().contentInPosition(1)).toBe('Test4');
await taskFiltersDemoPage.completedTasksFilter().clickTaskFilter();
await tasksListPage.checkContentIsDisplayed('Test1');
await tasksListPage.checkContentIsDisplayed('Test2');
await expect(await tasksListPage.getDataTable().contentInPosition(1)).toBe('Test2');
await tasksPage.clickSortByNameAsc();
await expect(await tasksListPage.getDataTable().contentInPosition(1)).toBe('Test1');
await taskFiltersDemoPage.involvedTasksFilter().clickTaskFilter();
await tasksListPage.checkContentIsDisplayed('Test3');
await tasksListPage.checkContentIsDisplayed('Test4');
});
it('[C277264] Should display task filter results when task filter is selected', async () => {
await tasksPage.createTask({ name: 'Test' });
await taskFiltersDemoPage.myTasksFilter().clickTaskFilter();
await tasksListPage.checkContentIsDisplayed('Test');
await expect(await taskDetailsPage.getTaskDetailsTitle()).toBe('Test');
});
});
describe('Custom Filters', () => {
const loginPage = new LoginPage();
const navigationBarPage = new NavigationBarPage();
const processServicesPage = new ProcessServicesPage();
const processServiceTabBarPage = new ProcessServiceTabBarPage();
const appSettingsToggles = new AppSettingsTogglesPage();
const taskFiltersDemoPage = new TaskFiltersDemoPage();
const apiService = createApiService();
const userFiltersApi = new UserFiltersUtil(apiService);
const usersActions = new UsersActions(apiService);
let user;
let appId: number;
const app = browser.params.resources.Files.APP_WITH_PROCESSES;
beforeAll(async () => {
await apiService.loginWithProfile('admin');
user = await usersActions.createUser();
await apiService.login(user.username, user.password);
const applicationsService = new ApplicationsUtil(apiService);
const importedApp = await applicationsService.importPublishDeployApp(app.file_path);
appId = await applicationsService.getAppDefinitionId(importedApp.id);
await loginPage.login(user.username, user.password);
});
afterAll(async () => {
await apiService.loginWithProfile('admin');
await usersActions.deleteTenant(user.tenantId);
});
beforeEach(async () => {
await navigationBarPage.navigateToProcessServicesPage();
await processServicesPage.checkApsContainer();
await processServicesPage.goToApp(app.title);
});
it('[C260350] Should display a new filter when a filter is added', async () => {
const newFilter = new UserProcessInstanceFilterRepresentation({
name: 'New Task Filter',
appId,
icon: 'glyphicon-filter',
filter: { sort: 'created-desc', state: 'completed', assignment: 'involved' }
});
const { id } = await userFiltersApi.createUserTaskFilter(newFilter);
await browser.refresh();
await taskFiltersDemoPage.customTaskFilter('New Task Filter').checkTaskFilterIsDisplayed();
await userFiltersApi.deleteUserTaskFilter(id);
});
it('[C286447] Should display the task filter icon when a custom filter is added', async () => {
const newFilter = new UserProcessInstanceFilterRepresentation({
name: 'New Task Filter with icon',
appId,
icon: 'glyphicon-cloud',
filter: { sort: 'created-desc', state: 'completed', assignment: 'involved' }
});
const { id } = await userFiltersApi.createUserTaskFilter(newFilter);
await browser.refresh();
await processServiceTabBarPage.clickSettingsButton();
await browser.sleep(500);
await appSettingsToggles.enableTaskFiltersIcon();
await processServiceTabBarPage.clickTasksButton();
await taskFiltersDemoPage.customTaskFilter('New Task Filter with icon').checkTaskFilterIsDisplayed();
await expect(await taskFiltersDemoPage.customTaskFilter('New Task Filter with icon').getTaskFilterIcon()).toEqual('cloud');
await userFiltersApi.deleteUserTaskFilter(id);
});
it('[C286449] Should display task filter icons only when showIcon property is set on true', async () => {
await taskFiltersDemoPage.myTasksFilter().checkTaskFilterHasNoIcon();
await processServiceTabBarPage.clickSettingsButton();
await appSettingsToggles.enableTaskFiltersIcon();
await processServiceTabBarPage.clickTasksButton();
await taskFiltersDemoPage.myTasksFilter().checkTaskFilterIsDisplayed();
await expect(await taskFiltersDemoPage.myTasksFilter().getTaskFilterIcon()).toEqual('inbox');
});
});
}); | the_stack |
import { Property, Event, Component, EmitType, Internationalization, extend } from '@syncfusion/ej2-base';
import { L10n, remove, addClass, Browser, Complex, ModuleDeclaration, getInstance } from '@syncfusion/ej2-base';
import { NotifyPropertyChanges, INotifyPropertyChanged, removeClass, isNullOrUndefined } from '@syncfusion/ej2-base';
import { DataManager, ReturnOption, Query } from '@syncfusion/ej2-data';
import { PivotEngine, IFieldListOptions, IPageSettings, IDataOptions, ICustomProperties, IDrilledItem } from '../../base/engine';
import { ISort, IFilter, IFieldOptions, ICalculatedFields, IDataSet } from '../../base/engine';
import { PivotFieldListModel } from './field-list-model';
import * as events from '../../common/base/constant';
import * as cls from '../../common/base/css-constant';
import { LoadEventArgs, EnginePopulatingEventArgs, EnginePopulatedEventArgs, BeforeServiceInvokeEventArgs, FetchRawDataArgs, UpdateRawDataArgs, PivotActionBeginEventArgs, PivotActionCompleteEventArgs, PivotActionFailureEventArgs, HeadersSortEventArgs } from '../../common/base/interface';
import { AggregateEventArgs, CalculatedFieldCreateEventArgs, AggregateMenuOpenEventArgs } from '../../common/base/interface';
import { FieldDroppedEventArgs, FieldListRefreshedEventArgs, FieldDropEventArgs } from '../../common/base/interface';
import { FieldDragStartEventArgs, FieldRemoveEventArgs } from '../../common/base/interface';
import { CommonArgs, MemberFilteringEventArgs, MemberEditorOpenEventArgs } from '../../common/base/interface';
import { Mode, AggregateTypes } from '../../common/base/enum';
import { PivotCommon } from '../../common/base/pivot-common';
import { Render } from '../renderer/renderer';
import { DialogRenderer } from '../renderer/dialog-renderer';
import { TreeViewRenderer } from '../renderer/tree-renderer';
import { AxisTableRenderer } from '../renderer/axis-table-renderer';
import { AxisFieldRenderer } from '../renderer/axis-field-renderer';
import { PivotButton } from '../../common/actions/pivot-button';
import { PivotView } from '../../pivotview/base/pivotview';
import { DataSourceSettingsModel, FieldOptionsModel } from '../../pivotview/model/datasourcesettings-model';
import { DataSourceSettings } from '../../pivotview/model/datasourcesettings';
import { CalculatedField } from '../../common/calculatedfield/calculated-field';
import { PivotContextMenu } from '../../common/popups/context-menu';
import { createSpinner, showSpinner, hideSpinner } from '@syncfusion/ej2-popups';
import { PivotUtil } from '../../base/util';
import { OlapEngine, IOlapFieldListOptions, IOlapCustomProperties, IOlapField } from '../../base/olap/engine';
/**
* Represents the PivotFieldList component.
* ```html
* <div id="pivotfieldlist"></div>
* <script>
* var pivotfieldlistObj = new PivotFieldList({ });
* pivotfieldlistObj.appendTo("#pivotfieldlist");
* </script>
* ```
*/
@NotifyPropertyChanges
export class PivotFieldList extends Component<HTMLElement> implements INotifyPropertyChanged {
/** @hidden */
public globalize: Internationalization;
/** @hidden */
public localeObj: L10n;
/* eslint-disable*/
/** @hidden */
public isAdaptive: Boolean;
/* eslint-enable*/
/** @hidden */
public pivotFieldList: IFieldListOptions | IOlapFieldListOptions;
/** @hidden */
public dataType: string;
/** @hidden */
public engineModule: PivotEngine;
/** @hidden */
public olapEngineModule: OlapEngine;
/** @hidden */
public pageSettings: IPageSettings;
/** @hidden */
public isDragging: boolean;
/** @hidden */
public fieldListSpinnerElement: Element;
/** @hidden */
public clonedDataSource: DataSourceSettingsModel;
/** @hidden */
public clonedFieldList: IFieldListOptions | IOlapFieldListOptions;
/** @hidden */
public clonedFieldListData: IOlapField[];
/** @hidden */
public pivotChange: boolean = false;
public isRequiredUpdate: boolean = true;
/** @hidden */
public clonedDataSet: IDataSet[];
/** @hidden */
public clonedReport: IDataOptions;
/** @hidden */
public lastSortInfo: ISort = {};
/** @hidden */
public lastFilterInfo: IFilter = {};
/** @hidden */
public lastAggregationInfo: IFieldOptions = {};
/** @hidden */
public lastCalcFieldInfo: ICalculatedFields = {};
/** @hidden */
public isPopupView: boolean = false;
/** @hidden */
public filterTargetID: HTMLElement;
/* eslint-disable-next-line*/
private defaultLocale: Object;
private captionData: FieldOptionsModel[][];
//Module Declarations
/** @hidden */
public pivotGridModule: PivotView;
/** @hidden */
public renderModule: Render;
/** @hidden */
public dialogRenderer: DialogRenderer;
/** @hidden */
public treeViewModule: TreeViewRenderer;
/** @hidden */
public axisTableModule: AxisTableRenderer;
/** @hidden */
public pivotCommon: PivotCommon;
/** @hidden */
public axisFieldModule: AxisFieldRenderer;
/** @hidden */
public pivotButtonModule: PivotButton;
/** @hidden */
public calculatedFieldModule: CalculatedField;
/** @hidden */
public contextMenuModule: PivotContextMenu;
/** @hidden */
public currentAction: string;
/** @hidden */
private staticPivotGridModule: PivotView;
/** @hidden */
public enableValueSorting: boolean = false;
/** @hidden */
public guid: string;
private request: XMLHttpRequest = new XMLHttpRequest();
private savedDataSourceSettings: DataSourceSettingsModel;
private remoteData: string[][] | IDataSet[] = [];
/** @hidden */
public actionObj: PivotActionCompleteEventArgs = {};
/** @hidden */
public destroyEngine: boolean = false;
//Property Declarations
/* eslint-disable */
/**
* Allows the following pivot report information such as rows, columns, values, filters, etc., that are used to render the pivot table and field list.
* * `catalog`: Allows to set the database name of SSAS cube as string type that used to retrieve the data from the specified connection string. **Note: It is applicable only for OLAP data source.**
* * `cube`: Allows you to set the SSAS cube name as string type that used to retrieve data for pivot table rendering. **Note: It is applicable only for OLAP data source.**
* * `providerType`: Allows to set the provider type to identify the given connection is either Relational or SSAS to render the pivot table and field list. **Note: It is applicable only for OLAP data source.**
* * `url`: Allows to set the URL as string type, which helps to identify the service endpoint where the data are processed and retrieved to render the pivot table and field list. **Note: It is applicable only for OLAP data source.**
* * `localeIdentifier`: Allows you to set the specific culture code as number type to render pivot table with desired localization.
* By default, the pivot table displays with culture code **1033**, which indicates "en-US" locale. **Note: It is applicale only for OLAP data source.**
* * `dataSource`: Allows you to set the data source to the pivot report either as JSON data collection or from remote data server using DataManager to the render the pivot that and field list. **Note: It is applicable only for relational data source.**
* * `rows`: Allows specific fields associated with field information that needs to be displayed in row axis of pivot table.
* * `columns`: Allows specific fields associated with field information that needs to be displayed in column axis of pivot table.
* * `values`: Allows specific fields associated with field information that needs to be displayed as aggregated numeric values in pivot table.
* * `filters`: Allows to filter the values in other axis based on the collection of filter fields in pivot table.
* * `excludeFields`: Allows you to restrict the specific field(s) from displaying it in the field list UI.
* You may also be unable to render the pivot table with this field(s) by doing so. **Note: It is applicable only for relational data source.**
* * `expandAll`: Allows you to either expand or collapse all the headers that are displayed in the pivot table.
* By default, all the headers are collapsed in the pivot table. **Note: It is applicable only for Relational data.**
* * `valueAxis`: Allows you to set the value fields that to be plotted either in row or column axis in the pivot table.
* * `filterSettings`: Allows specific fields associated with either selective or conditional-based filter members that used to be displayed in the pivot table.
* * `sortSettings`: Allows specific fields associated with sort settings to order their members either in ascending or descending that used to be displayed in the pivot table.
* By default, the data source containing fields are display with Ascending order alone. To use this option, it requires the `enableSorting` property to be **true**.
* * `enableSorting`: Allows to perform sort operation to order members of a specific fields either in ascending or descending that used to be displayed in the pivot table.
* * `formatSettings`: Allows specific fields used to display the values with specific format that used to be displayed in the pivot table.
* For example, to display a specific field with currency formatted values in the pivot table, the set the `format` property to be **C**.
* * `drilledMembers`: Allows specific fields to with specify the headers that used to be either expanded or collapsed in the pivot table.
* * `valueSortSettings`: Allows to sort individual value field and its aggregated values either in row or column axis to ascending or descending order.
* * `calculatedFieldSettings`: Allows to create new calculated fields from the bound data source or using simple formula with basic arithmetic operators in the pivot table.
* * `allowMemberFilter`: Allows to perform filter operation based on the selective filter members of the specific fields used to be displayed in the pivot table.
* * `allowLabelFilter`: Allows to perform filter operation based on the selective headers used to be displayed in the pivot table.
* * `allowValueFilter`: Allows to perform filter operation based only on value fields and its resultant aggregated values over other fields defined in row and column axes that used to be displayed in the pivot table.
* * `showSubTotals`: Allows to show or hide sub-totals in both rows and columns axis of the pivot table.
* * `showRowSubTotals`: Allows to show or hide sub-totals in row axis of the pivot table.
* * `showColumnSubTotals`: Allows to show or hide sub-totals in column axis of the pivot table.
* * `showGrandTotals`: Allows to show or hide grand totals in both rows and columns axis of the pivot table.
* * `showRowGrandTotals`: Allows to show or hide grand totals in row axis of the pivot table.
* * `showColumnGrandTotals`: Allows to show or hide grand totals in column axis of the pivot table.
* * `showHeaderWhenEmpty`: Allows the undefined headers to be displayed in the pivot table, when the specific field(s) are not defined in the raw data.
* For example, if the raw data for the field ‘Country’ is defined as “United Kingdom” and “State” is not defined means, it will be shown as “United Kingdom >> Undefined” in the header section.
* * `alwaysShowValueHeader`: Allows to show the value field header always in pivot table, even if it holds a single field in the value field axis.
* * `conditionalFormatSettings`: Allows a collection of values fields to change the appearance of the pivot table value cells with different style properties such as background color, font color, font family, and font size based on specific conditions.
* * `emptyCellsTextContent`: Allows to show custom string to the empty value cells that used to display in the pivot table. You can fill empty value cells with any value like “0”, ”-”, ”*”, “(blank)”, etc.
* * `groupSettings`: Allows specific fields to group their data on the basis of their type.
* For example, the date type fields can be formatted and displayed based on year, quarter, month, and more. Likewise, the number type fields can be grouped range-wise, such as 1-5, 6-10, etc.
* You can perform custom group to the string type fields that used to displayed in the pivot table.
* * `authentication`: Allows you to set the credential information to access the specified SSAS cube. Note: It is applicable only for OLAP data source.
*/
@Complex<DataSourceSettingsModel>({}, DataSourceSettings)
public dataSourceSettings: DataSourceSettingsModel;
/**
* Allows to show field list either in static or popup mode. The available modes are:
* * `Popup`: To display the field list icon in pivot table UI to invoke the built-in dialog.
* It hepls to display over the pivot table UI without affecting any form of UI shrink within a web page.
* * `Fixed`: To display the field list in a static position within a web page.
* @default 'Popup'
*/
@Property('Popup')
public renderMode: Mode;
/**
* Allows you to set the specific target element to the fieldlist dialog.
* This helps the field list dialog to display the appropriate position on its target element.
* > To use thsi option, set the property `renderMode` to be **Popup**.
* @default null
*/
@Property()
public target: HTMLElement | string;
/**
* Allows you to add the CSS class name to the field list element.
* Use this class name, you can customize the field list easily at your end.
* @default ''
*/
@Property('')
public cssClass: string;
/**
* Allows the built-in calculated field dialog to be displayed in the component.
* You can view the calculated field dialog by clicking the "Calculated Field" button in the field list UI.
* This dialog will helps you to create a new calculated field in the pivot table, based on available fields from the bound data source or using simple formula with basic arithmetic operators at runtime.
* @default false
*/
@Property(false)
public allowCalculatedField: boolean;
/**
* Allows you to create a pivot button with "Values" as a caption used to display in the field list UI.
* It helps you to plot the value fields to either column or row axis during runtime.
* > The showValuesButton property is enabled by default for the OLAP data source.
* And the pivot button can be displayed with "Measures" as a caption used to display in the field list UI.
* @default false
*/
@Property(false)
public showValuesButton: boolean;
/**
* Allows the pivot table component to be updated only on demand, meaning,
* you can perform a variety of operations such as drag-and-drop fields between row, column, value and filter axes,
* apply sorting and filtering inside the Field List, resulting the field list UI would be updated on its own, but not the pivot table.
* On clicking the “Apply” button in the Field List, the pivot table will updates the last modified report.
* This helps to improve the performance of the pivot table component rendering.
* @default false
*/
@Property(false)
public allowDeferLayoutUpdate: boolean;
/**
* Allows you to set the limit for displaying members while loading large data in the member filter dialog.
* Based on this limit, initial loading will be completed quickly without any performance constraint.
* A message with remaining member count, that are not currently shown in the member filter dialog UI, will be displayed in the member editor.
* > This property is not applicable to user-defined hierarchies in the OLAP data source.
* @default 1000
*/
@Property(1000)
public maxNodeLimitInMemberEditor: number;
/**
* Allows to load members inside the member filter dialog on-demand.
* The first level members will be loaded from the OLAP cube to display the member editor by default.
* As a result, the member editor will be opened quickly, without any performance constraints.
* You can use either of the following actions to load your next level members. The actions are:
* * By clicking on the respective member's expander button. By doing so, only the child members of the respective member will be loaded.
* * Choose the level from the drop-down button. By doing so, all the members up to the level chosen will be loaded from the cube.
*
* Also, searching members will only be considered for the level members that are loaded.
* > This property is applicable only for OLAP data source.
* @default true
*/
@Property(true)
public loadOnDemandInMemberEditor: boolean;
/**
* Allows the appearance of the loading indicator to be customized with either an HTML string or the element’s ID,
* that can be used to displayed with custom formats in the field list UI.
* @default null
*/
@Property()
public spinnerTemplate: string;
/**
* Allows you to show a menu with built-in aggregate options displayed in the pivot button's dropdown icon of fieldList UI.
* These aggregate options help to display the values in the pivot table with appropriate aggregations such as sum, product, count, average, etc… easily at runtime.
* The available aggregate options are:
* * `Sum`: Allows to display the pivot table values with sum.
* * `Product`: Allows to display the pivot table values with product.
* * `Count`: Allows to display the pivot table values with count.
* * `DistinctCount`: Allows to display the pivot table values with distinct count.
* * `Min`: Allows to display the pivot table with minimum value.
* * `Max`: Allows to display the pivot table with maximum value.
* * `Avg`: Allows to display the pivot table values with average.
* * `Median`: Allows to display the pivot table values with median.
* * `Index`: Allows to display the pivot table values with index.
* * `PopulationStDev`: Allows to display the pivot table values with population standard deviation.
* * `SampleStDev`: Allows to display the pivot table values with sample standard deviation.
* * `PopulationVar`: Allows to display the pivot table values with population variance.
* * `SampleVar`: Allows to display the pivot table values with sample variance.
* * `RunningTotals`: Allows to display the pivot table values with running totals.
* * `DifferenceFrom`: Allows to display the pivot table values with difference from the value of the base item in the base field.
* * `PercentageOfDifferenceFrom`: Allows to display the pivot table values with percentage difference from the value of the base item in the base field.
* * `PercentageOfGrandTotal`: Allows to display the pivot table values with percentage of grand total of all values.
* * `PercentageOfColumnTotal`: Allows to display the pivot table values in each column with percentage of total values for the column.
* * `PercentageOfRowTotal`: Allows to display the pivot table values in each row with percentage of total values for the row.
* * `PercentageOfParentTotal`: Allows to display the pivot table values with percentage of total of all values based on selected field.
* * `PercentageOfParentColumnTotal`: Allows to display the pivot table values with percentage of its parent total in each column.
* * `PercentageOfParentRowTotal`: Allows to display the pivot table values with percentage of its parent total in each row.
*
* > It is applicable ony for Relational data.
* @default ['Sum', 'Count', 'DistinctCount', 'Product', 'Min', 'Max', 'Avg', 'Median', 'Index', 'PopulationVar', 'SampleVar',
* 'PopulationStDev', 'SampleStDev', 'RunningTotals', 'PercentageOfGrandTotal', 'PercentageOfColumnTotal', 'PercentageOfRowTotal',
* 'PercentageOfParentColumnTotal', 'PercentageOfParentRowTotal', 'DifferenceFrom', 'PercentageOfDifferenceFrom',
* 'PercentageOfParentTotal']
*/
@Property(['Sum', 'Count', 'DistinctCount', 'Product', 'Min', 'Max', 'Avg', 'Median', 'Index', 'PopulationVar', 'SampleVar', 'PopulationStDev', 'SampleStDev', 'RunningTotals', 'PercentageOfGrandTotal', 'PercentageOfColumnTotal', 'PercentageOfRowTotal', 'PercentageOfParentColumnTotal', 'PercentageOfParentRowTotal', 'DifferenceFrom', 'PercentageOfDifferenceFrom', 'PercentageOfParentTotal'])
public aggregateTypes: AggregateTypes[];
/**
* Allows values with a specific country currency format to be displayed in the pivot table.
* Standard currency codes referred to as ISO 4217 can be used for the formatting of currency values.
* For example, to display "US Dollar($)" currency values, set the `currencyCode` to **USD**.
* > It is applicable ony for Relational data.
* @private
*/
@Property('USD')
private currencyCode: string;
//Event Declarations
/**
* It allows any customization of Pivot Field List properties on initial rendering.
* Based on the changes, the pivot field list will be redered.
* @event
*/
@Event()
public load: EmitType<LoadEventArgs>;
/**
* It triggers before the pivot engine starts to populate and allows to customize the pivot datasource settings.
* @event
*/
@Event()
public enginePopulating: EmitType<EnginePopulatingEventArgs>;
/**
* It triggers before the filtering applied.
* @event
*/
@Event()
public memberFiltering: EmitType<MemberFilteringEventArgs>;
/**
* It triggers after the pivot engine populated and allows to customize the pivot datasource settings.
* @event
*/
@Event()
public enginePopulated: EmitType<EnginePopulatedEventArgs>;
/**
* It trigger when a field getting dropped into any axis.
* @event
*/
@Event()
public onFieldDropped: EmitType<FieldDroppedEventArgs>;
/**
* It triggers before a field drops into any axis.
* @event
*/
@Event()
public fieldDrop: EmitType<FieldDropEventArgs>;
/**
* It trigger when a field drag (move) starts.
* @event
*/
@Event()
public fieldDragStart: EmitType<FieldDragStartEventArgs>;
/**
* It allows to change the each cell value during engine populating.
* @event
* @deprecated
*/
@Event()
public aggregateCellInfo: EmitType<AggregateEventArgs>;
/**
* It triggers before member editor dialog opens.
* @event
*/
@Event()
public memberEditorOpen: EmitType<MemberEditorOpenEventArgs>;
/**
* It triggers before a calculated field created/edited during runtime.
* @event
*/
@Event()
public calculatedFieldCreate: EmitType<CalculatedFieldCreateEventArgs>;
/**
* It triggers before aggregate type context menu opens.
* @event
*/
@Event()
public aggregateMenuOpen: EmitType<AggregateMenuOpenEventArgs>;
/**
* It triggers before removing the field from any axis during runtime.
* @event
*/
@Event()
public fieldRemove: EmitType<FieldRemoveEventArgs>;
/**
* It trigger when the Pivot Field List rendered.
* @event
*/
@Event()
public dataBound: EmitType<Object>;
/**
* It trigger when the Pivot Field List component is created..
* @event
*/
@Event()
public created: EmitType<Object>;
/**
* It trigger when the Pivot Field List component getting destroyed.
* @event
*/
@Event()
public destroyed: EmitType<Object>;
/* eslint-enable */
/**
* It triggers before service get invoked from client.
* @event
*/
@Event()
public beforeServiceInvoke: EmitType<BeforeServiceInvokeEventArgs>;
/**
* It triggers when UI action begins in the Pivot FieldList. The UI actions used to trigger this event such as
* sorting fields through icon click in the field list tree,
* [`Calculated field`](../../pivotview/field-list/#calculated-fields) UI,
* Button actions such as
* [`editing`](../../pivotview/calculated-field/#editing-through-the-field-list-and-the-groupingbar),
* [`sorting`](../../pivotview/field-list/#sorting-members),
* [`filtering`](../../pivotview/field-list/#filtering-members) and
* [`aggregation`](pivotview/field-list/#changing-aggregation-type-of-value-fields-at-runtime).
* @event
*/
@Event()
public actionBegin: EmitType<PivotActionBeginEventArgs>;
/**
* It triggers when UI action in the Pivot FieldList completed. The UI actions used to trigger this event such as
* sorting fields through icon click in the field list tree,
* [`Calculated field`](../../pivotview/field-list/#calculated-fields) UI,
* Button actions such as
* [`editing`](../../pivotview/calculated-field/#editing-through-the-field-list-and-the-groupingbar),
* [`sorting`](../../pivotview/field-list/#sorting-members),
* [`filtering`](../../pivotview/field-list/#filtering-members) and
* [`aggregation`](pivotview/field-list/#changing-aggregation-type-of-value-fields-at-runtime).
* @event
*/
@Event()
public actionComplete: EmitType<PivotActionCompleteEventArgs>;
/**
* It triggers when UI action failed to achieve the desired results in the Pivot FieldList. The UI actions used to trigger this event such as
* sorting fields through icon click in the field list tree,
* [`Calculated field`](../../pivotview/field-list/#calculated-fields) UI,
* Button actions such as
* [`editing`](../../pivotview/calculated-field/#editing-through-the-field-list-and-the-groupingbar),
* [`sorting`](../../pivotview/field-list/#sorting-members),
* [`filtering`](../../pivotview/field-list/#filtering-members) and
* [`aggregation`](pivotview/field-list/#changing-aggregation-type-of-value-fields-at-runtime).
* @event
*/
@Event()
public actionFailure: EmitType<PivotActionFailureEventArgs>;
/**
* It triggers before the sorting performed.
* @event
*/
@Event()
public onHeadersSort: EmitType<HeadersSortEventArgs>;
/**
* Constructor for creating the widget
* @param {PivotFieldListModel} options - options
* @param {string|HTMLElement} element - element
*/
constructor(options?: PivotFieldListModel, element?: string | HTMLElement) { /* eslint-disable-line */
super(options, <string | HTMLElement>element);
}
/**
* To provide the array of modules needed for control rendering
* @returns {ModuleDeclaration[]} - ModuleDeclaration[]
* @hidden
*/
public requiredModules(): ModuleDeclaration[] {
let modules: ModuleDeclaration[] = [];
if (this.allowCalculatedField) {
modules.push({ args: [this], member: 'calculatedField' });
}
return modules;
}
/**
* @returns {AggregateTypes[]}- AggregateTypes[]
* @hidden
*/
public getAllSummaryType(): AggregateTypes[] {
return ['Sum', 'Count', 'DistinctCount', 'Product', 'Min', 'Max', 'Avg', 'Median', 'Index',
'PopulationVar', 'SampleVar', 'PopulationStDev', 'SampleStDev', 'RunningTotals', 'PercentageOfGrandTotal',
'PercentageOfColumnTotal', 'PercentageOfRowTotal', 'PercentageOfParentColumnTotal', 'PercentageOfParentRowTotal',
'DifferenceFrom', 'PercentageOfDifferenceFrom', 'PercentageOfParentTotal'];
}
/* eslint-disable-next-line */
/**
* For internal use only - Initialize the event handler;
* @private
*/
protected preRender(): void {
if (this.dataSourceSettings && this.dataSourceSettings.providerType === 'SSAS') {
this.olapEngineModule = new OlapEngine();
this.dataType = 'olap';
} else {
this.engineModule = new PivotEngine();
this.dataType = 'pivot';
}
this.isAdaptive = Browser.isDevice;
this.globalize = new Internationalization(this.locale);
this.renderModule = new Render(this);
/* eslint-disable */
this.defaultLocale = {
staticFieldList: 'Pivot Field List',
fieldList: 'Field List',
dropFilterPrompt: 'Drop filter here',
dropColPrompt: 'Drop column here',
dropRowPrompt: 'Drop row here',
dropValPrompt: 'Drop value here',
addPrompt: 'Add field here',
adaptiveFieldHeader: 'Choose field',
centerHeader: 'Drag fields between axes below:',
add: 'add',
drag: 'Drag',
filter: 'Filter',
filtered: 'Filtered',
sort: 'Sort',
remove: 'Remove',
filters: 'Filters',
rows: 'Rows',
columns: 'Columns',
values: 'Values',
CalculatedField: 'Calculated Field',
createCalculatedField: 'Create Calculated Field',
fieldName: 'Enter the field name',
error: 'Error',
invalidFormula: 'Invalid formula.',
dropText: 'Example: ("Sum(Order_Count)" + "Sum(In_Stock)") * 250',
dropTextMobile: 'Add fields and edit formula here.',
dropAction: 'Calculated field cannot be place in any other region except value axis.',
search: 'Search',
close: 'Close',
cancel: 'Cancel',
delete: 'Delete',
alert: 'Alert',
warning: 'Warning',
ok: 'OK',
allFields: 'All Fields',
formula: 'Formula',
fieldExist: 'A field already exists in this name. Please enter a different name.',
confirmText: 'A calculation field already exists in this name. Do you want to replace it?',
noMatches: 'No matches',
format: 'Summaries values by',
edit: 'Edit',
clear: 'Clear',
clearCalculatedField: 'Clear edited field info',
editCalculatedField: 'Edit calculated field',
sortAscending: 'Sort ascending order',
sortDescending: 'Sort descending order',
sortNone: 'Sort data order',
formulaField: 'Drag and drop fields to formula',
dragField: 'Drag field to formula',
clearFilter: 'Clear',
by: 'by',
enterValue: 'Enter value',
chooseDate: 'Enter date',
all: 'All',
multipleItems: 'Multiple items',
Equals: 'Equals',
DoesNotEquals: 'Does Not Equal',
BeginWith: 'Begins With',
DoesNotBeginWith: 'Does Not Begin With',
EndsWith: 'Ends With',
DoesNotEndsWith: 'Does Not End With',
Contains: 'Contains',
DoesNotContains: 'Does Not Contain',
GreaterThan: 'Greater Than',
GreaterThanOrEqualTo: 'Greater Than Or Equal To',
LessThan: 'Less Than',
LessThanOrEqualTo: 'Less Than Or Equal To',
Between: 'Between',
NotBetween: 'Not Between',
Before: 'Before',
BeforeOrEqualTo: 'Before Or Equal To',
After: 'After',
AfterOrEqualTo: 'After Or Equal To',
member: 'Member',
label: 'Label',
date: 'Date',
value: 'Value',
labelTextContent: 'Show the items for which the label',
dateTextContent: 'Show the items for which the date',
valueTextContent: 'Show the items for which',
And: 'and',
Sum: 'Sum',
Count: 'Count',
DistinctCount: 'Distinct Count',
Product: 'Product',
Avg: 'Avg',
Median: 'Median',
Min: 'Min',
Max: 'Max',
Index: 'Index',
SampleStDev: 'Sample StDev',
PopulationStDev: 'Population StDev',
SampleVar: 'Sample Var',
PopulationVar: 'Population Var',
RunningTotals: 'Running Totals',
DifferenceFrom: 'Difference From',
PercentageOfDifferenceFrom: '% of Difference From',
PercentageOfGrandTotal: '% of Grand Total',
PercentageOfColumnTotal: '% of Column Total',
PercentageOfRowTotal: '% of Row Total',
PercentageOfParentTotal: '% of Parent Total',
PercentageOfParentColumnTotal: '% of Parent Column Total',
PercentageOfParentRowTotal: '% of Parent Row Total',
MoreOption: 'More...',
Years: 'Years',
Quarters: 'Quarters',
Months: 'Months',
Days: 'Days',
Hours: 'Hours',
Minutes: 'Minutes',
Seconds: 'Seconds',
apply: 'Apply',
valueFieldSettings: 'Value field settings',
sourceName: 'Field name :',
sourceCaption: 'Field caption',
summarizeValuesBy: 'Summarize values by',
baseField: 'Base field',
baseItem: 'Base item',
example: 'e.g:',
editorDataLimitMsg: ' more items. Search to refine further.',
deferLayoutUpdate: 'Defer Layout Update',
null: 'null',
undefined: 'undefined',
groupOutOfRange: 'Out of Range',
fieldDropErrorAction: 'The field you are moving cannot be placed in that area of the report',
memberType: 'Field Type',
selectedHierarchy: 'Parent Hierarchy',
formatString: 'Format',
expressionField: 'Expression',
olapDropText: 'Example: [Measures].[Order Quantity] + ([Measures].[Order Quantity] * 0.10)',
customFormat: 'Enter custom format string',
numberFormatString: 'Example: C, P, 0000 %, ###0.##0#, etc.',
Measure: 'Measure',
Dimension: 'Dimension',
Standard: 'Standard',
Currency: 'Currency',
Percent: 'Percent',
Custom: 'Custom',
blank: '(Blank)',
fieldTooltip: 'Drag and drop fields to create an expression. ' +
'And, if you want to edit the existing calculated fields! ' +
'You can achieve it by simply selecting the field under "Calculated Members".',
fieldTitle: 'Field Name',
QuarterYear: 'Quarter Year',
caption: 'Field Caption',
copy: 'Copy',
of: 'of',
group: 'Group',
removeCalculatedField: 'Are you sure you want to delete this calculated field?',
yes: 'Yes',
no: 'No',
None: 'None'
};
/* eslint-enable */
this.localeObj = new L10n(this.getModuleName(), this.defaultLocale, this.locale);
this.isDragging = false;
this.captionData = [];
this.wireEvent();
}
private frameCustomProperties(fieldListData?: IOlapField[], fieldList?: IOlapFieldListOptions): ICustomProperties | IOlapCustomProperties { /* eslint-disable-line */
if (this.pivotGridModule) {
this.pivotGridModule.updatePageSettings(false);
}
let pageSettings: IPageSettings = this.pivotGridModule ? this.pivotGridModule.pageSettings : this.pageSettings;
let localeObj: L10n = this.pivotGridModule ? this.pivotGridModule.localeObj :
(this.staticPivotGridModule ? this.staticPivotGridModule.localeObj : this.localeObj);
let isDrillThrough: boolean = this.pivotGridModule ?
(this.pivotGridModule.allowDrillThrough || this.pivotGridModule.editSettings.allowEditing) : true;
let enableValueSorting: boolean = this.pivotGridModule ? this.pivotGridModule.enableValueSorting : undefined;
let customProperties: ICustomProperties | IOlapCustomProperties;
if (this.dataType === 'olap') {
customProperties = {
mode: '',
savedFieldList: fieldList ? fieldList : undefined,
savedFieldListData: fieldListData ? fieldListData : undefined,
pageSettings: pageSettings,
enableValueSorting: enableValueSorting,
isDrillThrough: isDrillThrough,
localeObj: localeObj
};
} else {
customProperties = {
mode: '',
savedFieldList: undefined,
pageSettings: pageSettings,
enableValueSorting: enableValueSorting,
isDrillThrough: isDrillThrough,
localeObj: localeObj,
clonedReport: this.clonedReport,
globalize: this.globalize,
currenyCode: this.currencyCode
};
}
return customProperties;
}
/* eslint-disable */
/**
* Initialize the control rendering
* @returns {void}
* @private
*/
public render(): void {
if (this.dataType === 'pivot' && this.dataSourceSettings.url && this.dataSourceSettings.url !== '') {
if (this.dataSourceSettings.mode === 'Server') {
this.guid = PivotUtil.generateUUID();
this.getEngine('initialRender', null, null, null, null, null, null);
} else {
this.request.open("GET", this.dataSourceSettings.url, true);
this.request.withCredentials = false;
this.request.onreadystatechange = this.onReadyStateChange.bind(this);
this.request.setRequestHeader("Content-type", "text/plain");
this.request.send(null);
}
} else {
this.initialLoad();
}
}
/**
* @hidden
*/
public getEngine(action: string, drillItem?: IDrilledItem, sortItem?: ISort, aggField?: IFieldOptions, cField?: ICalculatedFields, filterItem?: IFilter, memberName?: string, rawDataArgs?: FetchRawDataArgs, editArgs?: UpdateRawDataArgs): void {
this.currentAction = action;
if (this.pivotGridModule) {
this.pivotGridModule.updatePageSettings(false);
}
let customProperties: any = {
pageSettings: this.pivotGridModule ? this.pivotGridModule.pageSettings : undefined,
enableValueSorting: this.pivotGridModule ? this.pivotGridModule.enableValueSorting : undefined,
enableDrillThrough: this.pivotGridModule ?
(this.pivotGridModule.allowDrillThrough || this.pivotGridModule.editSettings.allowEditing) : true,
locale: JSON.stringify(PivotUtil.getLocalizedObject(this))
};
this.request.open("POST", this.dataSourceSettings.url, true);
let params: BeforeServiceInvokeEventArgs = {
request: this.request,
dataSourceSettings: JSON.parse(this.getPersistData()).dataSourceSettings,
action: action,
customProperties: {},
internalProperties: customProperties,
drillItem: drillItem,
sortItem: sortItem,
aggregatedItem: aggField,
calculatedItem: cField,
filterItem: filterItem,
memberName: memberName,
fetchRawDataArgs: rawDataArgs,
editArgs: editArgs,
hash: this.guid
};
this.trigger(events.beforeServiceInvoke, params, (observedArgs: BeforeServiceInvokeEventArgs) => {
this.request = observedArgs.request;
params.internalProperties = observedArgs.internalProperties;
params.customProperties = observedArgs.customProperties;
params.dataSourceSettings = observedArgs.dataSourceSettings;
params.calculatedItem = observedArgs.calculatedItem;
params.drillItem = observedArgs.drillItem;
params.editArgs = observedArgs.editArgs;
params.fetchRawDataArgs = observedArgs.fetchRawDataArgs;
params.filterItem = observedArgs.filterItem;
params.hash = observedArgs.hash;
params.memberName = observedArgs.memberName;
params.sortItem = observedArgs.sortItem;
});
this.request.withCredentials = false;
this.request.onreadystatechange = this.onSuccess.bind(this);
this.request.setRequestHeader("Content-type", "application/json");
this.request.send(JSON.stringify(params));
}
private onSuccess(): void {
if (this.request.readyState === XMLHttpRequest.DONE) {
try {
let engine: any = JSON.parse(this.request.responseText);
if (this.currentAction === 'fetchFieldMembers') {
let currentMembers: any = JSON.parse(engine.members);
let dateMembers: any = [];
let formattedMembers: any = {};
let members: any = {};
for (let i: number = 0; i < currentMembers.length; i++) {
dateMembers.push({ formattedText: currentMembers[i].FormattedText, actualText: currentMembers[i].ActualText });
formattedMembers[currentMembers[i].FormattedText] = {};
members[currentMembers[i].ActualText] = {};
}
this.engineModule.fieldList[engine.memberName].dateMember = dateMembers;
this.engineModule.fieldList[engine.memberName].formattedMembers = formattedMembers;
this.engineModule.fieldList[engine.memberName].members = members;
this.pivotButtonModule.updateFilterEvents();
} else {
let fList: IFieldListOptions = PivotUtil.formatFieldList(JSON.parse(engine.fieldList));
if (this.engineModule.fieldList) {
let keys: string[] = Object.keys(this.engineModule.fieldList);
for (let i: number = 0; i < keys.length; i++) {
if (this.engineModule.fieldList[keys[i]] && fList[keys[i]]) {
fList[keys[i]].dateMember = this.engineModule.fieldList[keys[i]].dateMember;
fList[keys[i]].formattedMembers = this.engineModule.fieldList[keys[i]].formattedMembers;
fList[keys[i]].members = this.engineModule.fieldList[keys[i]].members;
}
}
}
this.engineModule.fieldList = fList;
this.engineModule.fields = JSON.parse(engine.fields);
this.engineModule.rowCount = JSON.parse(engine.pivotCount).RowCount;
this.engineModule.columnCount = JSON.parse(engine.pivotCount).ColumnCount;
this.engineModule.rowStartPos = JSON.parse(engine.pivotCount).RowStartPosition;
this.engineModule.colStartPos = JSON.parse(engine.pivotCount).ColumnStartPosition;
this.engineModule.rowFirstLvl = JSON.parse(engine.pivotCount).RowFirstLevel;
this.engineModule.colFirstLvl = JSON.parse(engine.pivotCount).ColumnFirstLevel;
let rowPos: number;
let pivotValues: any = PivotUtil.formatPivotValues(JSON.parse(engine.pivotValue));
for (let rCnt: number = 0; rCnt < pivotValues.length; rCnt++) {
if (pivotValues[rCnt] && pivotValues[rCnt][0] && pivotValues[rCnt][0].axis === 'row') {
rowPos = rCnt;
break;
}
}
this.engineModule.headerContent = PivotUtil.frameContent(pivotValues, 'header', rowPos, this);
this.engineModule.pageSettings = this.pivotGridModule ? this.pivotGridModule.pageSettings : undefined;
let valueSort: any = JSON.parse(engine.dataSourceSettings).ValueSortSettings;
this.engineModule.valueSortSettings = {
headerText: valueSort.HeaderText,
headerDelimiter: valueSort.HeaderDelimiter,
sortOrder: valueSort.SortOrder,
columnIndex: valueSort.ColumnIndex
};
this.engineModule.pivotValues = pivotValues;
}
} catch (error) {
this.engineModule.pivotValues = [];
}
if (this.currentAction !== 'fetchFieldMembers') {
this.initEngine();
if (this.calculatedFieldModule && this.calculatedFieldModule.isRequireUpdate) {
this.calculatedFieldModule.endDialog();
this.calculatedFieldModule.isRequireUpdate = false;
}
if (this.pivotGridModule && this.pivotGridModule.calculatedFieldModule && this.pivotGridModule.calculatedFieldModule.isRequireUpdate) {
this.pivotGridModule.calculatedFieldModule.endDialog();
this.pivotGridModule.calculatedFieldModule.isRequireUpdate = false;
}
}
}
}
private onReadyStateChange(): void {
if (this.request.readyState === XMLHttpRequest.DONE) {
let dataSource: string[][] | IDataSet[] = [];
if (this.dataSourceSettings.type === 'CSV') {
let jsonObject: string[] = this.request.responseText.split(/\r?\n|\r/);
for (let i: number = 0; i < jsonObject.length; i++) {
if (!isNullOrUndefined(jsonObject[i]) && jsonObject[i] !== '') {
(dataSource as string[][]).push(jsonObject[i].split(','));
}
}
} else {
try {
dataSource = JSON.parse(this.request.responseText);
} catch (error) {
dataSource = [];
}
}
if (dataSource && dataSource.length > 0) {
this.setProperties({ dataSourceSettings: { dataSource: dataSource } }, true);
}
this.initialLoad();
}
}
private initialLoad(): void {
this.trigger(events.load, { dataSourceSettings: this.dataSourceSettings }, (observedArgs: LoadEventArgs) => {
this.dataSourceSettings = observedArgs.dataSourceSettings;
addClass([this.element], cls.ROOT);
if (this.enableRtl) {
addClass([this.element], cls.RTL);
} else {
removeClass([this.element], cls.RTL);
}
if (this.isAdaptive) {
addClass([this.element], cls.DEVICE);
} else {
removeClass([this.element], cls.DEVICE);
}
if (this.cssClass) {
addClass([this.element], this.cssClass);
}
this.notify(events.initialLoad, {});
});
}
/**
* Binding events to the Pivot Field List element.
* @hidden
*/
private wireEvent(): void {
this.on(events.initialLoad, this.generateData, this);
this.on(events.dataReady, this.fieldListRender, this);
}
/**
* Unbinding events from the element on widget destroy.
* @hidden
*/
private unWireEvent(): void {
if (this.pivotGridModule && this.pivotGridModule.isDestroyed) { return; }
this.off(events.initialLoad, this.generateData);
this.off(events.dataReady, this.fieldListRender);
}
/**
* Get the properties to be maintained in the persisted state.
* @returns {string}
*/
public getPersistData(): string {
let keyEntity: string[] = ['dataSourceSettings'];
return this.addOnPersist(keyEntity);
}
/**
* Get component name.
* @returns string
* @private
*/
public getModuleName(): string {
return 'pivotfieldlist';
}
/**
* Called internally if any of the property value changed.
* @hidden
*/
public onPropertyChanged(newProp: PivotFieldListModel, oldProp: PivotFieldListModel): void {
let requireRefresh: boolean = false;
for (let prop of Object.keys(newProp)) {
switch (prop) {
case 'locale':
super.refresh();
break;
case 'dataSourceSettings':
if (!isNullOrUndefined(newProp.dataSourceSettings.dataSource) && newProp.dataSourceSettings.groupSettings.length === 0) {
if (!isNullOrUndefined(this.savedDataSourceSettings)) {
PivotUtil.updateDataSourceSettings(this.staticPivotGridModule, this.savedDataSourceSettings);
this.savedDataSourceSettings = undefined;
}
if (newProp.dataSourceSettings.dataSource && (newProp.dataSourceSettings.dataSource as IDataSet[]).length === 0 && !isNullOrUndefined(this.staticPivotGridModule)) {
this.savedDataSourceSettings = PivotUtil.getClonedDataSourceSettings(this.staticPivotGridModule.dataSourceSettings);
this.staticPivotGridModule.setProperties({ dataSourceSettings: { rows: [] } }, true);
this.staticPivotGridModule.setProperties({ dataSourceSettings: { columns: [] } }, true);
this.staticPivotGridModule.setProperties({ dataSourceSettings: { values: [] } }, true);
this.staticPivotGridModule.setProperties({ dataSourceSettings: { filters: [] } }, true);
}
this.engineModule.fieldList = null;
if (!isNullOrUndefined(this.staticPivotGridModule)) {
this.staticPivotGridModule.pivotValues = [];
}
this.initEngine();
}
if (PivotUtil.isButtonIconRefesh(prop, oldProp, newProp)) {
if (this.isPopupView && this.pivotGridModule &&
this.pivotGridModule.showGroupingBar && this.pivotGridModule.groupingBarModule) {
let filters: IFieldOptions[] = PivotUtil.cloneFieldSettings(this.dataSourceSettings.filters);
let values: IFieldOptions[] = PivotUtil.cloneFieldSettings(this.dataSourceSettings.values);
let rows: IFieldOptions[] = PivotUtil.cloneFieldSettings(this.dataSourceSettings.rows);
let columns: IFieldOptions[] = PivotUtil.cloneFieldSettings(this.dataSourceSettings.columns);
this.pivotGridModule.setProperties({ dataSourceSettings: { rows: rows, columns: columns, values: values, filters: filters } }, true);
this.pivotGridModule.axisFieldModule.render();
} else if (!this.isPopupView && this.staticPivotGridModule && !this.staticPivotGridModule.isDestroyed) {
let pivot: PivotView = this.staticPivotGridModule;
if (pivot.showGroupingBar && pivot.groupingBarModule) {
pivot.axisFieldModule.render();
}
if (pivot.showFieldList && pivot.pivotFieldListModule) {
let rows: IFieldOptions[] = PivotUtil.cloneFieldSettings(pivot.dataSourceSettings.rows);
let columns: IFieldOptions[] = PivotUtil.cloneFieldSettings(pivot.dataSourceSettings.columns);
let values: IFieldOptions[] = PivotUtil.cloneFieldSettings(pivot.dataSourceSettings.values);
let filters: IFieldOptions[] = PivotUtil.cloneFieldSettings(pivot.dataSourceSettings.filters);
pivot.pivotFieldListModule.setProperties({ dataSourceSettings: { rows: rows, columns: columns, values: values, filters: filters } }, true);
pivot.pivotFieldListModule.axisFieldModule.render();
if (pivot.pivotFieldListModule.treeViewModule.fieldTable && !pivot.isAdaptive) {
pivot.pivotFieldListModule.notify(events.treeViewUpdate, {});
}
}
}
this.axisFieldModule.render();
if (this.treeViewModule.fieldTable && !this.isAdaptive) {
this.notify(events.treeViewUpdate, {});
}
}
break;
case 'aggregateTypes':
if (this.axisFieldModule) {
this.axisFieldModule.render();
}
if (this.pivotGridModule && this.pivotGridModule.axisFieldModule) {
this.pivotGridModule.setProperties({ aggregateTypes: newProp.aggregateTypes }, true);
this.pivotGridModule.axisFieldModule.render();
}
break;
case 'showValuesButton':
if (this.axisFieldModule) {
this.axisFieldModule.render();
}
if (this.pivotGridModule && this.pivotGridModule.showGroupingBar &&
this.pivotGridModule.groupingBarModule && this.pivotGridModule.axisFieldModule) {
this.pivotGridModule.setProperties({ showValuesButton: newProp.showValuesButton }, true);
this.pivotGridModule.axisFieldModule.render();
}
break;
case 'enableRtl':
if (this.enableRtl) {
addClass([this.element], cls.RTL);
} else {
removeClass([this.element], cls.RTL);
}
requireRefresh = true;
break;
}
if (requireRefresh) {
this.fieldListRender();
}
}
}
/* eslint-disable */
private initEngine(): void {
if (this.dataType === 'pivot') {
let data: any = !isNullOrUndefined(this.dataSourceSettings.dataSource) ? (this.dataSourceSettings.dataSource as IDataSet[])[0] :
!isNullOrUndefined(this.engineModule.data) ? (this.engineModule.data as IDataSet[])[0] : undefined;
if (data && this.pivotCommon) {
let isArray: boolean = Object.prototype.toString.call(data) == '[object Array]';
if (isArray && this.dataSourceSettings.type === 'JSON') {
this.pivotCommon.errorDialog.createErrorDialog(
this.localeObj.getConstant('error'), this.localeObj.getConstant('invalidJSON'));
return;
} else if (!isArray && this.dataSourceSettings.type === 'CSV') {
this.pivotCommon.errorDialog.createErrorDialog(
this.localeObj.getConstant('error'), this.localeObj.getConstant('invalidCSV'));
return;
}
}
}
let args: EnginePopulatingEventArgs = {
dataSourceSettings: PivotUtil.getClonedDataSourceSettings(this.dataSourceSettings)
};
let control: PivotView | PivotFieldList = this.isPopupView ? this.pivotGridModule : this;
control.trigger(events.enginePopulating, args, (observedArgs: EnginePopulatingEventArgs) => {
PivotUtil.updateDataSourceSettings(this, observedArgs.dataSourceSettings);
if (this.dataType === 'pivot') {
if (this.dataSourceSettings.groupSettings && this.dataSourceSettings.groupSettings.length > 0) {
let pivotDataSet: IDataSet[];
pivotDataSet = this.dataSourceSettings.dataSource as IDataSet[];
this.clonedDataSet = (this.clonedDataSet ? this.clonedDataSet : PivotUtil.getClonedData(pivotDataSet)) as IDataSet[];
let dataSourceSettings: IDataOptions = JSON.parse(this.getPersistData()).dataSourceSettings as IDataOptions;
dataSourceSettings.dataSource = [];
this.clonedReport = this.clonedReport ? this.clonedReport : dataSourceSettings;
}
let customProperties: ICustomProperties = this.frameCustomProperties();
customProperties.enableValueSorting = this.staticPivotGridModule ?
this.staticPivotGridModule.enableValueSorting : this.enableValueSorting;
if (this.dataSourceSettings.mode !== 'Server') {
this.engineModule.renderEngine(this.dataSourceSettings as IDataOptions, customProperties, this.getValueCellInfo.bind(this), this.getHeaderSortInfo.bind(this));
}
this.pivotFieldList = this.engineModule.fieldList;
let eventArgs: EnginePopulatedEventArgs = {
pivotFieldList: this.pivotFieldList,
pivotValues: this.engineModule.pivotValues
};
const this$: PivotFieldList = this;
control.trigger(events.enginePopulated, eventArgs, (observedArgs: EnginePopulatedEventArgs) => {
this$.pivotFieldList = observedArgs.pivotFieldList;
this$.engineModule.pivotValues = observedArgs.pivotValues;
this$.notify(events.dataReady, {});
this$.trigger(events.dataBound);
});
} else if (this.dataType === 'olap') {
this.olapEngineModule.renderEngine(this.dataSourceSettings as IDataOptions,
this.frameCustomProperties(this.olapEngineModule.fieldListData, this.olapEngineModule.fieldList), this.getHeaderSortInfo.bind(this));
this.pivotFieldList = this.olapEngineModule.fieldList;
let eventArgs: EnginePopulatedEventArgs = {
pivotFieldList: this.pivotFieldList,
pivotValues: this.olapEngineModule.pivotValues
};
const this$: PivotFieldList = this;
control.trigger(events.enginePopulated, eventArgs, (observedArgs: EnginePopulatedEventArgs) => {
this$.pivotFieldList = observedArgs.pivotFieldList;
this$.olapEngineModule.pivotValues = observedArgs.pivotValues;
this$.notify(events.dataReady, {});
this$.trigger(events.dataBound);
});
}
});
}
/* eslint-enable */
private generateData(): void {
this.pivotFieldList = {};
if (this.dataSourceSettings && (this.dataSourceSettings.dataSource || this.dataSourceSettings.url)) {
if ((this.dataSourceSettings.url !== '' && this.dataType === 'olap') ||
(this.dataSourceSettings.dataSource as IDataSet[]).length > 0) {
if (this.dataType === 'pivot') {
this.engineModule.data = this.dataSourceSettings.dataSource as IDataSet[];
}
this.initEngine();
} else if (this.dataSourceSettings.dataSource instanceof DataManager) {
if (this.dataType === 'pivot' && this.remoteData.length > 0) {
this.engineModule.data = this.remoteData;
this.initEngine();
} else {
setTimeout(this.getData.bind(this), 100);
}
}
} else {
this.notify(events.dataReady, {});
this.trigger(events.dataBound);
}
}
private getValueCellInfo(aggregateObj: AggregateEventArgs): AggregateEventArgs {
let args: AggregateEventArgs = aggregateObj;
this.trigger(events.aggregateCellInfo, args);
return args;
}
private getHeaderSortInfo(sortingObj: HeadersSortEventArgs): HeadersSortEventArgs {
let args: HeadersSortEventArgs = sortingObj;
this.trigger(events.onHeadersSort, args);
return args;
}
private getData(): void {
(this.dataSourceSettings.dataSource as DataManager).executeQuery(new Query()).then(this.executeQuery.bind(this));
}
private executeQuery(e: ReturnOption): void {
this.engineModule.data = (e.result as IDataSet[]);
this.initEngine();
}
private fieldListRender(): void {
this.element.innerHTML = '';
let showDialog: boolean;
if (this.renderMode === 'Popup' && this.dialogRenderer.fieldListDialog && !this.dialogRenderer.fieldListDialog.isDestroyed) {
showDialog = this.dialogRenderer.fieldListDialog.visible;
this.dialogRenderer.fieldListDialog.destroy();
remove(document.getElementById(this.element.id + '_Container'));
}
this.renderModule.render();
if (this.renderMode === 'Popup') {
this.fieldListSpinnerElement = this.dialogRenderer.fieldListDialog.element;
if (showDialog) {
this.dialogRenderer.fieldListDialog.show();
}
} else {
this.fieldListSpinnerElement = this.element.querySelector('.e-pivotfieldlist-container');
}
if (this.spinnerTemplate) {
createSpinner({ target: this.fieldListSpinnerElement as HTMLElement, template: this.spinnerTemplate }, this.createElement);
} else {
createSpinner({ target: this.fieldListSpinnerElement as HTMLElement }, this.createElement);
}
let args: CommonArgs;
args = {
pivotEngine: this.dataType === 'olap' ? this.olapEngineModule : this.engineModule,
dataSourceSettings: this.dataSourceSettings as IDataOptions,
id: this.element.id,
element: document.getElementById(this.element.id + '_Container'),
moduleName: this.getModuleName(),
enableRtl: this.enableRtl,
isAdaptive: this.isAdaptive as boolean,
renderMode: this.renderMode,
localeObj: this.localeObj,
dataType: this.dataType
};
this.pivotCommon = new PivotCommon(args);
this.pivotCommon.control = this;
if (this.allowDeferLayoutUpdate) {
this.clonedDataSource = extend({}, this.dataSourceSettings, null, true) as IDataOptions;
if (this.dataType === 'olap') {
this.clonedFieldListData = PivotUtil.cloneOlapFieldSettings(this.olapEngineModule.fieldListData);
}
this.clonedFieldList = extend({}, this.pivotFieldList, null, true) as IFieldListOptions;
}
}
private getFieldCaption(dataSourceSettings: DataSourceSettingsModel): void {
this.getFields(dataSourceSettings);
if (this.captionData.length > 0) {
let lnt: number = this.captionData.length;
let engineModule: OlapEngine | PivotEngine = this.dataType === 'olap' ? this.olapEngineModule : this.engineModule;
while (lnt--) {
if (this.captionData[lnt]) {
for (let obj of this.captionData[lnt]) {
if (obj) {
if (engineModule.fieldList[obj.name]) {
if (obj.caption) {
engineModule.fieldList[obj.name].caption = obj.caption;
} else {
engineModule.fieldList[obj.name].caption = obj.name;
}
}
}
}
}
}
} else {
return;
}
}
private getFields(dataSourceSettings: DataSourceSettingsModel): void {
this.captionData =
[dataSourceSettings.rows, dataSourceSettings.columns, dataSourceSettings.values, dataSourceSettings.filters] as FieldOptionsModel[][]; /* eslint-disable-line */
}
/* eslint-disable */
/**
* Updates the PivotEngine using dataSource from Pivot Field List component.
* @function updateDataSource
* @returns {void}
* @hidden
*/
public updateDataSource(isTreeViewRefresh?: boolean, isEngineRefresh?: boolean): void {
if (this.pivotGridModule) {
this.pivotGridModule.showWaitingPopup();
}
showSpinner(this.fieldListSpinnerElement as HTMLElement);
let pivot: PivotFieldList = this;
let control: PivotView | PivotFieldList = pivot.isPopupView ? pivot.pivotGridModule : pivot;
//setTimeout(() => {
let isOlapDataRefreshed: boolean = false;
let pageSettings: IPageSettings = pivot.pivotGridModule && pivot.pivotGridModule.enableVirtualization ?
pivot.pivotGridModule.pageSettings : undefined;
let isCalcChange: boolean = Object.keys(pivot.lastCalcFieldInfo).length > 0 ? true : false;
let isSorted: boolean = Object.keys(pivot.lastSortInfo).length > 0 ? true : false;
let isAggChange: boolean = Object.keys(pivot.lastAggregationInfo).length > 0 ? true : false;
let isFiltered: boolean = Object.keys(pivot.lastFilterInfo).length > 0 ? true : false;
let args: EnginePopulatingEventArgs = {
dataSourceSettings: PivotUtil.getClonedDataSourceSettings(pivot.dataSourceSettings)
};
control.trigger(events.enginePopulating, args, (observedArgs: EnginePopulatingEventArgs) => {
if (!(pageSettings && (isSorted || isFiltered || isAggChange || isCalcChange))) {
PivotUtil.updateDataSourceSettings(pivot, observedArgs.dataSourceSettings);
PivotUtil.updateDataSourceSettings(pivot.pivotGridModule, observedArgs.dataSourceSettings);
}
if (isNullOrUndefined(isEngineRefresh)) {
if (pivot.dataType === 'pivot') {
let customProperties: ICustomProperties = pivot.frameCustomProperties();
if (!isSorted) {
customProperties.enableValueSorting = pivot.staticPivotGridModule ?
pivot.staticPivotGridModule.enableValueSorting : pivot.enableValueSorting;
}
else {
if (pivot.pivotGridModule) {
pivot.pivotGridModule.setProperties({ dataSourceSettings: { valueSortSettings: { headerText: '' } } }, true)
}
pivot.setProperties({ dataSourceSettings: { valueSortSettings: { headerText: '' } } }, true);
customProperties.enableValueSorting = false;
}
customProperties.savedFieldList = pivot.pivotFieldList;
if (pageSettings && (isSorted || isFiltered || isAggChange || isCalcChange)) {
let interopArguments: any = {};
if (isSorted) {
pivot.pivotGridModule.setProperties({ dataSourceSettings: { valueSortSettings: { headerText: '' } } }, true);
if (control.dataSourceSettings.mode === 'Server') {
control.getEngine('onSort', null, pivot.lastSortInfo, null, null, null, null);
} else {
pivot.engineModule.onSort(pivot.lastSortInfo);
}
pivot.lastSortInfo = {};
}
if (isFiltered) {
if (control.dataSourceSettings.mode === 'Server') {
control.getEngine('onFilter', null, null, null, null, pivot.lastFilterInfo, null);
} else {
pivot.engineModule.onFilter(pivot.lastFilterInfo, pivot.dataSourceSettings as IDataOptions);
}
pivot.lastFilterInfo = {};
}
if (isAggChange) {
if (control.dataSourceSettings.mode === 'Server') {
control.getEngine('onAggregation', null, null, pivot.lastAggregationInfo, null, null, null);
} else {
pivot.engineModule.onAggregation(pivot.lastAggregationInfo);
}
pivot.lastAggregationInfo = {};
}
if (isCalcChange) {
if (control.dataSourceSettings.mode === 'Server') {
control.getEngine('onCalcOperation', null, null, null, pivot.lastCalcFieldInfo, null, null);
} else {
pivot.engineModule.onCalcOperation(pivot.lastCalcFieldInfo);
}
pivot.lastCalcFieldInfo = {};
}
} else {
if (pivot.dataSourceSettings.mode === 'Server') {
if (isSorted)
control.getEngine('onSort', null, pivot.lastSortInfo, null, null, null, null);
else if (isAggChange)
control.getEngine('onAggregation', null, null, pivot.lastAggregationInfo, null, null, null);
else if (isCalcChange)
control.getEngine('onCalcOperation', null, null, null, pivot.lastCalcFieldInfo, null, null);
else if (isFiltered)
control.getEngine('onFilter', null, null, null, null, pivot.lastFilterInfo, null);
else
control.getEngine('onDrop', null, null, null, null, null, null);
pivot.lastSortInfo = {};
pivot.lastAggregationInfo = {};
pivot.lastCalcFieldInfo = {};
pivot.lastFilterInfo = {};
} else {
pivot.engineModule.renderEngine(pivot.dataSourceSettings as IDataOptions, customProperties, pivot.getValueCellInfo.bind(pivot), pivot.getHeaderSortInfo.bind(pivot));
}
}
} else {
isOlapDataRefreshed = pivot.updateOlapDataSource(pivot, isSorted, isCalcChange, isOlapDataRefreshed);
}
pivot.getFieldCaption(pivot.dataSourceSettings);
} else {
pivot.axisFieldModule.render();
pivot.isRequiredUpdate = false;
}
pivot.enginePopulatedEventMethod(pivot, isTreeViewRefresh, isOlapDataRefreshed);
});
//});
}
/* eslint-enable */
private enginePopulatedEventMethod(pivot: PivotFieldList, isTreeViewRefresh: boolean, isOlapDataRefreshed: boolean): void {
let control: PivotView | PivotFieldList = pivot.isPopupView ? pivot.pivotGridModule : pivot;
let eventArgs: EnginePopulatedEventArgs = {
dataSourceSettings: pivot.dataSourceSettings as IDataOptions,
pivotFieldList: pivot.dataType === 'pivot' ? pivot.engineModule.fieldList : pivot.olapEngineModule.fieldList,
pivotValues: pivot.dataType === 'pivot' ? pivot.engineModule.pivotValues : pivot.olapEngineModule.pivotValues
};
control.trigger(events.enginePopulated, eventArgs, (observedArgs: EnginePopulatedEventArgs) => {
let dataSource: IDataSet[] | DataManager | string[][] = pivot.dataSourceSettings.dataSource;
pivot.dataSourceSettings = observedArgs.dataSourceSettings;
pivot.pivotCommon.dataSourceSettings = pivot.dataSourceSettings as IDataOptions;
pivot.pivotFieldList = observedArgs.pivotFieldList;
if (pivot.dataType === 'olap') {
pivot.olapEngineModule.pivotValues = observedArgs.pivotValues;
pivot.pivotCommon.engineModule = pivot.olapEngineModule;
} else {
pivot.engineModule.pivotValues = observedArgs.pivotValues;
pivot.pivotCommon.engineModule = pivot.engineModule;
}
if (!isTreeViewRefresh && pivot.treeViewModule.fieldTable && !pivot.isAdaptive) {
pivot.notify(events.treeViewUpdate, {});
}
if (pivot.isRequiredUpdate) {
if (pivot.allowDeferLayoutUpdate) {
pivot.clonedDataSource = extend({}, pivot.dataSourceSettings, null, true) as IDataOptions;
if (this.dataType === 'olap') {
this.clonedFieldListData = PivotUtil.cloneOlapFieldSettings(this.olapEngineModule.fieldListData);
}
pivot.clonedFieldList = extend({}, pivot.pivotFieldList, null, true) as IFieldListOptions;
}
pivot.updateView(pivot.pivotGridModule);
} else if (this.isPopupView && pivot.allowDeferLayoutUpdate) {
pivot.pivotGridModule.engineModule = pivot.engineModule;
pivot.pivotGridModule.setProperties({
dataSourceSettings: (<{ [key: string]: Object }>pivot.dataSourceSettings).properties as IDataOptions /* eslint-disable-line */
}, true);
pivot.pivotGridModule.notify(events.uiUpdate, pivot);
hideSpinner(pivot.fieldListSpinnerElement as HTMLElement);
}
if (this.isPopupView && pivot.pivotGridModule &&
pivot.pivotGridModule.allowDeferLayoutUpdate && !pivot.isRequiredUpdate) {
hideSpinner(pivot.fieldListSpinnerElement as HTMLElement);
pivot.pivotGridModule.hideWaitingPopup();
}
pivot.isRequiredUpdate = true;
if (!pivot.pivotGridModule || isOlapDataRefreshed) {
hideSpinner(pivot.fieldListSpinnerElement as HTMLElement);
} else {
pivot.pivotGridModule.fieldListSpinnerElement = pivot.fieldListSpinnerElement as HTMLElement;
}
});
let actionName: string = this.getActionCompleteName();
this.actionObj.actionName = actionName;
if (this.actionObj.actionName) {
this.actionCompleteMethod();
}
}
private updateOlapDataSource(pivot: PivotFieldList, isSorted: boolean, isCalcChange: boolean, isOlapDataRefreshed: boolean): boolean {
let customProperties: IOlapCustomProperties =
pivot.frameCustomProperties(pivot.olapEngineModule.fieldListData, pivot.olapEngineModule.fieldList);
customProperties.savedFieldList = pivot.pivotFieldList;
if (isCalcChange || isSorted) {
pivot.olapEngineModule.savedFieldList = pivot.pivotFieldList;
pivot.olapEngineModule.savedFieldListData = pivot.olapEngineModule.fieldListData;
if (isCalcChange) {
pivot.olapEngineModule.updateCalcFields(pivot.dataSourceSettings as IDataOptions, pivot.lastCalcFieldInfo);
pivot.lastCalcFieldInfo = {};
isOlapDataRefreshed = pivot.olapEngineModule.dataFields[pivot.lastCalcFieldInfo.name] ? false : true;
if (pivot.pivotGridModule) {
pivot.pivotGridModule.hideWaitingPopup();
}
} else {
pivot.olapEngineModule.onSort(pivot.dataSourceSettings as IDataOptions);
}
} else {
pivot.olapEngineModule.renderEngine(pivot.dataSourceSettings as IDataOptions, customProperties, pivot.getHeaderSortInfo.bind(pivot));
}
pivot.lastSortInfo = {};
pivot.lastAggregationInfo = {};
pivot.lastCalcFieldInfo = {};
pivot.lastFilterInfo = {};
return isOlapDataRefreshed;
}
/**
* Updates the Pivot Field List component using dataSource from PivotView component.
* @function update
* @param {PivotView} control - Pass the instance of pivot table component.
* @returns {void}
*/
public update(control: PivotView): void {
if (control) {
this.clonedDataSet = control.clonedDataSet;
this.clonedReport = control.clonedReport;
this.setProperties({ dataSourceSettings: control.dataSourceSettings, showValuesButton: control.showValuesButton }, true);
this.engineModule = control.engineModule;
this.olapEngineModule = control.olapEngineModule;
this.dataType = control.dataType;
this.pivotFieldList = this.dataType === 'olap' ? control.olapEngineModule.fieldList : control.engineModule.fieldList;
if (this.isPopupView) {
this.pivotGridModule = control;
} else {
this.staticPivotGridModule = control;
}
this.getFieldCaption(control.dataSourceSettings);
this.pivotCommon.engineModule = this.dataType === 'olap' ? this.olapEngineModule : this.engineModule;
this.pivotCommon.dataSourceSettings = this.dataSourceSettings as IDataOptions;
this.pivotCommon.control = this;
if (this.treeViewModule.fieldTable && !this.isAdaptive) {
this.notify(events.treeViewUpdate, {});
}
this.axisFieldModule.render();
if (!this.isPopupView && this.allowDeferLayoutUpdate) {
this.clonedDataSource = extend({}, this.dataSourceSettings, null, true) as IDataOptions;
if (this.dataType === 'olap') {
this.clonedFieldListData = PivotUtil.cloneOlapFieldSettings(this.olapEngineModule.fieldListData);
}
this.clonedFieldList = extend({}, this.pivotFieldList, null, true) as IFieldListOptions;
}
}
}
/**
* Updates the PivotView component using dataSource from Pivot Field List component.
* @function updateView
* @param {PivotView} control - Pass the instance of pivot table component.
* @returns {void}
*/
public updateView(control: PivotView): void {
if (control) {
control.clonedDataSet = this.clonedDataSet;
control.clonedReport = this.clonedReport;
control.setProperties({ dataSourceSettings: this.dataSourceSettings, showValuesButton: this.showValuesButton }, true);
control.engineModule = this.engineModule;
control.olapEngineModule = this.olapEngineModule;
control.dataType = this.dataType;
if (!this.pivotChange) {
control.pivotValues = this.dataType === 'olap' ? this.olapEngineModule.pivotValues : this.engineModule.pivotValues;
}
let eventArgs: FieldListRefreshedEventArgs = {
dataSourceSettings: PivotUtil.getClonedDataSourceSettings(control.dataSourceSettings),
pivotValues: control.pivotValues
};
control.trigger(events.fieldListRefreshed, eventArgs);
if (!this.isPopupView) {
this.staticPivotGridModule = control;
control.isStaticRefresh = true;
}
control.dataBind();
}
}
/* eslint-disable-next-line */
/**
* Called internally to trigger populate event.
* @hidden
*/
public triggerPopulateEvent(): void {
let control: PivotView | PivotFieldList = this.isPopupView ? this.pivotGridModule : this;
let eventArgs: EnginePopulatedEventArgs = {
dataSourceSettings: this.dataSourceSettings as IDataOptions,
pivotFieldList: this.dataType === 'olap' ? this.olapEngineModule.fieldList : this.engineModule.fieldList,
pivotValues: this.dataType === 'olap' ? this.olapEngineModule.pivotValues : this.engineModule.pivotValues
};
control.trigger(events.enginePopulated, eventArgs, (observedArgs: EnginePopulatedEventArgs) => {
this.dataSourceSettings = observedArgs.dataSourceSettings;
this.pivotFieldList = observedArgs.pivotFieldList;
if (this.dataType === 'olap') {
this.olapEngineModule.pivotValues = observedArgs.pivotValues;
} else {
this.engineModule.pivotValues = observedArgs.pivotValues;
}
});
}
/** @hidden */
public actionBeginMethod(): boolean {
let eventArgs: PivotActionBeginEventArgs = {
dataSourceSettings: PivotUtil.getClonedDataSourceSettings(this.dataSourceSettings),
actionName: this.actionObj.actionName,
fieldInfo: this.actionObj.fieldInfo,
cancel: false
}
let control: PivotView | PivotFieldList = this.isPopupView ? this.pivotGridModule : this;
control.trigger(events.actionBegin, eventArgs);
return eventArgs.cancel;
}
/** @hidden */
public actionCompleteMethod(): void {
let eventArgs: PivotActionCompleteEventArgs = {
dataSourceSettings: PivotUtil.getClonedDataSourceSettings(this.dataSourceSettings),
actionName: this.actionObj.actionName,
fieldInfo: this.actionObj.fieldInfo,
actionInfo: this.actionObj.actionInfo
}
let control: PivotView | PivotFieldList = this.isPopupView ? this.pivotGridModule : this;
control.trigger(events.actionComplete, eventArgs);
this.actionObj.actionName = '';
this.actionObj.actionInfo = undefined;
this.actionObj.fieldInfo = undefined;
}
/** @hidden */
public actionFailureMethod(error: Error): void {
let eventArgs: PivotActionFailureEventArgs = {
actionName: this.actionObj.actionName,
errorInfo: error
}
let control: PivotView | PivotFieldList = this.isPopupView ? this.pivotGridModule : this;
control.trigger(events.actionFailure, eventArgs);
}
/** @hidden */
public getActionCompleteName(): any {
let actionName: string = (this.actionObj.actionName == events.openCalculatedField) ? events.calculatedFieldApplied : (this.actionObj.actionName == events.editCalculatedField) ? events.calculatedFieldEdited : (this.actionObj.actionName == events.sortField) ? events.fieldSorted
: (this.actionObj.actionName == events.filterField) ? events.fieldFiltered : (this.actionObj.actionName == events.removeField) ? events.fieldRemoved : (this.actionObj.actionName == events.aggregateField) ? events.fieldAggregated : this.actionObj.actionName == events.sortFieldTree ? events.fieldTreeSorted : this.actionObj.actionName;
return actionName;
}
/**
* Destroys the Field Table component.
* @function destroy
* @returns {void}
*/
public destroy(): void {
this.unWireEvent();
if (this.engineModule && !this.destroyEngine) {
this.engineModule.fieldList = {};
this.engineModule.rMembers = null;
this.engineModule.cMembers = null;
(this.engineModule as any).valueMatrix = null;
(this.engineModule as any).indexMatrix = null;
this.engineModule = {} as PivotEngine;
}
if (this.olapEngineModule && !this.destroyEngine) {
this.olapEngineModule.fieldList = {};
this.olapEngineModule = {} as OlapEngine;
}
if (this.pivotFieldList) {
this.pivotFieldList = {};
}
if (this.captionData) {
this.captionData = null;
}
if (this.contextMenuModule) {
this.contextMenuModule.destroy();
}
if (this.treeViewModule) {
this.treeViewModule.destroy();
}
if (this.pivotButtonModule) {
this.pivotButtonModule.destroy();
}
if (this.pivotCommon) {
this.pivotCommon.destroy();
}
if (this.dialogRenderer) {
this.dialogRenderer.destroy();
}
if (this.calculatedFieldModule) {
this.calculatedFieldModule.destroy();
}
super.destroy();
if (this.contextMenuModule) {
this.contextMenuModule = null;
}
if (this.treeViewModule) {
this.treeViewModule = null;
}
if (this.pivotButtonModule) {
this.pivotButtonModule = null;
}
if (this.pivotCommon) {
this.pivotCommon = null;
}
if (this.dialogRenderer) {
this.dialogRenderer = null;
}
if (this.calculatedFieldModule) {
this.calculatedFieldModule = null;
}
if (this.axisFieldModule) {
this.axisFieldModule = null;
}
if (this.axisTableModule) {
this.axisTableModule = null;
}
if (this.renderModule) {
this.renderModule = null;
}
if (this.clonedDataSet) {
this.clonedDataSet = null;
}
if (this.clonedReport) {
this.clonedReport = null;
}
if (this.clonedFieldList) {
this.clonedFieldList = null;
}
if (this.clonedFieldListData) {
this.clonedFieldListData = null;
}
if (this.localeObj) {
this.localeObj = null;
}
if (this.defaultLocale) {
this.defaultLocale = null;
}
this.element.innerHTML = '';
removeClass([this.element], cls.ROOT);
removeClass([this.element], cls.RTL);
removeClass([this.element], cls.DEVICE);
}
} | the_stack |
import '../fixtures/window';
import { Editor, engineConfig } from '@alilc/lowcode-editor-core';
import { LowCodePluginManager } from '../../src/plugin/plugin-manager';
import { ILowCodePluginContext, ILowCodePluginManager } from '../../src/plugin/plugin-types';
const editor = new Editor();
describe('plugin 测试', () => {
let pluginManager: ILowCodePluginManager;
beforeEach(() => {
pluginManager = new LowCodePluginManager(editor).toProxy();
});
afterEach(() => {
pluginManager.dispose();
});
it('注册插件,插件参数生成函数能被调用,且能拿到正确的 ctx ', () => {
const mockFn = jest.fn();
const creater = (ctx: ILowCodePluginContext) => {
mockFn(ctx);
return {
init: jest.fn(),
};
};
creater.pluginName = 'demo1';
pluginManager.register(creater);
const [expectedCtx] = mockFn.mock.calls[0];
expect(expectedCtx).toHaveProperty('project');
expect(expectedCtx).toHaveProperty('setters');
expect(expectedCtx).toHaveProperty('material');
expect(expectedCtx).toHaveProperty('hotkey');
expect(expectedCtx).toHaveProperty('plugins');
expect(expectedCtx).toHaveProperty('skeleton');
expect(expectedCtx).toHaveProperty('logger');
expect(expectedCtx).toHaveProperty('config');
expect(expectedCtx).toHaveProperty('event');
expect(expectedCtx).toHaveProperty('preference');
});
it('注册插件,调用插件 init 方法', async () => {
const mockFn = jest.fn();
const creater = (ctx: ILowCodePluginContext) => {
return {
init: mockFn,
exports() {
return {
x: 1,
y: 2,
};
},
};
};
creater.pluginName = 'demo1';
pluginManager.register(creater);
await pluginManager.init();
expect(pluginManager.size).toBe(1);
expect(pluginManager.has('demo1')).toBeTruthy();
expect(pluginManager.get('demo1')!.isInited()).toBeTruthy();
expect(pluginManager.demo1).toBeTruthy();
expect(pluginManager.demo1.x).toBe(1);
expect(pluginManager.demo1.y).toBe(2);
expect(mockFn).toHaveBeenCalled();
});
it('注册插件,调用 setDisabled 方法', async () => {
const mockFn = jest.fn();
const creater = (ctx: ILowCodePluginContext) => {
return {
init: mockFn,
};
};
creater.pluginName = 'demo1';
pluginManager.register(creater);
await pluginManager.init();
expect(pluginManager.demo1).toBeTruthy();
pluginManager.setDisabled('demo1', true);
expect(pluginManager.demo1).toBeUndefined();
});
it('删除插件,调用插件 destroy 方法', async () => {
const mockFn = jest.fn();
const creater = (ctx: ILowCodePluginContext) => {
return {
init: jest.fn(),
destroy: mockFn,
};
};
creater.pluginName = 'demo1';
pluginManager.register(creater);
await pluginManager.init();
await pluginManager.delete('demo1');
expect(mockFn).toHaveBeenCalled();
await pluginManager.delete('non-existing');
});
it('dep 依赖', async () => {
const mockFn = jest.fn();
const creater1 = (ctx: ILowCodePluginContext) => {
return {
// dep: ['demo2'],
init: () => mockFn('demo1'),
};
};
creater1.pluginName = 'demo1';
creater1.meta = {
dependencies: ['demo2'],
};
pluginManager.register(creater1);
const creater2 = (ctx: ILowCodePluginContext) => {
return {
init: () => mockFn('demo2'),
};
};
creater2.pluginName = 'demo2';
pluginManager.register(creater2);
await pluginManager.init();
expect(mockFn).toHaveBeenNthCalledWith(1, 'demo2');
expect(mockFn).toHaveBeenNthCalledWith(2, 'demo1');
});
it('version 依赖', async () => {
const mockFn = jest.fn();
const creater1 = (ctx: ILowCodePluginContext) => {
return {
init: () => mockFn('demo1'),
};
};
creater1.pluginName = 'demo1';
creater1.meta = {
engines: {
lowcodeEngine: '^1.1.0',
}
};
engineConfig.set('ENGINE_VERSION', '1.0.1');
console.log('version: ', engineConfig.get('ENGINE_VERSION'));
// not match should skip
pluginManager.register(creater1).catch(e => {
expect(e).toEqual(new Error('plugin demo1 skipped, engine check failed, current engine version is 1.0.1, meta.engines.lowcodeEngine is ^1.1.0'));
});
expect(pluginManager.plugins.length).toBe(0);
const creater2 = (ctx: ILowCodePluginContext) => {
return {
init: () => mockFn('demo2'),
};
};
creater2.pluginName = 'demo2';
creater2.meta = {
engines: {
lowcodeEngine: '^1.0.1',
}
};
engineConfig.set('ENGINE_VERSION', '1.0.3');
pluginManager.register(creater2);
expect(pluginManager.plugins.length).toBe(1);
const creater3 = (ctx: ILowCodePluginContext) => {
return {
init: () => mockFn('demo3'),
};
};
creater3.pluginName = 'demo3';
creater3.meta = {
engines: {
lowcodeEngine: '1.x',
}
};
engineConfig.set('ENGINE_VERSION', '1.1.1');
pluginManager.register(creater3);
expect(pluginManager.plugins.length).toBe(2);
});
it('autoInit 功能', async () => {
const mockFn = jest.fn();
const creater = (ctx: ILowCodePluginContext) => {
return {
init: mockFn,
};
};
creater.pluginName = 'demo1';
await pluginManager.register(creater, { autoInit: true });
expect(mockFn).toHaveBeenCalled();
});
it('插件不会重复 init,除非强制重新 init', async () => {
const mockFn = jest.fn();
const creater = (ctx: ILowCodePluginContext) => {
return {
name: 'demo1',
init: mockFn,
};
};
creater.pluginName = 'demo1';
pluginManager.register(creater);
await pluginManager.init();
expect(mockFn).toHaveBeenCalledTimes(1);
pluginManager.get('demo1')!.init();
expect(mockFn).toHaveBeenCalledTimes(1);
pluginManager.get('demo1')!.init(true);
expect(mockFn).toHaveBeenCalledTimes(2);
});
it('默认情况不允许重复注册', async () => {
const mockFn = jest.fn();
const mockPlugin = (ctx: ILowCodePluginContext) => {
return {
init: mockFn,
};
};
mockPlugin.pluginName = 'demoDuplicated';
pluginManager.register(mockPlugin);
pluginManager.register(mockPlugin).catch(e => {
expect(e).toEqual(new Error('Plugin with name demoDuplicated exists'));
});
await pluginManager.init();
});
it('插件增加 override 参数时可以重复注册', async () => {
const mockFn = jest.fn();
const mockPlugin = (ctx: ILowCodePluginContext) => {
return {
init: mockFn,
};
};
mockPlugin.pluginName = 'demoOverride';
pluginManager.register(mockPlugin);
pluginManager.register(mockPlugin, { override: true });
await pluginManager.init();
});
it('插件增加 override 参数时可以重复注册, 被覆盖的如果已初始化,会被销毁', async () => {
const mockInitFn = jest.fn();
const mockDestroyFn = jest.fn();
const mockPlugin = (ctx: ILowCodePluginContext) => {
return {
init: mockInitFn,
destroy: mockDestroyFn,
};
};
mockPlugin.pluginName = 'demoOverride';
await pluginManager.register(mockPlugin, { autoInit: true });
expect(mockInitFn).toHaveBeenCalledTimes(1);
await pluginManager.register(mockPlugin, { override: true });
expect(mockDestroyFn).toHaveBeenCalledTimes(1);
await pluginManager.init();
});
it('内部事件机制', async () => {
const mockFn = jest.fn();
const creater = (ctx: ILowCodePluginContext) => {
return {
};
}
creater.pluginName = 'demo1';
pluginManager.register(creater);
await pluginManager.init();
const plugin = pluginManager.get('demo1')!;
plugin.on('haha', mockFn);
plugin.emit('haha', 1, 2, 3);
expect(mockFn).toHaveBeenCalledTimes(1);
expect(mockFn).toHaveBeenCalledWith(1, 2, 3);
plugin.removeAllListeners('haha');
plugin.emit('haha', 1, 2, 3);
expect(mockFn).toHaveBeenCalledTimes(1);
});
it('dispose 方法', async () => {
const creater = (ctx: ILowCodePluginContext) => {
return {
};
}
creater.pluginName = 'demo1';
pluginManager.register(creater);
await pluginManager.init();
const plugin = pluginManager.get('demo1')!;
await plugin.dispose();
expect(pluginManager.has('demo1')).toBeFalsy();
});
it('注册插件,调用插件 init 方法并传入preference,可以成功获取', async () => {
const mockFn = jest.fn();
const mockFnForCtx = jest.fn();
const mockPreference = new Map();
mockPreference.set('demo1',{
key1: 'value for key1',
key2: false,
key3: 123,
key5: 'value for key5, but declared, should not work'
});
mockPreference.set('demo2',{
key1: 'value for demo2.key1',
key2: false,
key3: 123,
});
const creater = (ctx: ILowCodePluginContext) => {
mockFnForCtx(ctx);
return {
init: jest.fn(),
};
};
creater.pluginName = 'demo1';
creater.meta = {
preferenceDeclaration: {
title: 'demo1的的参数定义',
properties: [
{
key: 'key1',
type: 'string',
description: 'this is description for key1',
},
{
key: 'key2',
type: 'boolean',
description: 'this is description for key2',
},
{
key: 'key3',
type: 'number',
description: 'this is description for key3',
},
{
key: 'key4',
type: 'string',
description: 'this is description for key4',
},
],
},
}
pluginManager.register(creater);
expect(mockFnForCtx).toHaveBeenCalledTimes(1);
await pluginManager.init(mockPreference);
// creater only get excuted once
expect(mockFnForCtx).toHaveBeenCalledTimes(1);
const [expectedCtx, expectedOptions] = mockFnForCtx.mock.calls[0];
expect(expectedCtx).toHaveProperty('preference');
// test normal case
expect(expectedCtx.preference.getPreferenceValue('key1', 'default')).toBe('value for key1');
// test default value logic
expect(expectedCtx.preference.getPreferenceValue('key4', 'default for key4')).toBe('default for key4');
// test undeclared key
expect(expectedCtx.preference.getPreferenceValue('key5', 'default for key5')).toBeUndefined();
});
}); | the_stack |
export as namespace AthenaJS;
export function Dom(sel?: string | HTMLElement): _Dom<HTMLElement>;
export class Scene {
constructor(options?: SceneOptions);
map: Map;
hudScene: Scene | null;
running: boolean;
opacity: number;
addObject(object: Drawable | Drawable[], layer?: number): Scene;
animate(fxName: string, options: EffectOptions): Promise;
bindEvents(eventList: string): void;
debug(bool?: boolean): void;
fadeIn(duration: number): Promise;
fadeOut(duration: number): Promise;
fadeInAndOut(inDuration: number, delay: number, outDuration: number): Promise;
getOpacity(): number;
getPlayTime(): number;
load(type: string, src: string, id?: string): void;
loadAudio(src: string, id?: string): void;
loadImage(src: string, id?: string): void;
loadMap(src: string, id?: string): void;
notify(name: string, data?: JSObject): void;
removeObject(obj: Drawable): void;
setBackgroundImage(image: string|HTMLImageElement): void;
setLayerPriority(layer: number, background: boolean): void;
setMap(map: Map | JSObject, x?: number, y?: number): void;
setOpacity(opacity: number): void;
setup(): void;
start(): void;
stop(): void;
}
export class Game {
constructor(options: GameOptions);
bindEvents(eventList: string): void;
setScene(scene: Scene): void;
toggleFullscreen(): void;
toggleSound(bool: boolean): void;
toggleTileInspector(bool: boolean): void;
togglePause(): void;
scene: Scene;
sound: boolean;
}
export class Drawable {
constructor(type: string, options: DrawableOptions);
addChild(child: Drawable): void;
animate(name: string, options: JSObject): Promise;
center(): Drawable;
destroy(data?: any): void;
moveTo(x: number, y: number, duration?: number): Drawable;
notify(id: string, data?: JSObject): void;
onCollision(object: Drawable): void;
onEvent(eventType: string, data?: JSObject): void;
playSound(id: string, options?: { pan?: boolean, loop?: false }): void;
setBehavior(behavior: string | { new(sprite: Drawable, options?: JSObject): Behavior }, options?: JSObject): void;
setScale(scale: number): void;
getCurrentWidth(): number;
getCurrentHeight(): number;
getProperty(prop: string): any;
setProperty(prop: string, value: any): void;
setMask(mask: MaskOptions | null, exclude?: boolean): void;
stopAnimate(endValue?: number): void;
reset(): void;
show(): void;
hide(): void;
type: string;
width: number;
height: number;
x: number;
y: number;
vx: number;
vy: number;
canCollide: boolean;
currentMovement: string;
running: boolean;
movable: boolean;
behavior: Behavior;
currentMap: Map;
data: JSObject;
visible: boolean;
}
export interface MaskOptions {
x: number;
y: number;
width: number;
height: number;
}
export interface MenuItem {
text: string;
selectable: boolean;
visible: boolean;
active?: boolean;
}
export interface MenuOptions {
title: string;
color: string;
menuItems: MenuItem[];
}
export class Menu extends Drawable {
constructor(id: string, options: MenuOptions);
nextItem(): void;
getSelectedItemIndex(): number;
}
export class SimpleText extends Drawable {
constructor(type: string, simpleTextOptions: SimpleTextOptions);
getCurrentOffsetX(): number;
getCurrentOffsetY(): number;
setColor(color: string): void;
setSize(width: number, height: number): void;
setText(text: string): void;
}
export class Paint extends Drawable {
constructor(type: string, paintOptions: PaintOptions);
arc(cx: number, cy: number, r: number, starteAngle: number, endAngle: number, fillStyle: string, borderSize: number): void;
fill(color?: string): void;
circle(cx: number, cy: number, r: number, fillStyle?: string, borderWidth?: number, borderStyle?: string): void;
rect(x: number, y: number, width: number, height: number, color: string): void;
name: string;
color: string;
}
export class BitmapText extends Drawable {
constructor(type: string, textOptions: BitmapTextOptions);
setText(text: string): void;
}
export class Sprite extends Drawable {
constructor(type: string, spriteOptions: SpriteOptions);
addAnimation(name: string, imgPath: string, options: AnimOptions): void;
setAnimation(name: string, fn?: Callback, frameNum?: number, revert?: boolean): void;
clearMove(): void;
}
export interface pixelPos {
x: number;
y: number;
}
export class Map {
constructor(options: MapOptions);
addObject(obj: Drawable, layerIndex?: number): void;
addTileSet(tiles: TileDesc[]): void;
checkMatrixForCollision(buffer: number[], matrixWidth: number, x: number, y: number, behavior: number): boolean;
clear(tileNum?: number, behavior?: number): void;
getTileBehaviorAtIndex(col: number, row: number): number;
getTileIndexFromPixel(x: number, y: number): pixelPos;
moveTo(x: number, y: number): void;
respawn(): void;
setData(map: Uint8Array, behaviors: Uint8Array): void;
setEasing(easing: string): void;
shift(startLine: number, height: number): void;
updateTile(col: number, row: number, tileNum?: number, behavior?: number): void;
duration: number;
numRows: number;
numCols: number;
width: number;
height: number;
tileWidth: number;
tileHeight: number;
}
export class Tile {
constructor(options: JSObject);
static TYPE: {
AIR: 1;
WALL: 2;
LADDER: 3;
};
offsetX: number;
offsetY: number;
width: number;
height: number;
inertia: number;
upCollide: boolean;
downCollide: boolean;
}
export interface TileDesc {
offsetX: number;
offsetY: number;
width: number;
height: number;
}
export interface MapOptions {
src: string;
tileWidth: number;
tileHeight: number;
width: number;
height: number;
viewportW?: number;
viewportH?: number;
buffer?: ArrayBuffer;
}
export interface FXInstance {
addFX(fxName: string, FxClass: { new(options: EffectOptions, display: Display): Effect }): void;
}
export const FX: FXInstance;
export class _FX {
/**
* Creates the FX class, adding the linear easing
*/
constructor();
/**
* Add a new Effect
*/
addFX(fxName: string, FxClass: { new(): Effect }): void;
/**
* Retrieve an effect Class by its name
*
*/
getEffect(fxName: string): Effect;
/**
* Add a new easing function for other objects to use
*
*/
addEasing(easingName: string, easingFn: (x?: number, t?: number, b?: number, c?: number, d?: number) => void): void;
/**
* Retrieves an easing function
*
*/
getEasing(easingName: string): (x?: number, t?: number, b?: number, c?: number, d?: number) => void;
}
export interface EffectOptions {
easing?: string;
when?: string;
startValue?: number;
endValue?: number;
duration?: number;
}
export class Effect {
width: number;
height: number;
buffer: RenderingContext;
animProgress: number;
startValue: number;
ended: boolean;
/**
* This the class constructor. Default options are:
*
*/
constructor(options: EffectOptions, display: Display);
/**
* Changes the easing function used for the ffect
*
*/
setEasing(easing: (x?: number, t?: number, b?: number, c?: number, d?: number) => void): void;
/**
* Called when the ffect is started.
*
* This method can be overriden but the super should always be called
*/
start(): Promise;
/**
* called when the effect is stopped
*/
stop(object: any, setEndValue: any): void;
/**
* Calculates current animation process
*
* This method can be overridden but the super should always be calle first
*/
process(ctx: RenderingContext, fxCtx?: RenderingContext, obj?: any): boolean;
}
// why do we need this ?
export type RenderingContext = CanvasRenderingContext2D;
export interface DisplayOptions {
width: number;
height: number;
type: string;
layers?: boolean[];
name: string;
}
export class Display {
/**
* Creates a new Display instance
*
*/
constructor(options: DisplayOptions, target: string | HTMLElement);
/**
* Creates a new (offscreen) drawing buffer
*
*/
getBuffer(width: number, height: number): RenderingContext;
/**
* Toggles fullscreen display scaling
*/
toggleFullscreen(): void;
/**
* Changes the zIndex property of the specified layer canvas
*
*/
setLayerZIndex(layer: number, zIndex: number): void;
/**
* Clears a canvas display buffer
*
*/
clearScreen(ctx: RenderingContext): void;
/**
* Clears every rendering buffer, including the special fxCtx one
*/
clearAllScreens(): void;
/**
* Changes the (CSS) opacity of a canvas
*
*/
setCanvasOpacity(canvas: HTMLElement, opacity: number): void;
/**
* Renders the specified scene
*
*/
renderScene(scene: Scene): void;
/**
* Prepares the canvas before rendering images.
*
* Explanation: during development, I noticed that the very first time
* the ctx.drawImage() was used to draw onto a canvas, it took a very long time,
* like at least 10ms for a very small 32x32 pixels drawImage.
*
* Subsequent calls do not have this problem and are instant.
* Maybe some ColorFormat conversion happens.
*
* This method makes sure that when the game starts rendering, we don't have
* any of these delays that can impact gameplay and alter the gameplay experience
* in a negative way.
*/
prepareCanvas(resources: JSObject[]): void;
/**
* Starts an animation on the display
*
*/
animate(fxName: string, options: EffectOptions, context: RenderingContext): Promise;
/**
* stops current animation
*
* TODO
*/
stopAnimate(fxName?: string): void;
/**
* Executes an effect on a frame at a given time
*
*/
executeFx(ctx: RenderingContext, fxCtx: RenderingContext, obj: Drawable, time: number, when: string): void;
/**
* Clears every display layer and clears fx queues
*/
clearDisplay(): void;
}
export const InputManager: _InputManager;
export class MapEvent {
/**
* Creates a new MapEvent
*
*/
constructor(map: Map);
/**
* Resets the MapEvent switches, events and items
*/
reset(): void;
/**
* Adds a new [`Drawable`]{#item} onto the map
*
*/
addItem(id: string, item: Drawable): void;
/**
* Returns an item
*
*/
getItem(id: string): Drawable | undefined;
// TODO: ability to trigger an event once a switch has been modified
setSwitch(id: string, bool: boolean): void;
toggleSwitch(id: string): void;
/**
* Retrieves a switch from the map using its id
*
*/
getSwitch(id: string): any;
/**
* checks of conditions of specified trigger are valid
*
*/
checkConditions(trigger: JSObject): boolean;
handleAction(options: JSObject): void;
handleEvent(options: JSObject): boolean;
/**
* Schedule adding a new object to the map
*/
scheduleSprite(spriteId: string, spriteOptions: JSObject, delay: number): Drawable;
/**
* Add a new wave of objects to the map
* Used for example when the player triggers apparition of several enemies or bonuses
*
* @related {Wave}
*/
handleWave(options: JSObject): boolean;
endWave(): void;
triggerEvent(id: string): void;
isEventTriggered(id: string): boolean;
}
export class Behavior {
vx: number;
vy: number;
gravity: number;
sprite: Drawable;
constructor(sprite: Drawable, options?: JSObject);
onUpdate(timestamp: number): void;
onVXChange?(vx: number): void;
onVYChange?(vy: number): void;
/**
* Returns current mapEvent
*
*/
getMapEvent(): MapEvent;
reset(): void;
}
export interface _AudioManager {
audioCache: JSObject;
enabled: boolean;
/**
* Adds a new sound element to the audio cache.
* *Note* if a sound with the same id has already been added, it will be replaced
* by the new one.
*
*/
addSound(id: string, element: HTMLAudioElement): void;
/**
* Toggles global sound playback
*
*/
toggleSound(bool: boolean): void;
/**
* Plays the specified sound with `id`.
*
*/
play(id: string, loop?: boolean, volume?: number, panning?: number): any;
/**
* Stops playing the sound id
*
*/
stop(id: string, instanceId: any): void;
}
export const AudioManager: _AudioManager;
export interface Res {
id: string;
type: string;
src: string;
}
export type Callback = (...args: any[]) => void;
export interface _NotificationManager {
notify(name: string, data?: JSObject): void;
}
export const NotificationManager: _NotificationManager;
export interface _ResourceManager {
addResources(resource: Res, group?: string): Promise;
getCanvasFromImage(image: HTMLImageElement): HTMLCanvasElement;
getResourceById(id: string, group?: string, fullObject?: boolean): any;
loadResources(group: string, progressCb?: Callback, errorCb?: Callback): void;
loadImage(res: Res, group?: string): Promise;
loadAudio(res: Res, group?: string): Promise;
newResourceFromPool(id: string): any;
registerScript(id: string, elt: any, poolSize?: number): void;
}
export const ResourceManager: _ResourceManager;
export interface _InputManager {
/**
* A list of common keyCodes
*/
KEYS: {
'UP': 38,
'DOWN': 40,
'LEFT': 37,
'RIGHT': 39,
'SPACE': 32,
'ENTER': 13,
'ESCAPE': 27,
'CTRL': 17
};
/**
* List of common pad buttons
*/
PAD_BUTTONS: {
32: 1, // Face (main) buttons
FACE_0: 1,
FACE_3: 2,
FACE_4: 3,
LEFT_SHOULDER: 4, // Top shoulder buttons
RIGHT_SHOULDER: 5,
LEFT_SHOULDER_BOTTOM: 6, // Bottom shoulder buttons
RIGHT_SHOULDER_BOTTOM: 7,
SELECT: 8,
START: 9,
LEFT_ANALOGUE_STICK: 10, // Analogue sticks (if depressible)
RIGHT_ANALOGUE_STICK: 11,
38: 12, // Directional (discrete) pad
40: 13,
37: 14,
39: 15
};
axes: JSObject;
newGamepadPollDelay: number;
gamepadSupport: boolean;
recording: boolean;
playingEvents: boolean;
playingPos: number;
/*recordedEvents: Array,*/
pad: null;
latches: JSObject;
keyPressed: JSObject;
padPressed: JSObject;
keyCb: JSObject;
enabled: boolean;
inputMode: string;
// virtual joystick instance
dPadJoystick: null;
jPollInterval: number;
/**
* Initializes the InputManager with a reference to the game.
*
* This method prepares the InputManager by reseting keyboard states/handlers and
* set current inputMode
*
*/
init(): void;
/**
* Starts recording input events. They are stored into `InputManager.recordedEvents`
*/
startRecordingEvents(): void;
/**
* Stops recording events.
*/
stopRecordingEvents(): void;
/**
* After events have been reccorded they can be played back using this method.
*/
playRecordedEvents(): void;
/**
* Sets next key states using recorded events
*
* TODO: add an optional callback to be called at the end of the playback
* so that demo can be looped.
*/
nextRecordedEvents(): void;
/**
* Saves current event state onto the recordedEvents stack
*/
/**
* Changes input mode
*
*/
setInputMode(mode: string): void;
/**
* Returns an object with the state of all keys
*/
getAllKeysStatus(): JSObject;
getKeyStatus(key: string, latch: boolean): boolean;
isKeyDown(key: string|number, latch?: boolean): boolean;
/**
* Install callback that gets called when a key is pressed/released
*
*/
installKeyCallback(key: string, event: string, callback: (key: string, event: string) => void): void;
removeKeyCallback(key: string, event: string, callback: () => void): void;
clearEvents(): void;
}
export interface Promise {
then(val?: () => any): Promise;
catch(val?: () => any): Promise;
}
/* Deferred */
export class Deferred {
constructor();
/**
* Creates and immediately resolves a new deferred.
*
*/
static resolve(val?: any): Promise;
promise: Promise;
reject(val: any): void;
resolve(val: any): void;
}
/* Dom support */
export interface _Dom<TElement> extends Iterable<TElement> {
[key: number]: TElement;
length: number;
css(prop: string, val: string): _Dom<TElement>;
css(prop: JSObject): _Dom<TElement>;
css(prop: string): string|null;
find(selector: string): _Dom<TElement>;
appendTo(selector: string | _Dom<TElement> | HTMLElement): _Dom<TElement>;
attr(att: string, val: string): _Dom<TElement>;
attr(att: JSObject): _Dom<TElement>;
addClass(classes: string): _Dom<TElement>;
removeClass(classes: string): _Dom<TElement>;
html(str: string): _Dom<TElement>;
show(): _Dom<TElement>;
hide(): _Dom<TElement>;
}
/* Game Support */
export interface GameOptions {
name: string;
showFps: boolean;
width: number;
height: number;
debug: boolean;
scene?: Scene;
target?: string | HTMLElement;
sound?: boolean;
}
export interface SceneOptions {
name?: string;
resources?: Res[];
opacity?: number;
layers?: number;
hudScene?: Scene;
}
export interface DrawableOptions {
x?: number;
y?: number;
behavior?: { new(sprite: Drawable, options?: JSObject): Behavior };
canCollide?: boolean;
canCollideFriendBullet?: boolean;
collideGroup?: number;
objectId?: string;
layer?: number;
map?: Map;
visible?: boolean;
pool?: number;
}
export interface SimpleTextOptions extends DrawableOptions {
text?: string;
width?: number;
height?: number;
fontFace?: string;
fontSize?: string;
fontStyle?: string;
fontWeight?: string;
align?: string;
color?: string;
}
export interface PaintOptions extends DrawableOptions {
width?: number;
height?: number;
color?: string;
lineHeight?: number;
}
export interface BitmapTextOptions extends DrawableOptions {
width?: number;
height?: number;
offsetX: number;
startY: number;
charWidth: number;
charHeight: number;
imageId?: string;
imageSrc?: string;
scrollOffsetX?: number;
scrollOffsetY?: number;
text?: string;
size?: string;
}
export interface SpriteOptions extends DrawableOptions {
easing?: string;
imageId?: string;
animations?: Animations;
data?: JSObject;
}
export interface AnimOptions {
numFrames: number;
frameWidth: number;
frameHeight: number;
frameDuration: number;
offsetX?: number;
offsetY?: number;
frameSpacing?: number;
}
export interface AnimationObject {
frameDuration?: number;
frames: Array<{
offsetX: number;
offsetY: number;
width: number;
height: number;
hitBox?: {
x: number;
y: number;
x2: number;
y2: number;
},
plane?: number;
}>;
loop?: number;
speed?: number;
}
export interface JSObject {
[key: string]: any;
}
export interface Animations {
[key: string]: AnimationObject;
}
export interface GameEvent {
type: string;
data: JSObject;
} | the_stack |
import React from 'react';
import { mount, shallow, ReactWrapper } from 'enzyme';
import sinon from 'sinon';
import ContextMenu, { ContextMenuProps, ContextMenuState } from '../ContextMenu';
import Button, { ButtonType } from '../../button/Button';
import Menu from '../../menu/Menu';
const sandbox = sinon.sandbox.create();
describe('components/context-menu/ContextMenu', () => {
const FakeButton = (props: Record<string, string | boolean>) => (
<Button className="bdl-FakeButton" isLoading={false} showRadar={false} type={ButtonType.BUTTON} {...props}>
Some Button
</Button>
);
FakeButton.displayName = 'FakeButton';
const FakeMenu = (props: Record<string, string | boolean>) => (
<Menu {...props}>
<ul role="menu">Some Menu</ul>
</Menu>
);
FakeMenu.displayName = 'FakeMenu';
afterEach(() => {
sandbox.verifyAndRestore();
});
describe('render()', () => {
test('should throw an error when passed less than 2 children', () => {
expect(() => {
shallow(
<ContextMenu>
<FakeButton />
</ContextMenu>,
);
}).toThrow();
});
test('should throw an error when passed more than 2 children', () => {
expect(() => {
shallow(
<ContextMenu>
<FakeButton />
<FakeMenu />
<div />
</ContextMenu>,
);
}).toThrow();
});
test('should correctly render a single child button with correct props', () => {
const wrapper = shallow<ContextMenu>(
<ContextMenu>
<FakeButton />
<FakeMenu />
</ContextMenu>,
);
const instance = wrapper.instance();
const button = wrapper.find(FakeButton);
expect(button.length).toBe(1);
expect(button.prop('id')).toEqual(instance.menuTargetID);
expect(button.key()).toEqual(instance.menuTargetID);
});
test('should not render child menu when menu is closed', () => {
const wrapper = shallow(
<ContextMenu>
<FakeButton />
<FakeMenu />
</ContextMenu>,
);
const menu = wrapper.find(FakeMenu);
expect(menu.length).toBe(0);
});
test('should correctly render a single child menu with correct props when menu is open', () => {
const wrapper = shallow<ContextMenu>(
<ContextMenu>
<FakeButton />
<FakeMenu />
</ContextMenu>,
);
wrapper.setState({ isOpen: true });
const instance = wrapper.instance();
const menu = wrapper.find(FakeMenu);
expect(menu.length).toBe(1);
expect(menu.prop('id')).toEqual(instance.menuID);
expect(menu.key()).toEqual(instance.menuID);
expect(menu.prop('initialFocusIndex')).toEqual(null);
});
test('should render TetherComponent with correct props with correct default values', () => {
const wrapper = shallow(
<ContextMenu>
<FakeButton />
<FakeMenu />
</ContextMenu>,
);
expect(wrapper.is('TetherComponent')).toBe(true);
expect(wrapper.prop('attachment')).toEqual('top left');
expect(wrapper.prop('targetAttachment')).toEqual('top left');
expect(wrapper.prop('constraints')).toEqual([]);
});
test('should render TetherComponent with constraints when specified', () => {
const constraints = [
{
to: 'window',
attachment: 'together',
},
];
const wrapper = shallow(
<ContextMenu constraints={constraints}>
<FakeButton />
<FakeMenu />
</ContextMenu>,
);
expect(wrapper.prop('constraints')).toEqual(constraints);
});
test('should render TetherComponent with correct target offset when set', () => {
const targetOffset = '10px 20px';
const wrapper = shallow(
<ContextMenu>
<FakeButton />
<FakeMenu />
</ContextMenu>,
);
wrapper.setState({ targetOffset });
expect(wrapper.prop('targetOffset')).toEqual(targetOffset);
});
});
describe('closeMenu()', () => {
test('should call setState() with correct values', () => {
const wrapper = shallow<ContextMenu>(
<ContextMenu>
<FakeButton />
<FakeMenu />
</ContextMenu>,
);
const instance = wrapper.instance();
sandbox
.mock(instance)
.expects('setState')
.withArgs({
isOpen: false,
});
instance.closeMenu();
});
test('should call onMenuClose() if onMenuClose prop is set', () => {
const onMenuCloseSpy = jest.fn();
const wrapper = shallow<ContextMenu>(
<ContextMenu onMenuClose={onMenuCloseSpy}>
<FakeButton />
<FakeMenu />
</ContextMenu>,
);
wrapper.instance().closeMenu();
expect(onMenuCloseSpy).toBeCalled();
});
});
describe('handleMenuClose()', () => {
test('should call closeMenu() and focusTarget() when called', () => {
const onMenuCloseSpy = jest.fn();
const onFocusTargetSpy = jest.fn();
const wrapper = shallow<ContextMenu>(
<ContextMenu onMenuClose={onMenuCloseSpy}>
<FakeButton />
<FakeMenu />
</ContextMenu>,
);
wrapper.setState({ isOpen: true });
const instance = wrapper.instance();
instance.focusTarget = onFocusTargetSpy;
instance.handleMenuClose();
expect(onMenuCloseSpy).toHaveBeenCalled();
expect(onFocusTargetSpy).toHaveBeenCalled();
});
});
describe('componentDidUpdate()', () => {
test('should add click and contextmenu listeners when opening menu', () => {
const wrapper = mount<ContextMenu>(
<ContextMenu>
<FakeButton />
<FakeMenu />
</ContextMenu>,
);
document.addEventListener = jest.fn();
wrapper.setState({ isOpen: true });
expect(document.addEventListener).toHaveBeenCalledWith('click', expect.anything(), expect.anything());
expect(document.addEventListener).toHaveBeenCalledWith('contextmenu', expect.anything(), expect.anything());
});
test('should remove click and contextmenu listeners when closing menu', () => {
const wrapper = mount<ContextMenu>(
<ContextMenu>
<FakeButton />
<FakeMenu />
</ContextMenu>,
);
wrapper.setState({ isOpen: true });
const instance = wrapper.instance();
document.removeEventListener = jest.fn();
instance.closeMenu();
expect(document.removeEventListener).toHaveBeenCalledWith(
'contextmenu',
expect.anything(),
expect.anything(),
);
expect(document.removeEventListener).toHaveBeenCalledWith('click', expect.anything(), expect.anything());
});
test('should not do anything opening a menu when menu is already open', () => {
const wrapper = mount(
<ContextMenu>
<FakeButton />
<FakeMenu />
</ContextMenu>,
);
wrapper.setState({ isOpen: true });
const instance = wrapper.instance();
document.addEventListener = jest.fn();
document.removeEventListener = jest.fn();
instance.setState({ isOpen: true });
expect(document.addEventListener).not.toHaveBeenCalledWith('click', expect.anything(), expect.anything());
expect(document.addEventListener).not.toHaveBeenCalledWith(
'contextmenu',
expect.anything(),
expect.anything(),
);
expect(document.removeEventListener).not.toHaveBeenCalledWith(
'contextmenu',
expect.anything(),
expect.anything(),
);
expect(document.removeEventListener).not.toHaveBeenCalledWith(
'click',
expect.anything(),
expect.anything(),
);
});
test('should close menu when context menu becomes disabled and the menu is currently open', () => {
const wrapper = shallow(
<ContextMenu>
<FakeButton />
<FakeMenu />
</ContextMenu>,
);
wrapper.setState({ isOpen: true });
const instance = wrapper.instance() as ContextMenu;
sandbox.mock(instance).expects('handleMenuClose');
instance.componentDidUpdate({ isDisabled: true } as ContextMenuProps, { isOpen: true } as ContextMenuState);
});
});
describe('componentWillUnmount()', () => {
test('should not do anything when menu is closed', () => {
const wrapper = mount(
<ContextMenu>
<FakeButton />
<FakeMenu />
</ContextMenu>,
);
const documentMock = sandbox.mock(document);
documentMock
.expects('removeEventListener')
.withArgs('contextmenu')
.never();
documentMock
.expects('removeEventListener')
.withArgs('click')
.never();
wrapper.unmount();
});
test('should remove listeners when menu is open', () => {
const wrapper = mount(
<ContextMenu>
<FakeButton />
<FakeMenu />
</ContextMenu>,
);
wrapper.setState({ isOpen: true });
const documentMock = sandbox.mock(document);
documentMock.expects('removeEventListener').withArgs('contextmenu');
documentMock.expects('removeEventListener').withArgs('click');
wrapper.unmount();
});
});
describe('tests requiring body mounting', () => {
let attachTo: HTMLDivElement;
let wrapper: ReactWrapper | null = null;
/**
* Helper method to mount things to the correct DOM element
* This makes it easier to clean up after ourselves after each test
*/
const mountToBody = (component: React.ReactElement) => mount(component, { attachTo });
const preventDefaultSpy = jest.fn();
beforeEach(() => {
// Set up a place to mount
attachTo = document.createElement('div');
attachTo.setAttribute('data-mounting-point', '');
document.body.appendChild(attachTo);
});
afterEach(() => {
// Unmount and remove the mounting point after each test
if (wrapper) {
wrapper.unmount();
wrapper = null;
}
document.body.removeChild(attachTo);
});
describe('handleContextMenu()', () => {
test('should be no-op when props.isDisabled is true', () => {
wrapper = mountToBody(
<ContextMenu isDisabled>
<FakeButton />
<FakeMenu />
</ContextMenu>,
);
wrapper.find(FakeButton).simulate('contextmenu', {
preventDefault: preventDefaultSpy,
});
expect(wrapper.state('isOpen')).toBe(false);
expect(preventDefaultSpy).not.toHaveBeenCalled();
});
test('should call setState() with correct values', () => {
wrapper = mountToBody(
<ContextMenu>
<FakeButton />
<FakeMenu />
</ContextMenu>,
);
const instance = wrapper.instance() as ContextMenu;
const menuTargetEl = document.getElementById(instance.menuTargetID) as HTMLDivElement;
menuTargetEl.getBoundingClientRect = jest.fn(() => {
return { left: 5, top: 10 } as DOMRect;
});
wrapper.find(FakeButton).simulate('contextmenu', {
clientX: 10,
clientY: 20,
preventDefault: preventDefaultSpy,
});
expect(wrapper.state('isOpen')).toBe(true);
expect(wrapper.state('targetOffset')).toEqual('10px 5px');
});
test('should call onMenuOpen handler when given', () => {
const onMenuOpenSpy = jest.fn();
wrapper = mountToBody(
<ContextMenu onMenuOpen={onMenuOpenSpy}>
<FakeButton />
<FakeMenu />
</ContextMenu>,
);
wrapper.find(FakeButton).simulate('contextmenu', {
preventDefault: () => null,
});
expect(onMenuOpenSpy).toBeCalled();
});
});
describe('handleDocumentClick()', () => {
test('should call closeMenu() when event target is not within the menu', () => {
const closeMenuSpy = jest.fn();
wrapper = mountToBody(
<ContextMenu>
<FakeButton />
<FakeMenu />
</ContextMenu>,
);
const instance = wrapper.instance() as ContextMenu;
instance.closeMenu = closeMenuSpy;
const handleContextMenuEvent = ({
clientX: 10,
clientY: 15,
preventDefault: preventDefaultSpy,
} as unknown) as MouseEvent;
instance.handleContextMenu(handleContextMenuEvent);
const documentClickEvent = ({
target: document.createElement('div'),
} as unknown) as MouseEvent;
instance.handleDocumentClick(documentClickEvent);
expect(closeMenuSpy).toHaveBeenCalled();
});
test('should not call closeMenu() when event target is within the menu', () => {
const closeMenuSpy = jest.fn();
wrapper = mountToBody(
<ContextMenu>
<FakeButton />
<FakeMenu />
</ContextMenu>,
);
const instance = wrapper.instance() as ContextMenu;
instance.closeMenu = closeMenuSpy;
const handleContextMenuEvent = ({
clientX: 10,
clientY: 15,
preventDefault: preventDefaultSpy,
} as unknown) as MouseEvent;
instance.handleContextMenu(handleContextMenuEvent);
const documentClickEvent = ({
target: document.getElementById(instance.menuID),
} as unknown) as MouseEvent;
instance.handleDocumentClick(documentClickEvent);
expect(closeMenuSpy).not.toHaveBeenCalled();
});
});
describe('focusTarget()', () => {
test('should focus the menu target when called', () => {
const onFocusTargetSpy = jest.fn();
wrapper = mountToBody(
<ContextMenu>
<FakeButton />
<FakeMenu />
</ContextMenu>,
);
const instance = wrapper.instance() as ContextMenu;
const menuTargetEl = document.getElementById(instance.menuTargetID) as HTMLButtonElement;
menuTargetEl.focus = onFocusTargetSpy;
instance.focusTarget();
expect(onFocusTargetSpy).toHaveBeenCalled();
});
});
});
}); | the_stack |
require('./link-view.css');
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Expression, $, find } from 'plywood';
import { Timezone } from 'chronoshift';
import { classNames } from '../../utils/dom/dom';
import { Fn } from '../../../common/utils/general/general';
import { Colors, Clicker, Essence, Timekeeper, Filter, FilterClause, Stage, Measure,
VisualizationProps, Collection, CollectionTile, User, Customization } from '../../../common/models/index';
import * as localStorage from '../../utils/local-storage/local-storage';
import { STRINGS } from "../../config/constants";
import { ManualFallback, PinboardPanel, Preset, ResizeHandle, Dropdown } from '../../components/index';
import { getVisualizationComponent } from '../../visualizations/index';
import { LinkHeaderBar } from './link-header-bar/link-header-bar';
var $maxTime = $(FilterClause.MAX_TIME_REF_NAME);
var latestPresets: Preset[] = [
{ name: STRINGS.last5Minutes, selection: $maxTime.timeRange('PT5M', -1) },
{ name: STRINGS.lastHour, selection: $maxTime.timeRange('PT1H', -1) },
{ name: STRINGS.lastDay, selection: $maxTime.timeRange('P1D', -1) },
{ name: STRINGS.lastWeek, selection: $maxTime.timeRange('P1W', -1) }
];
export interface LinkViewLayout {
linkPanelWidth: number;
pinboardWidth: number;
}
export interface LinkViewProps extends React.Props<any> {
timekeeper: Timekeeper;
collection: Collection;
user?: User;
hash: string;
updateViewHash: (newHash: string) => void;
changeHash: (newHash: string, force?: boolean) => void;
getUrlPrefix?: () => string;
onNavClick?: Fn;
customization?: Customization;
stateful: boolean;
}
export interface LinkViewState {
linkTile?: CollectionTile;
essence?: Essence;
visualizationStage?: Stage;
menuStage?: Stage;
layout?: LinkViewLayout;
deviceSize?: string;
}
const MIN_PANEL_WIDTH = 240;
const MAX_PANEL_WIDTH = 400;
export class LinkView extends React.Component<LinkViewProps, LinkViewState> {
private clicker: Clicker;
constructor() {
super();
this.state = {
linkTile: null,
essence: null,
visualizationStage: null,
menuStage: null,
layout: this.getStoredLayout()
};
var clicker = {
changeFilter: (filter: Filter, colors?: Colors) => {
var { essence } = this.state;
essence = essence.changeFilter(filter);
if (colors) essence = essence.changeColors(colors);
this.setState({ essence });
},
changeTimeSelection: (selection: Expression) => {
var { essence } = this.state;
this.setState({ essence: essence.changeTimeSelection(selection) });
},
changeColors: (colors: Colors) => {
var { essence } = this.state;
this.setState({ essence: essence.changeColors(colors) });
},
changePinnedSortMeasure: (measure: Measure) => {
var { essence } = this.state;
this.setState({ essence: essence.changePinnedSortMeasure(measure) });
},
toggleMeasure: (measure: Measure) => {
var { essence } = this.state;
this.setState({ essence: essence.toggleSelectedMeasure(measure) });
},
changeHighlight: (owner: string, measure: string, delta: Filter) => {
var { essence } = this.state;
this.setState({ essence: essence.changeHighlight(owner, measure, delta) });
},
acceptHighlight: () => {
var { essence } = this.state;
this.setState({ essence: essence.acceptHighlight() });
},
dropHighlight: () => {
var { essence } = this.state;
this.setState({ essence: essence.dropHighlight() });
}
};
this.clicker = clicker;
this.globalResizeListener = this.globalResizeListener.bind(this);
}
componentWillMount() {
var { hash, collection, updateViewHash } = this.props;
var linkTile = collection.findByName(hash);
if (!linkTile) {
linkTile = collection.getDefaultTile();
updateViewHash(linkTile.name);
}
this.setState({
linkTile,
essence: linkTile.essence
});
}
componentDidMount() {
window.addEventListener('resize', this.globalResizeListener);
this.globalResizeListener();
}
componentWillReceiveProps(nextProps: LinkViewProps) {
const { hash, collection } = this.props;
if (hash !== nextProps.hash) {
var linkTile = collection.findByName(hash);
this.setState({ linkTile });
}
}
componentWillUpdate(nextProps: LinkViewProps, nextState: LinkViewState): void {
const { updateViewHash } = this.props;
const { linkTile } = this.state;
if (updateViewHash && !nextState.linkTile.equals(linkTile)) {
updateViewHash(nextState.linkTile.name);
}
}
componentWillUnmount() {
window.removeEventListener('resize', this.globalResizeListener);
}
globalResizeListener() {
var { container, visualization } = this.refs;
var containerDOM = ReactDOM.findDOMNode(container);
var visualizationDOM = ReactDOM.findDOMNode(visualization);
if (!containerDOM || !visualizationDOM) return;
let deviceSize = 'large';
if (window.innerWidth <= 1250) deviceSize = 'medium';
if (window.innerWidth <= 1080) deviceSize = 'small';
this.setState({
deviceSize,
menuStage: Stage.fromClientRect(containerDOM.getBoundingClientRect()),
visualizationStage: Stage.fromClientRect(visualizationDOM.getBoundingClientRect())
});
}
selectLinkItem(linkTile: CollectionTile) {
const { essence } = this.state;
var newEssence = linkTile.essence;
if (essence.dataCube.getPrimaryTimeExpression()) {
newEssence = newEssence.changeTimeSelection(essence.getPrimaryTimeSelection());
}
this.setState({
linkTile,
essence: newEssence
});
}
goToCubeView() {
var { changeHash, getUrlPrefix } = this.props;
var { essence } = this.state;
changeHash(`${essence.dataCube.name}/${essence.toHash()}`, true);
}
changeTimezone(newTimezone: Timezone): void {
const { essence } = this.state;
const newEssence = essence.changeTimezone(newTimezone);
this.setState({ essence: newEssence });
}
getStoredLayout(): LinkViewLayout {
return localStorage.get('link-view-layout') || {linkPanelWidth: 240, pinboardWidth: 240};
}
storeLayout(layout: LinkViewLayout) {
localStorage.set('link-view-layout', layout);
}
onLinkPanelResize(value: number) {
let { layout } = this.state;
layout.linkPanelWidth = value;
this.setState({layout});
this.storeLayout(layout);
}
onPinboardPanelResize(value: number) {
let { layout } = this.state;
layout.pinboardWidth = value;
this.setState({layout});
this.storeLayout(layout);
}
onPanelResizeEnd() {
this.globalResizeListener();
}
selectPreset(p: Preset) {
this.clicker.changeTimeSelection(p.selection);
}
renderPresets() {
const { essence } = this.state;
const PresetDropdown = Dropdown.specialize<Preset>();
var selected = find(latestPresets, p => p.selection.equals(essence.getPrimaryTimeSelection()));
return <PresetDropdown
items={latestPresets}
selectedItem={selected}
equal={(a, b) => {
if (a === b) return true;
if (!a !== !b) return false;
return a.selection === b.selection;
}
}
renderItem={(p) => p ? p.name : ""}
onSelect={this.selectPreset.bind(this)}
/>;
}
renderLinkPanel(style: React.CSSProperties) {
const { collection } = this.props;
const { linkTile } = this.state;
var groupId = 0;
var lastGroup: string = null;
var items: JSX.Element[] = [];
collection.tiles.forEach(li => {
// Add a group header if needed
if (lastGroup !== li.group) {
items.push(<div
className="link-group-title"
key={'group_' + groupId}
>
{li.group}
</div>);
groupId++;
lastGroup = li.group;
}
items.push(<div
className={classNames('link-item', { selected: li === linkTile })}
key={'li_' + li.name}
onClick={this.selectLinkItem.bind(this, li)}
>
{li.title}
</div>);
});
return <div className="link-panel" style={style}>
<div className="link-container">
{items}
</div>
</div>;
}
render() {
var clicker = this.clicker;
var { timekeeper, getUrlPrefix, onNavClick, collection, user, customization, stateful } = this.props;
var { deviceSize, linkTile, essence, visualizationStage, layout } = this.state;
if (!linkTile) return null;
var { visualization } = essence;
var visElement: JSX.Element = null;
if (essence.visResolve.isReady() && visualizationStage) {
var visProps: VisualizationProps = {
clicker,
timekeeper,
essence,
stage: visualizationStage
};
visElement = React.createElement(getVisualizationComponent(visualization), visProps);
}
var manualFallback: JSX.Element = null;
if (essence.visResolve.isManual()) {
manualFallback = React.createElement(ManualFallback, {
clicker,
essence
});
}
var styles = {
linkMeasurePanel: {width: layout.linkPanelWidth},
centerPanel: {left: layout.linkPanelWidth, right: layout.pinboardWidth},
pinboardPanel: {width: layout.pinboardWidth}
};
if (deviceSize === 'small') {
styles = {
linkMeasurePanel: {width: 200},
centerPanel: {left: 200, right: 200},
pinboardPanel: {width: 200}
};
}
return <div className='link-view'>
<LinkHeaderBar
title={collection.title}
user={user}
onNavClick={onNavClick}
onExploreClick={this.goToCubeView.bind(this)}
getUrlPrefix={getUrlPrefix}
customization={customization}
changeTimezone={this.changeTimezone.bind(this)}
timezone={essence.timezone}
stateful={stateful}
/>
<div className="container" ref='container'>
{this.renderLinkPanel(styles.linkMeasurePanel)}
{deviceSize !== 'small' ? <ResizeHandle
side="left"
initialValue={layout.linkPanelWidth}
onResize={this.onLinkPanelResize.bind(this)}
onResizeEnd={this.onPanelResizeEnd.bind(this)}
min={MIN_PANEL_WIDTH}
max={MAX_PANEL_WIDTH}
/> : null}
<div className='center-panel' style={styles.centerPanel}>
<div className='center-top-bar'>
<div className='link-title'>{linkTile.title}</div>
<div className='link-description'>{linkTile.description}</div>
<div className="right-align">
{this.renderPresets()}
</div>
</div>
<div className='center-main'>
<div className='visualization' ref='visualization'>{visElement}</div>
{manualFallback}
</div>
</div>
{deviceSize !== 'small' ? <ResizeHandle
side="right"
initialValue={layout.pinboardWidth}
onResize={this.onPinboardPanelResize.bind(this)}
onResizeEnd={this.onPanelResizeEnd.bind(this)}
min={MIN_PANEL_WIDTH}
max={MAX_PANEL_WIDTH}
/> : null}
<PinboardPanel
style={styles.pinboardPanel}
clicker={clicker}
essence={essence}
timekeeper={timekeeper}
getUrlPrefix={getUrlPrefix}
/>
</div>
</div>;
}
} | the_stack |
import assert from 'assert'
import zip from 'lodash/zip'
import { getWellDepth } from '@opentrons/shared-data'
import { AIR_GAP_OFFSET_FROM_TOP } from '../../constants'
import * as errorCreators from '../../errorCreators'
import { getPipetteWithTipMaxVol } from '../../robotStateSelectors'
import {
blowoutUtil,
curryCommandCreator,
getDispenseAirGapLocation,
reduceCommandCreators,
} from '../../utils'
import {
airGap,
aspirate,
delay,
dispense,
dispenseAirGap,
dropTip,
replaceTip,
touchTip,
moveToWell,
} from '../atomic'
import { mixUtil } from './mix'
import type {
TransferArgs,
CurriedCommandCreator,
CommandCreator,
CommandCreatorError,
} from '../../types'
export const transfer: CommandCreator<TransferArgs> = (
args,
invariantContext,
prevRobotState
) => {
/**
Transfer will iterate through a set of 1 or more source and destination wells.
For each pair, it will aspirate from the source well, then dispense into the destination well.
This pair of 1 source well and 1 dest well is internally called a "sub-transfer".
If the volume to aspirate from a source well exceeds the max volume of the pipette,
then each sub-transfer will be chunked into multiple asp-disp, asp-disp commands.
A single uniform volume will be aspirated from every source well and dispensed into every dest well.
In other words, all the sub-transfers will use the same uniform volume.
=====
For transfer, changeTip means:
* 'always': before each aspirate, get a fresh tip
* 'once': get a new tip at the beginning of the transfer step, and use it throughout
* 'never': reuse the tip from the last step
* 'perSource': change tip each time you encounter a new source well (including the first one)
* 'perDest': change tip each time you encounter a new destination well (including the first one)
NOTE: In some situations, different changeTip options have equivalent outcomes. That's OK.
*/
assert(
args.sourceWells.length === args.destWells.length,
`Transfer command creator expected N:N source-to-dest wells ratio. Got ${args.sourceWells.length}:${args.destWells.length}`
)
// TODO Ian 2018-04-02 following ~10 lines are identical to first lines of consolidate.js...
const actionName = 'transfer'
const errors: CommandCreatorError[] = []
if (
!prevRobotState.pipettes[args.pipette] ||
!invariantContext.pipetteEntities[args.pipette]
) {
// bail out before doing anything else
errors.push(
errorCreators.pipetteDoesNotExist({
actionName,
pipette: args.pipette,
})
)
}
if (!args.sourceLabware || !prevRobotState.labware[args.sourceLabware]) {
errors.push(
errorCreators.labwareDoesNotExist({
actionName,
labware: args.sourceLabware,
})
)
}
if (errors.length > 0)
return {
errors,
}
const pipetteSpec = invariantContext.pipetteEntities[args.pipette].spec
// TODO: BC 2019-07-08 these argument names are a bit misleading, instead of being values bound
// to the action of aspiration of dispensing in a given command, they are actually values bound
// to a given labware associated with a command (e.g. Source, Destination). For this reason we
// currently remapping the inner mix values. Those calls to mixUtil should become easier to read
// when we decide to rename these fields/args... probably all the way up to the UI level.
const {
aspirateDelay,
dispenseDelay,
aspirateFlowRateUlSec,
aspirateOffsetFromBottomMm,
blowoutFlowRateUlSec,
blowoutOffsetFromTopMm,
dispenseFlowRateUlSec,
dispenseOffsetFromBottomMm,
} = args
const aspirateAirGapVolume = args.aspirateAirGapVolume || 0
const dispenseAirGapVolume = args.dispenseAirGapVolume || 0
const effectiveTransferVol =
getPipetteWithTipMaxVol(args.pipette, invariantContext) -
aspirateAirGapVolume
const pipetteMinVol = pipetteSpec.minVolume
const chunksPerSubTransfer = Math.ceil(args.volume / effectiveTransferVol)
const lastSubTransferVol =
args.volume - (chunksPerSubTransfer - 1) * effectiveTransferVol
// volume of each chunk in a sub-transfer
let subTransferVolumes: number[] = Array(chunksPerSubTransfer - 1)
.fill(effectiveTransferVol)
.concat(lastSubTransferVol)
if (chunksPerSubTransfer > 1 && lastSubTransferVol < pipetteMinVol) {
// last chunk volume is below pipette min, split the last
const splitLastVol = (effectiveTransferVol + lastSubTransferVol) / 2
subTransferVolumes = Array(chunksPerSubTransfer - 2)
.fill(effectiveTransferVol)
.concat(splitLastVol)
.concat(splitLastVol)
}
// @ts-expect-error(SA, 2021-05-05): zip can return undefined so this really should be Array<[string | undefined, string | undefined]>
const sourceDestPairs: Array<[string, string]> = zip(
args.sourceWells,
args.destWells
)
let prevSourceWell: string | null = null
let prevDestWell: string | null = null
const commandCreators = sourceDestPairs.reduce(
(
outerAcc: CurriedCommandCreator[],
wellPair: [string, string],
pairIdx: number
): CurriedCommandCreator[] => {
const [sourceWell, destWell] = wellPair
const sourceLabwareDef =
invariantContext.labwareEntities[args.sourceLabware].def
const destLabwareDef =
invariantContext.labwareEntities[args.destLabware].def
const airGapOffsetSourceWell =
getWellDepth(sourceLabwareDef, sourceWell) + AIR_GAP_OFFSET_FROM_TOP
const airGapOffsetDestWell =
getWellDepth(destLabwareDef, destWell) + AIR_GAP_OFFSET_FROM_TOP
const commands = subTransferVolumes.reduce(
(
innerAcc: CurriedCommandCreator[],
subTransferVol: number,
chunkIdx: number
): CurriedCommandCreator[] => {
const isInitialSubtransfer = pairIdx === 0 && chunkIdx === 0
const isLastPair = pairIdx + 1 === sourceDestPairs.length
const isLastChunk = chunkIdx + 1 === subTransferVolumes.length
let changeTipNow = false // 'never' by default
if (args.changeTip === 'always') {
changeTipNow = true
} else if (args.changeTip === 'once') {
changeTipNow = isInitialSubtransfer
} else if (args.changeTip === 'perSource') {
changeTipNow = sourceWell !== prevSourceWell
} else if (args.changeTip === 'perDest') {
changeTipNow = isInitialSubtransfer || destWell !== prevDestWell
}
const tipCommands: CurriedCommandCreator[] = changeTipNow
? [
curryCommandCreator(replaceTip, {
pipette: args.pipette,
}),
]
: []
const preWetTipCommands =
args.preWetTip && chunkIdx === 0
? mixUtil({
pipette: args.pipette,
labware: args.sourceLabware,
well: sourceWell,
volume: Math.max(subTransferVol),
times: 1,
aspirateOffsetFromBottomMm,
dispenseOffsetFromBottomMm: aspirateOffsetFromBottomMm,
aspirateFlowRateUlSec,
dispenseFlowRateUlSec,
aspirateDelaySeconds: aspirateDelay?.seconds,
dispenseDelaySeconds: dispenseDelay?.seconds,
})
: []
const mixBeforeAspirateCommands =
args.mixBeforeAspirate != null
? mixUtil({
pipette: args.pipette,
labware: args.sourceLabware,
well: sourceWell,
volume: args.mixBeforeAspirate.volume,
times: args.mixBeforeAspirate.times,
aspirateOffsetFromBottomMm,
dispenseOffsetFromBottomMm: aspirateOffsetFromBottomMm,
aspirateFlowRateUlSec,
dispenseFlowRateUlSec,
aspirateDelaySeconds: aspirateDelay?.seconds,
dispenseDelaySeconds: dispenseDelay?.seconds,
})
: []
const delayAfterAspirateCommands =
aspirateDelay != null
? [
curryCommandCreator(moveToWell, {
pipette: args.pipette,
labware: args.sourceLabware,
well: sourceWell,
offset: {
x: 0,
y: 0,
z: aspirateDelay.mmFromBottom,
},
}),
curryCommandCreator(delay, {
commandCreatorFnName: 'delay',
description: null,
name: null,
meta: null,
wait: aspirateDelay.seconds,
}),
]
: []
const touchTipAfterAspirateCommands = args.touchTipAfterAspirate
? [
curryCommandCreator(touchTip, {
pipette: args.pipette,
labware: args.sourceLabware,
well: sourceWell,
offsetFromBottomMm:
args.touchTipAfterAspirateOffsetMmFromBottom,
}),
]
: []
const touchTipAfterDispenseCommands = args.touchTipAfterDispense
? [
curryCommandCreator(touchTip, {
pipette: args.pipette,
labware: args.destLabware,
well: destWell,
offsetFromBottomMm:
args.touchTipAfterDispenseOffsetMmFromBottom,
}),
]
: []
const mixInDestinationCommands =
args.mixInDestination != null
? mixUtil({
pipette: args.pipette,
labware: args.destLabware,
well: destWell,
volume: args.mixInDestination.volume,
times: args.mixInDestination.times,
aspirateOffsetFromBottomMm: dispenseOffsetFromBottomMm,
dispenseOffsetFromBottomMm,
aspirateFlowRateUlSec,
dispenseFlowRateUlSec,
aspirateDelaySeconds: aspirateDelay?.seconds,
dispenseDelaySeconds: dispenseDelay?.seconds,
})
: []
const delayAfterDispenseCommands =
dispenseDelay != null
? [
curryCommandCreator(moveToWell, {
pipette: args.pipette,
labware: args.destLabware,
well: destWell,
offset: {
x: 0,
y: 0,
z: dispenseDelay.mmFromBottom,
},
}),
curryCommandCreator(delay, {
commandCreatorFnName: 'delay',
description: null,
name: null,
meta: null,
wait: dispenseDelay.seconds,
}),
]
: []
const airGapAfterAspirateCommands = aspirateAirGapVolume
? [
curryCommandCreator(airGap, {
pipette: args.pipette,
volume: aspirateAirGapVolume,
labware: args.sourceLabware,
well: sourceWell,
flowRate: aspirateFlowRateUlSec,
offsetFromBottomMm: airGapOffsetSourceWell,
}),
...(aspirateDelay != null
? [
curryCommandCreator(delay, {
commandCreatorFnName: 'delay',
description: null,
name: null,
meta: null,
wait: aspirateDelay.seconds,
}),
]
: []),
curryCommandCreator(dispenseAirGap, {
pipette: args.pipette,
volume: aspirateAirGapVolume,
labware: args.destLabware,
well: destWell,
flowRate: dispenseFlowRateUlSec,
offsetFromBottomMm: airGapOffsetDestWell,
}),
...(dispenseDelay != null
? [
curryCommandCreator(delay, {
commandCreatorFnName: 'delay',
description: null,
name: null,
meta: null,
wait: dispenseDelay.seconds,
}),
]
: []),
]
: []
// `willReuseTip` is like changeTipNow, but thinking ahead about
// the NEXT subtransfer and not this current one
let willReuseTip = true // never or once --> true
if (isLastChunk && isLastPair) {
// if we're at the end of this step, we won't reuse the tip in this step
// so we can discard it (even if changeTip is never, we'll drop it!)
willReuseTip = false
} else if (args.changeTip === 'always') {
willReuseTip = false
} else if (args.changeTip === 'perSource' && !isLastPair) {
const nextSourceWell = sourceDestPairs[pairIdx + 1][0]
willReuseTip = nextSourceWell === sourceWell
} else if (args.changeTip === 'perDest' && !isLastPair) {
const nextDestWell = sourceDestPairs[pairIdx + 1][1]
willReuseTip = nextDestWell === destWell
}
// TODO(IL, 2020-10-12): extract this ^ into a util to reuse in distribute/consolidate??
const {
dispenseAirGapLabware,
dispenseAirGapWell,
} = getDispenseAirGapLocation({
blowoutLocation: args.blowoutLocation,
sourceLabware: args.sourceLabware,
destLabware: args.destLabware,
sourceWell,
destWell,
})
const airGapAfterDispenseCommands =
dispenseAirGapVolume && !willReuseTip
? [
curryCommandCreator(airGap, {
pipette: args.pipette,
volume: dispenseAirGapVolume,
labware: dispenseAirGapLabware,
well: dispenseAirGapWell,
flowRate: aspirateFlowRateUlSec,
offsetFromBottomMm: airGapOffsetDestWell,
}),
...(aspirateDelay != null
? [
curryCommandCreator(delay, {
commandCreatorFnName: 'delay',
description: null,
name: null,
meta: null,
wait: aspirateDelay.seconds,
}),
]
: []),
]
: []
// if using dispense > air gap, drop or change the tip at the end
const dropTipAfterDispenseAirGap =
airGapAfterDispenseCommands.length > 0 && isLastChunk && isLastPair
? [
curryCommandCreator(dropTip, {
pipette: args.pipette,
}),
]
: []
const blowoutCommand = blowoutUtil({
pipette: args.pipette,
sourceLabwareId: args.sourceLabware,
sourceWell: sourceWell,
destLabwareId: args.destLabware,
destWell: destWell,
blowoutLocation: args.blowoutLocation,
flowRate: blowoutFlowRateUlSec,
offsetFromTopMm: blowoutOffsetFromTopMm,
invariantContext,
})
const nextCommands = [
...tipCommands,
...preWetTipCommands,
...mixBeforeAspirateCommands,
curryCommandCreator(aspirate, {
pipette: args.pipette,
volume: subTransferVol,
labware: args.sourceLabware,
well: sourceWell,
flowRate: aspirateFlowRateUlSec,
offsetFromBottomMm: aspirateOffsetFromBottomMm,
}),
...delayAfterAspirateCommands,
...touchTipAfterAspirateCommands,
...airGapAfterAspirateCommands,
curryCommandCreator(dispense, {
pipette: args.pipette,
volume: subTransferVol,
labware: args.destLabware,
well: destWell,
flowRate: dispenseFlowRateUlSec,
offsetFromBottomMm: dispenseOffsetFromBottomMm,
}),
...delayAfterDispenseCommands,
...mixInDestinationCommands,
...touchTipAfterDispenseCommands,
...blowoutCommand,
...airGapAfterDispenseCommands,
...dropTipAfterDispenseAirGap,
]
// NOTE: side-effecting
prevSourceWell = sourceWell
prevDestWell = destWell
return [...innerAcc, ...nextCommands]
},
[]
)
return [...outerAcc, ...commands]
},
[]
)
return reduceCommandCreators(
commandCreators,
invariantContext,
prevRobotState
)
} | the_stack |
import { Matrix, Vector3 } from '.';
import { MathTmp } from './tmp';
export interface QuaternionLike {
x: number;
y: number;
z: number;
w: number;
}
/**
* Class used to store quaternion data
* @see https://en.wikipedia.org/wiki/Quaternion
*/
export class Quaternion implements QuaternionLike {
/**
* Creates a new Quaternion from the given floats
* @param x defines the first component (0 by default)
* @param y defines the second component (0 by default)
* @param z defines the third component (0 by default)
* @param w defines the fourth component (1.0 by default)
*/
constructor(
/** defines the first component (0 by default) */
public x = 0.0,
/** defines the second component (0 by default) */
public y = 0.0,
/** defines the third component (0 by default) */
public z = 0.0,
/** defines the fourth component (1.0 by default) */
public w = 1.0) {
}
/**
* Gets a string representation for the current quaternion
* @returns a string with the Quaternion coordinates
*/
public toString(): string {
return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
}
/**
* Returns a JSON representation of this quaternion. This is necessary due to the way
* Actors detect changes on components like the actor's transform. They do this by adding
* properties for observation, and we don't want these properties serialized.
*/
public toJSON() {
return {
x: this.x,
y: this.y,
z: this.z,
w: this.w,
} as QuaternionLike;
}
/**
* Gets the class name of the quaternion
* @returns the string "Quaternion"
*/
public getClassName(): string {
return "Quaternion";
}
/**
* Gets a hash code for this quaternion
* @returns the quaternion hash code
*/
public getHashCode(): number {
let hash = this.x || 0;
hash = (hash * 397) ^ (this.y || 0);
hash = (hash * 397) ^ (this.z || 0);
hash = (hash * 397) ^ (this.w || 0);
return hash;
}
/**
* Copy the quaternion to an array
* @returns a new array populated with 4 elements from the quaternion coordinates
*/
public asArray(): number[] {
return [this.x, this.y, this.z, this.w];
}
/**
* Check if two quaternions are equals
* @param otherQuaternion defines the second operand
* @return true if the current quaternion and the given one coordinates are strictly equals
*/
public equals(otherQuaternion: Quaternion): boolean {
return (
otherQuaternion &&
this.x === otherQuaternion.x &&
this.y === otherQuaternion.y &&
this.z === otherQuaternion.z &&
this.w === otherQuaternion.w);
}
/**
* Clone the current quaternion
* @returns a new quaternion copied from the current one
*/
public clone(): Quaternion {
return new Quaternion(this.x, this.y, this.z, this.w);
}
/**
* Copy a quaternion to the current one
* @param other defines the other quaternion
* @returns the updated current quaternion
*/
public copyFrom(other: Quaternion): Quaternion {
this.x = other.x;
this.y = other.y;
this.z = other.z;
this.w = other.w;
return this;
}
/**
* Updates the Quaternion from the value.
* @param from The value to read from.
*/
public copy(from: Partial<QuaternionLike>): this {
if (!from) return this;
if (from.x !== undefined) this.x = from.x;
if (from.y !== undefined) this.y = from.y;
if (from.z !== undefined) this.z = from.z;
if (from.w !== undefined) this.w = from.w;
return this;
}
/**
* Updates the current quaternion with the given float coordinates
* @param x defines the x coordinate
* @param y defines the y coordinate
* @param z defines the z coordinate
* @param w defines the w coordinate
* @returns the updated current quaternion
*/
public copyFromFloats(x: number, y: number, z: number, w: number): Quaternion {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
return this;
}
/**
* Updates the current quaternion from the given float coordinates
* @param x defines the x coordinate
* @param y defines the y coordinate
* @param z defines the z coordinate
* @param w defines the w coordinate
* @returns the updated current quaternion
*/
public set(x: number, y: number, z: number, w: number): Quaternion {
return this.copyFromFloats(x, y, z, w);
}
/**
* Adds two quaternions
* @param other defines the second operand
* @returns a new quaternion as the addition result of the given one and the current quaternion
*/
public add(other: Quaternion): Quaternion {
return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
}
/**
* Add a quaternion to the current one
* @param other defines the quaternion to add
* @returns the current quaternion
*/
public addInPlace(other: Quaternion): Quaternion {
this.x += other.x;
this.y += other.y;
this.z += other.z;
this.w += other.w;
return this;
}
/**
* Subtract two quaternions
* @param other defines the second operand
* @returns a new quaternion as the subtraction result of the given one from the current one
*/
public subtract(other: Quaternion): Quaternion {
return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
}
/**
* Multiplies the current quaternion by a scale factor
* @param value defines the scale factor
* @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
*/
public scale(value: number): Quaternion {
return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
}
/**
* Scale the current quaternion values by a factor and stores the result to a given quaternion
* @param scale defines the scale factor
* @param result defines the Quaternion object where to store the result
* @returns the unmodified current quaternion
*/
public scaleToRef(scale: number, result: Quaternion): Quaternion {
result.x = this.x * scale;
result.y = this.y * scale;
result.z = this.z * scale;
result.w = this.w * scale;
return this;
}
/**
* Multiplies in place the current quaternion by a scale factor
* @param value defines the scale factor
* @returns the current modified quaternion
*/
public scaleInPlace(value: number): Quaternion {
this.x *= value;
this.y *= value;
this.z *= value;
this.w *= value;
return this;
}
/**
* Scale the current quaternion values by a factor and add the result to a given quaternion
* @param scale defines the scale factor
* @param result defines the Quaternion object where to store the result
* @returns the unmodified current quaternion
*/
public scaleAndAddToRef(scale: number, result: Quaternion): Quaternion {
result.x += this.x * scale;
result.y += this.y * scale;
result.z += this.z * scale;
result.w += this.w * scale;
return this;
}
/**
* Multiplies two quaternions
* @param q1 defines the second operand
* @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
*/
public multiply(q1: Quaternion): Quaternion {
const result = new Quaternion(0, 0, 0, 1.0);
this.multiplyToRef(q1, result);
return result;
}
/**
* Sets the given "result" as the the multiplication result of the current one with the given one "q1"
* @param q1 defines the second operand
* @param result defines the target quaternion
* @returns the current quaternion
*/
public multiplyToRef(q1: Quaternion, result: Quaternion): Quaternion {
const x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
const y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
const z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
const w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
result.copyFromFloats(x, y, z, w);
return this;
}
/**
* Updates the current quaternion with the multiplication of itself with the given one "q1"
* @param q1 defines the second operand
* @returns the currentupdated quaternion
*/
public multiplyInPlace(q1: Quaternion): Quaternion {
this.multiplyToRef(q1, this);
return this;
}
/**
* Conjugates (1-q) the current quaternion and stores the result in the given quaternion
* @param ref defines the target quaternion
* @returns the current quaternion
*/
public conjugateToRef(ref: Quaternion): Quaternion {
ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
return this;
}
/**
* Conjugates in place (1-q) the current quaternion
* @returns the current updated quaternion
*/
public conjugateInPlace(): Quaternion {
this.x *= -1;
this.y *= -1;
this.z *= -1;
return this;
}
/**
* Conjugates in place (1-q) the current quaternion
* @returns a new quaternion
*/
public conjugate(): Quaternion {
const result = new Quaternion(-this.x, -this.y, -this.z, this.w);
return result;
}
/**
* Gets length of current quaternion
* @returns the quaternion length (float)
*/
public length(): number {
return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
}
/**
* Normalize in place the current quaternion
* @returns the current updated quaternion
*/
public normalize(): Quaternion {
const length = 1.0 / this.length();
this.x *= length;
this.y *= length;
this.z *= length;
this.w *= length;
return this;
}
/**
* Returns a new Vector3 set with the Euler angles translated from the current quaternion
* @param order is a reserved parameter and is ignore for now
* @returns a new Vector3 containing the Euler angles
*/
public toEulerAngles(order = "YZX"): Vector3 {
const result = Vector3.Zero();
this.toEulerAnglesToRef(result, order);
return result;
}
/**
* Sets the given vector3 "result" with the Euler angles translated from the current quaternion
* @param result defines the vector which will be filled with the Euler angles
* @param order is a reserved parameter and is ignore for now
* @returns the current unchanged quaternion
*/
public toEulerAnglesToRef(result: Vector3, order = "YZX"): Quaternion {
const qz = this.z;
const qx = this.x;
const qy = this.y;
const qw = this.w;
const sqw = qw * qw;
const sqz = qz * qz;
const sqx = qx * qx;
const sqy = qy * qy;
const zAxisY = qy * qz - qx * qw;
const limit = .4999999;
if (zAxisY < -limit) {
result.y = 2 * Math.atan2(qy, qw);
result.x = Math.PI / 2;
result.z = 0;
} else if (zAxisY > limit) {
result.y = 2 * Math.atan2(qy, qw);
result.x = -Math.PI / 2;
result.z = 0;
} else {
result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
}
return this;
}
/**
* Updates the given rotation matrix with the current quaternion values
* @param result defines the target matrix
* @returns the current unchanged quaternion
*/
public toRotationMatrix(result: Matrix): Quaternion {
Matrix.FromQuaternionToRef(this, result);
return this;
}
/**
* Updates the current quaternion from the given rotation matrix values
* @param matrix defines the source matrix
* @returns the current updated quaternion
*/
public fromRotationMatrix(matrix: Matrix): Quaternion {
Quaternion.FromRotationMatrixToRef(matrix, this);
return this;
}
// Statics
/**
* Creates a new quaternion from a rotation matrix
* @param matrix defines the source matrix
* @returns a new quaternion created from the given rotation matrix values
*/
public static FromRotationMatrix(matrix: Matrix): Quaternion {
const result = new Quaternion();
Quaternion.FromRotationMatrixToRef(matrix, result);
return result;
}
/**
* Updates the given quaternion with the given rotation matrix values
* @param matrix defines the source matrix
* @param result defines the target quaternion
*/
public static FromRotationMatrixToRef(matrix: Matrix, result: Quaternion): void {
const data = matrix.m;
const m11 = data[0], m12 = data[4], m13 = data[8];
const m21 = data[1], m22 = data[5], m23 = data[9];
const m31 = data[2], m32 = data[6], m33 = data[10];
const trace = m11 + m22 + m33;
let s;
if (trace > 0) {
s = 0.5 / Math.sqrt(trace + 1.0);
result.w = 0.25 / s;
result.x = (m32 - m23) * s;
result.y = (m13 - m31) * s;
result.z = (m21 - m12) * s;
} else if (m11 > m22 && m11 > m33) {
s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
result.w = (m32 - m23) / s;
result.x = 0.25 * s;
result.y = (m12 + m21) / s;
result.z = (m13 + m31) / s;
} else if (m22 > m33) {
s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
result.w = (m13 - m31) / s;
result.x = (m12 + m21) / s;
result.y = 0.25 * s;
result.z = (m23 + m32) / s;
} else {
s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
result.w = (m21 - m12) / s;
result.x = (m13 + m31) / s;
result.y = (m23 + m32) / s;
result.z = 0.25 * s;
}
}
/**
* Calculates a rotation to face the `to` point from the `from` point.
* @param from The location of the viewpoint.
* @param to The location to face toward.
* @param offset (Optional) Offset yaw, pitch, roll to add.
*/
public static LookAt(from: Vector3, to: Vector3, offset = Vector3.Zero()) {
const direction = to.subtract(from);
const yaw = -Math.atan2(direction.z, direction.x) + Math.PI / 2;
const len = Math.sqrt(direction.x * direction.x + direction.z * direction.z);
const pitch = -Math.atan2(direction.y, len);
return Quaternion.RotationYawPitchRoll(yaw + offset.x, pitch + offset.y, + offset.z);
}
/**
* Returns the dot product (float) between the quaternions "left" and "right"
* @param left defines the left operand
* @param right defines the right operand
* @returns the dot product
*/
public static Dot(left: Quaternion, right: Quaternion): number {
return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
}
/**
* Checks if the two quaternions are close to each other
* @param quat0 defines the first quaternion to check
* @param quat1 defines the second quaternion to check
* @returns true if the two quaternions are close to each other
*/
public static AreClose(quat0: Quaternion, quat1: Quaternion): boolean {
const dot = Quaternion.Dot(quat0, quat1);
return dot >= 0;
}
/**
* Creates an empty quaternion
* @returns a new quaternion set to (0.0, 0.0, 0.0)
*/
public static Zero(): Quaternion {
return new Quaternion(0.0, 0.0, 0.0, 0.0);
}
/**
* Inverse a given quaternion
* @param q defines the source quaternion
* @returns a new quaternion as the inverted current quaternion
*/
public static Inverse(q: Quaternion): Quaternion {
return new Quaternion(-q.x, -q.y, -q.z, q.w);
}
/**
* Inverse a given quaternion
* @param q defines the source quaternion
* @param result the quaternion the result will be stored in
* @returns the result quaternion
*/
public static InverseToRef(q: Quaternion, result: Quaternion): Quaternion {
result.set(-q.x, -q.y, -q.z, q.w);
return result;
}
/**
* Creates an identity quaternion
* @returns the identity quaternion
*/
public static Identity(): Quaternion {
return new Quaternion(0.0, 0.0, 0.0, 1.0);
}
/**
* Gets a boolean indicating if the given quaternion is identity
* @param quaternion defines the quaternion to check
* @returns true if the quaternion is identity
*/
public static IsIdentity(quaternion: Quaternion): boolean {
return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
}
/**
* Creates a quaternion from a rotation around an axis
* @param axis defines the axis to use
* @param angle defines the angle to use
* @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
*/
public static RotationAxis(axis: Vector3, angle: number): Quaternion {
return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
}
/**
* Creates a rotation around an axis and stores it into the given quaternion
* @param axis defines the axis to use
* @param angle defines the angle to use
* @param result defines the target quaternion
* @returns the target quaternion
*/
public static RotationAxisToRef(axis: Vector3, angle: number, result: Quaternion): Quaternion {
const sin = Math.sin(angle / 2);
axis.normalize();
result.w = Math.cos(angle / 2);
result.x = axis.x * sin;
result.y = axis.y * sin;
result.z = axis.z * sin;
return result;
}
/**
* Creates a new quaternion from data stored into an array
* @param array defines the data source
* @param offset defines the offset in the source array where the data starts
* @returns a new quaternion
*/
public static FromArray(array: ArrayLike<number>, offset?: number): Quaternion {
if (!offset) {
offset = 0;
}
return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
}
/**
* Create a quaternion from Euler rotation angles
* @param x Pitch
* @param y Yaw
* @param z Roll
* @returns the new Quaternion
*/
public static FromEulerAngles(x: number, y: number, z: number): Quaternion {
const q = new Quaternion();
Quaternion.RotationYawPitchRollToRef(y, x, z, q);
return q;
}
/**
* Updates a quaternion from Euler rotation angles
* @param x Pitch
* @param y Yaw
* @param z Roll
* @param result the quaternion to store the result
* @returns the updated quaternion
*/
public static FromEulerAnglesToRef(x: number, y: number, z: number, result: Quaternion): Quaternion {
Quaternion.RotationYawPitchRollToRef(y, x, z, result);
return result;
}
/**
* Create a quaternion from Euler rotation vector
* @param vec the Euler vector (x Pitch, y Yaw, z Roll)
* @returns the new Quaternion
*/
public static FromEulerVector(vec: Vector3): Quaternion {
const q = new Quaternion();
Quaternion.RotationYawPitchRollToRef(vec.y, vec.x, vec.z, q);
return q;
}
/**
* Updates a quaternion from Euler rotation vector
* @param vec the Euler vector (x Pitch, y Yaw, z Roll)
* @param result the quaternion to store the result
* @returns the updated quaternion
*/
public static FromEulerVectorToRef(vec: Vector3, result: Quaternion): Quaternion {
Quaternion.RotationYawPitchRollToRef(vec.y, vec.x, vec.z, result);
return result;
}
/**
* Creates a new quaternion from the given Euler float angles (y, x, z)
* @param yaw defines the rotation around Y axis
* @param pitch defines the rotation around X axis
* @param roll defines the rotation around Z axis
* @returns the new quaternion
*/
public static RotationYawPitchRoll(yaw: number, pitch: number, roll: number): Quaternion {
const q = new Quaternion();
Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
return q;
}
/**
* Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
* @param yaw defines the rotation around Y axis
* @param pitch defines the rotation around X axis
* @param roll defines the rotation around Z axis
* @param result defines the target quaternion
*/
public static RotationYawPitchRollToRef(yaw: number, pitch: number, roll: number, result: Quaternion): void {
// Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
const halfRoll = roll * 0.5;
const halfPitch = pitch * 0.5;
const halfYaw = yaw * 0.5;
const sinRoll = Math.sin(halfRoll);
const cosRoll = Math.cos(halfRoll);
const sinPitch = Math.sin(halfPitch);
const cosPitch = Math.cos(halfPitch);
const sinYaw = Math.sin(halfYaw);
const cosYaw = Math.cos(halfYaw);
result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
}
/**
* Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
* @param alpha defines the rotation around first axis
* @param beta defines the rotation around second axis
* @param gamma defines the rotation around third axis
* @returns the new quaternion
*/
public static RotationAlphaBetaGamma(alpha: number, beta: number, gamma: number): Quaternion {
const result = new Quaternion();
Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
return result;
}
/**
* Creates a new quaternion from the given Euler float angles expressed
* in z-x-z orientation and stores it in the target quaternion
* @param alpha defines the rotation around first axis
* @param beta defines the rotation around second axis
* @param gamma defines the rotation around third axis
* @param result defines the target quaternion
*/
public static RotationAlphaBetaGammaToRef(alpha: number, beta: number, gamma: number, result: Quaternion): void {
// Produces a quaternion from Euler angles in the z-x-z orientation
const halfGammaPlusAlpha = (gamma + alpha) * 0.5;
const halfGammaMinusAlpha = (gamma - alpha) * 0.5;
const halfBeta = beta * 0.5;
result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
}
/**
* Creates a new quaternion containing the rotation value to reach the target
* (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and
* axis3 are normalized during this operation)
* @param axis1 defines the first axis
* @param axis2 defines the second axis
* @param axis3 defines the third axis
* @returns the new quaternion
*/
public static RotationQuaternionFromAxis(axis1: Vector3, axis2: Vector3, axis3: Vector3): Quaternion {
const quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
return quat;
}
/**
* Creates a rotation value to reach the target (axis1, axis2, axis3) orientation
* as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this
* operation) and stores it in the target quaternion
* @param axis1 defines the first axis
* @param axis2 defines the second axis
* @param axis3 defines the third axis
* @param ref defines the target quaternion
*/
public static RotationQuaternionFromAxisToRef(
axis1: Vector3,
axis2: Vector3,
axis3: Vector3,
ref: Quaternion): void {
const rotMat = MathTmp.Matrix[0];
Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
Quaternion.FromRotationMatrixToRef(rotMat, ref);
}
/**
* Interpolates between two quaternions
* @param left defines first quaternion
* @param right defines second quaternion
* @param amount defines the gradient to use
* @returns the new interpolated quaternion
*/
public static Slerp(left: Quaternion, right: Quaternion, amount: number): Quaternion {
const result = Quaternion.Identity();
Quaternion.SlerpToRef(left, right, amount, result);
return result;
}
/**
* Interpolates between two quaternions and stores it into a target quaternion
* @param left defines first quaternion
* @param right defines second quaternion
* @param amount defines the gradient to use
* @param result defines the target quaternion
*/
public static SlerpToRef(left: Quaternion, right: Quaternion, amount: number, result: Quaternion): void {
let num2;
let num3;
let num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
let flag = false;
if (num4 < 0) {
flag = true;
num4 = -num4;
}
if (num4 > 0.999999) {
num3 = 1 - amount;
num2 = flag ? -amount : amount;
} else {
const num5 = Math.acos(num4);
const num6 = (1.0 / Math.sin(num5));
num3 = (Math.sin((1.0 - amount) * num5)) * num6;
num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
}
result.x = (num3 * left.x) + (num2 * right.x);
result.y = (num3 * left.y) + (num2 * right.y);
result.z = (num3 * left.z) + (num2 * right.z);
result.w = (num3 * left.w) + (num2 * right.w);
}
/**
* Interpolate between two quaternions using Hermite interpolation
* @param value1 defines first quaternion
* @param tangent1 defines the incoming tangent
* @param value2 defines second quaternion
* @param tangent2 defines the outgoing tangent
* @param amount defines the target quaternion
* @returns the new interpolated quaternion
*/
public static Hermite(
value1: Quaternion,
tangent1: Quaternion,
value2: Quaternion,
tangent2: Quaternion,
amount: number): Quaternion {
const squared = amount * amount;
const cubed = amount * squared;
const part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
const part2 = (-2.0 * cubed) + (3.0 * squared);
const part3 = (cubed - (2.0 * squared)) + amount;
const part4 = cubed - squared;
const x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
const y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
const z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
const w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
return new Quaternion(x, y, z, w);
}
} | the_stack |
import { URLSearchParams } from 'url';
import { authentication, usGovernmentAuthentication } from '../constants/authEndpoints';
import { BotEndpoint } from './botEndpoint';
describe('BotEndpoint', () => {
it('should determine whether a token will expire within a time period', () => {
const endpoint = new BotEndpoint();
const currentTime = Date.now();
endpoint.speechAuthenticationToken = {
expireAt: currentTime + 100, // 100 ms in the future
} as any;
expect((endpoint as any).willTokenExpireWithin(5000)).toBe(true);
});
it('should return the speech token if it already exists', async () => {
const endpoint = new BotEndpoint('', '', '', 'msaAppId', 'msaAppPw');
endpoint.speechAuthenticationToken = {
accessToken: 'someToken',
region: 'westus2',
expireAt: Date.now() + 10 * 1000 * 60, // expires in 10 minutes
tokenLife: 10 * 1000 * 60, // token life of 10 minutes
};
const refresh = false;
const token = await endpoint.getSpeechToken(refresh);
expect(token).toBe('someToken');
});
it('should return a new speech token if the current token is expired', async () => {
const endpoint = new BotEndpoint('', '', '', 'msaAppId', 'msaAppPw');
endpoint.speechAuthenticationToken = {
expireAt: Date.now() - 5000,
} as any;
jest.spyOn(endpoint as any, 'fetchSpeechToken').mockResolvedValueOnce('new speech token');
const token = await endpoint.getSpeechToken();
expect(token).toBe('new speech token');
});
it('should return a new speech token if the current token is past its half life', async () => {
const endpoint = new BotEndpoint('', '', '', 'msaAppId', 'msaAppPw');
endpoint.speechAuthenticationToken = {
expireAt: Date.now() + 4 * 1000 * 60, // expires in 4 minutes
tokenLife: 10 * 1000 * 60, // token life of 10 minutes
} as any;
jest.spyOn(endpoint as any, 'fetchSpeechToken').mockResolvedValueOnce('new speech token');
const token = await endpoint.getSpeechToken();
expect(token).toBe('new speech token');
});
it('should return a new speech token if there is no existing token or if the refresh flag is true', async () => {
const endpoint = new BotEndpoint('', '', '', 'msaAppId', 'msaAppPw');
jest.spyOn(endpoint as any, 'fetchSpeechToken').mockResolvedValueOnce('new speech token');
const token = await endpoint.getSpeechToken(true);
expect(token).toBe('new speech token');
});
it('should throw if there is no msa app id or password', async () => {
const endpoint = new BotEndpoint();
try {
await endpoint.getSpeechToken();
} catch (e) {
expect(e).toEqual(new Error('Bot must have a valid Microsoft App ID and password'));
}
});
it('should fetch a speech token', async () => {
const endpoint = new BotEndpoint();
jest.spyOn(endpoint as any, 'fetchWithAuth').mockResolvedValueOnce({
json: () =>
Promise.resolve({
access_Token: 'someSpeechToken',
region: 'westus2',
expireAt: 1234,
tokenLife: 9999,
}),
status: 200,
});
const token = await (endpoint as any).fetchSpeechToken();
expect(token).toBe('someSpeechToken');
});
it('should throw when failing to read the token response', async () => {
const endpoint = new BotEndpoint();
jest.spyOn(endpoint as any, 'fetchWithAuth').mockResolvedValueOnce({
json: async () => Promise.reject(new Error('Malformed response JSON.')),
status: 200,
});
try {
await (endpoint as any).fetchSpeechToken();
expect(false).toBe(true); // make sure catch is hit
} catch (e) {
expect(e).toEqual(new Error(`Couldn't read speech token response: ${new Error('Malformed response JSON.')}`));
}
});
it(`should throw when the token response doesn't contain a token and has an error attached`, async () => {
const endpoint = new BotEndpoint();
jest.spyOn(endpoint as any, 'fetchWithAuth').mockResolvedValueOnce({
json: () => Promise.resolve({ error: 'Token was lost in transit.' }),
status: 200,
});
try {
await (endpoint as any).fetchSpeechToken();
expect(false).toBe(true); // make sure catch is hit
} catch (e) {
expect(e).toEqual(new Error('Token was lost in transit.'));
}
});
it(`should throw when the token response doesn't contain a token nor an error`, async () => {
const endpoint = new BotEndpoint();
jest.spyOn(endpoint as any, 'fetchWithAuth').mockResolvedValueOnce({
json: () => Promise.resolve({}),
status: 200,
});
try {
await (endpoint as any).fetchSpeechToken();
expect(false).toBe(true); // make sure catch is hit
} catch (e) {
expect(e).toEqual(new Error('Could not retrieve speech token'));
}
});
it(`should throw when the token endpoint returns a 401`, async () => {
const endpoint = new BotEndpoint();
jest.spyOn(endpoint as any, 'fetchWithAuth').mockResolvedValueOnce({
status: 401,
});
try {
await (endpoint as any).fetchSpeechToken();
expect(false).toBe(true); // make sure catch is hit
} catch (e) {
expect(e).toEqual(new Error('Not authorized to use Cognitive Services Speech API'));
}
});
it(`should throw when the token endpoint returns an error response that is not a 401`, async () => {
const endpoint = new BotEndpoint();
jest.spyOn(endpoint as any, 'fetchWithAuth').mockResolvedValueOnce({
status: 500,
});
try {
await (endpoint as any).fetchSpeechToken();
expect(false).toBe(true); // make sure catch is hit
} catch (e) {
expect(e).toEqual(new Error(`Can't retrieve speech token`));
}
});
it('should fetch with auth', async () => {
const endpoint = new BotEndpoint();
endpoint.msaAppId = 'someAppId';
const mockGetAccessToken = jest.fn(() => Promise.resolve('someAccessToken'));
(endpoint as any).getAccessToken = mockGetAccessToken;
const mockResponse = 'I am a response!';
const mockFetch = jest.fn(() => Promise.resolve(mockResponse));
(endpoint as any)._options = { fetch: mockFetch };
const response = await endpoint.fetchWithAuth('someUrl');
expect(response).toBe('I am a response!');
expect(mockGetAccessToken).toHaveBeenCalledWith(false);
expect(mockFetch).toHaveBeenCalledWith('someUrl', { headers: { Authorization: 'Bearer someAccessToken' } });
});
it('should retry fetching with a refreshed auth token if the fetch returns a 401', async () => {
const endpoint = new BotEndpoint();
endpoint.msaAppId = 'someAppId';
const mockGetAccessToken = jest.fn(() => Promise.resolve('someAccessToken'));
(endpoint as any).getAccessToken = mockGetAccessToken;
const mockResponse = 'I am a response!';
const mockFetch = jest
.fn()
.mockImplementationOnce(() => Promise.resolve({ status: 401 }))
.mockImplementationOnce(() => Promise.resolve(mockResponse));
(endpoint as any)._options = { fetch: mockFetch };
const response = await endpoint.fetchWithAuth('someUrl');
expect(response).toBe('I am a response!');
expect(mockGetAccessToken).toHaveBeenCalledTimes(2);
expect(mockGetAccessToken).toHaveBeenCalledWith(true); // forceRefresh will be true on second attempt
});
it('should retry fetching with a refreshed auth token if the fetch returns a 403', async () => {
const endpoint = new BotEndpoint();
endpoint.msaAppId = 'someAppId';
const mockGetAccessToken = jest.fn(() => Promise.resolve('someAccessToken'));
(endpoint as any).getAccessToken = mockGetAccessToken;
const mockResponse = 'I am a response!';
const mockFetch = jest
.fn()
.mockImplementationOnce(() => Promise.resolve({ status: 403 }))
.mockImplementationOnce(() => Promise.resolve(mockResponse));
(endpoint as any)._options = { fetch: mockFetch };
const response = await endpoint.fetchWithAuth('someUrl');
expect(response).toBe('I am a response!');
expect(mockGetAccessToken).toHaveBeenCalledTimes(2);
expect(mockGetAccessToken).toHaveBeenCalledWith(true); // forceRefresh will be true on second attempt
});
it('should return the access token if it already exists and has not expired yet', async () => {
const endpoint = new BotEndpoint();
const msaAppId = 'someAppId';
const msaPw = 'someAppPw';
endpoint.msaAppId = msaAppId;
endpoint.msaPassword = msaPw;
endpoint.use10Tokens = false;
endpoint.channelService = undefined;
// ensure that the token won't be expired
const tokenRefreshTime = 5 * 60 * 1000;
const accessTokenExpires = Date.now() * 2 + tokenRefreshTime;
endpoint.accessTokenExpires = accessTokenExpires;
// using non-v1.0 token & standard endpoint
const mockOauthResponse = { access_token: 'I am an access token!', expires_in: 10 };
const mockResponse = { json: jest.fn(() => Promise.resolve(mockOauthResponse)), status: 200 };
const mockFetch = jest.fn(() => Promise.resolve(mockResponse));
(endpoint as any)._options = { fetch: mockFetch };
let response = await (endpoint as any).getAccessToken();
expect(response).toBe('I am an access token!');
expect(endpoint.accessToken).toBe('I am an access token!');
expect(endpoint.accessTokenExpires).not.toEqual(accessTokenExpires);
expect(endpoint.accessTokenExpires).toEqual(jasmine.any(Number));
expect(mockFetch).toHaveBeenCalledWith(authentication.tokenEndpoint, {
method: 'POST',
body: new URLSearchParams({
grant_type: 'client_credentials',
client_id: msaAppId,
client_secret: msaPw,
scope: `${msaAppId}/.default`,
} as { [key: string]: string }).toString(),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
// using v1.0 token & government endpoint
endpoint.use10Tokens = true;
endpoint.channelService = usGovernmentAuthentication.channelService;
response = await (endpoint as any).getAccessToken();
expect(response).toBe('I am an access token!');
expect(endpoint.accessToken).toBe('I am an access token!');
expect(endpoint.accessTokenExpires).not.toEqual(accessTokenExpires);
expect(endpoint.accessTokenExpires).toEqual(jasmine.any(Number));
expect(mockFetch).toHaveBeenCalledWith(usGovernmentAuthentication.tokenEndpoint, {
method: 'POST',
body: new URLSearchParams({
grant_type: 'client_credentials',
client_id: msaAppId,
client_secret: msaPw,
scope: `${msaAppId}/.default`,
atver: '1',
} as { [key: string]: string }).toString(),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
});
it('should throw when requesting an access returns a bad response', async () => {
const endpoint = new BotEndpoint();
const msaAppId = 'someAppId';
const msaPw = 'someAppPw';
endpoint.msaAppId = msaAppId;
endpoint.msaPassword = msaPw;
endpoint.use10Tokens = false;
endpoint.channelService = undefined;
// ensure that the token won't be expired
const tokenRefreshTime = 5 * 60 * 1000;
const accessTokenExpires = Date.now() * 2 + tokenRefreshTime;
endpoint.accessTokenExpires = accessTokenExpires;
const mockResponse = { status: 404 };
const mockFetch = jest.fn(() => Promise.resolve(mockResponse));
(endpoint as any)._options = { fetch: mockFetch };
try {
await (endpoint as any).getAccessToken();
expect(false).toBe(true); // make sure catch is hit
} catch (e) {
expect(e).toEqual({ body: undefined, message: 'Refresh access token failed with status code: 404', status: 404 });
}
});
}); | the_stack |
interface IBroadcastCacheUpdateOptions {
/**
* A list of headers that will be used to determine whether the responses differ.
*/
headersToCheck: string[];
/**
* An attribution value that indicates where the update originated.
*/
source: string;
}
/**
* Uses the Broadcast Channel API to notify interested parties when a cached response has been updated.
* For efficiency's sake, the underlying response bodies are not compared; only specific response headers are checked
*/
declare class BroadcastCacheUpdate {
/**
* Compare two Responses and send a message via the Broadcast Channel API if they differ.
* Neither of the Responses can be opaque.
* @param {Response} firstResponse - First response to compare.
* @param {Response} secondResponse - Second response to compare.
* @param {string} url - The URL of the updated request.
* @param {string} cacheName - Name of the cache the responses belong to. This is included in the message posted on the broadcast channel.
*/
notifyIfUpdated (firstResponse: Response, secondResponse: Response, url: string, cacheName: string): void;
}
/**
* Construct a BroadcastCacheUpdate instance with a specific channelName to broadcast messages on
*/
interface IBroadcastCacheUpdateConstructor {
new (channelName: string, options: Partial<IBroadcastCacheUpdateOptions>): BroadcastCacheUpdate;
}
/**
* ===== CacheableResponse =====
*/
interface ICacheableResponseOptions {
statuses: number[];
headers: { [key: string]: string };
}
/**
* This class allows you to set up rules determining what status codes and/or headers need to be present in order for a Response to be considered cacheable.
*/
declare class CacheableResponse {
/**
* Checks a response to see whether it's cacheable or not, based on this object's configuration.
* @param {Response} response - The response whose cacheability is being checked.
* @returns {boolean}
*/
isResponseCacheable (response: Response): boolean;
}
/**
* To construct a new CacheableResponse instance you must provide at least one of the config properties.
* If both statuses and headers are specified, then both conditions must be met for the Response to be considered cacheable.
*/
interface ICacheableResponseConstructor {
new (options: Partial<ICacheableResponseOptions>): CacheableResponse;
}
/**
* ===== CacheExpiration =====
*/
interface ICacheExpirationOptions {
/**
* The maximum number of entries to store in a cache.
*/
maxEntries: number;
/**
* The maximum lifetime of a request to stay in the cache before it's removed.
*/
maxAgeSeconds: number;
}
/**
* The CacheExpiration class allows you define an expiration and / or limit on the number of responses stored in a Cache.
*/
declare class CacheExpiration {
/**
* Expires entries for the given cache and given criteria.
* @returns {Promise<void>}
*/
expireEntries (): Promise<void>;
/**
* Can be used to check if a URL has expired or not before it's used.
* This requires a look up from IndexedDB, so can be slow.
* Note: This method will not remove the cached entry, call expireEntries() to remove indexedDB and Cache entries.
* @param {string} url
* @returns {Promise<boolean>}
*/
isURLExpired (url: string): Promise<boolean>;
/**
* Update the timestamp for the given URL.
* This ensures the when removing entries based on maximum entries, most recently used is accurate or when expiring, the timestamp is up-to-date.
* @param {string} url
* @returns {Promise<void>}
*/
updateTimestamp (url: string): Promise<void>;
}
/**
* To construct a new CacheExpiration instance you must provide at least one of the config properties.
*/
interface ICacheExpirationConstructor {
new (cacheName: string, config: Partial<ICacheExpirationOptions>): CacheExpiration;
}
/**
* ===== Strategies =====
*/
interface ICacheStrategyHandleOptions {
event: FetchEvent;
}
interface ICacheStrategyMakeRequestOptions {
request: Request|string;
event?: FetchEvent | undefined;
}
declare class CacheStrategy {
/**
* This method will perform a request strategy and follows an API that will work with the Workbox Router.
* @param {ICacheStrategyHandleOptions} input
* @returns {Promise<Response>}
*/
handle (input: ICacheStrategyHandleOptions): Promise<Response>;
/**
* This method can be used to perform a make a standalone request outside the context of the Workbox Router.
* @param {ICacheStrategyMakeRequestOptions} input
* @returns {Promise<Response>}
*/
makeRequest (input: ICacheStrategyMakeRequestOptions): Promise<Response>;
}
/**
* ===== CacheOnly strategy =====
*/
interface ICacheOnlyOptions {
/**
* Cache name to store and retrieve requests. Defaults to cache names provided by workbox-core.
*/
cacheName: string;
/**
* Plugins to use in conjunction with this caching strategy.
*/
plugins: Plugin[];
}
/**
* An implementation of a cache-only request strategy.
* This class is useful if you want to take advantage of any Workbox plugins.
*/
declare class CacheOnly extends CacheStrategy {
}
/**
* Instantiates a new CacheOnly strategy
*/
interface ICacheOnlyConstructor {
new (options?: Partial<ICacheOnlyOptions>): CacheOnly;
}
/**
* ===== CacheFirst strategy =====
*/
interface ICacheFirstOptions extends ICacheOnlyOptions {
/**
* Values passed along to the init of all fetch() requests made by this strategy.
*/
fetchOptions: RequestInit;
}
/**
* An implementation of a cache-first request strategy.
* A cache first strategy is useful for assets that have been revisioned, such as URLs like /styles/example.a8f5f1.css, since they can be cached for long periods of time.
*/
declare class CacheFirst extends CacheStrategy {
}
/**
* Instantiates a new CacheFirst strategy
*/
interface ICacheFirstConstructor {
new (options?: Partial<ICacheFirstOptions>): CacheFirst;
}
/**
* ===== NetworkOnly strategy =====
*/
interface INetworkOnlyOptions extends ICacheFirstOptions {
}
/**
* An implementation of a network-only request strategy.
* This class is useful if you want to take advantage of any Workbox plugins.
*/
declare class NetworkOnly extends CacheStrategy {
}
/**
* Instantiates a new NetworkOnly strategy
*/
interface INetworkOnlyConstructor {
new (options?: Partial<INetworkOnlyOptions>): NetworkOnly;
}
/**
* ===== NetworkFirst strategy =====
*/
interface INetworkFirstOptions extends ICacheFirstOptions {
networkTimeoutSeconds: number;
}
/**
* An implementation of a network first request strategy.
* By default, this strategy will cache responses with a 200 status code as well as opaque responses.
* Opaque responses are are cross-origin requests where the response doesn't support CORS.
*/
declare class NetworkFirst extends CacheStrategy {
}
/**
* Instantiates a new NetworkFirst strategy
*/
interface INetworkFirstConstructor {
new (options?: Partial<INetworkFirstOptions>): NetworkFirst;
}
/**
* ===== StaleWhileRevalidate strategy =====
*/
interface IStaleWhileRevalidateOptions extends ICacheFirstOptions {
}
/**
* An implementation of a stale-while-revalidate request strategy.
* Resources are requested from both the cache and the network in parallel.
* The strategy will respond with the cached version if available, otherwise wait for the network response.
* The cache is updated with the network response with each successful request.
* By default, this strategy will cache responses with a 200 status code as well as opaque responses.
* Opaque responses are are cross-origin requests where the response doesn't support CORS.
*/
declare class StaleWhileRevalidate extends CacheStrategy {
}
/**
* Instantiates a new StaleWhileRevalidate strategy
*/
interface IStaleWhileRevalidateConstructor {
new (options?: Partial<IStaleWhileRevalidateOptions>): StaleWhileRevalidate;
}
/**
* ===== MatchCallback =====
*/
interface IMatchContext extends IURLContext {
/**
* The service workers' fetch event.
*/
event: FetchEvent;
}
/**
* To signify a match, return anything other than null. Return null if the route shouldn't match.
*/
type MatchCallback = (context: IMatchContext) => {}|null;
/**
* ===== HandlerCallback =====
*/
interface IHandlerContext extends IMatchContext {
/**
* Parameters returned by the Route's match callback function. This will be undefined if nothing was returned.
*/
params?: {} | undefined;
}
/**
* The "handler" callback is called when a service worker's fetch event has been matched by a Route. This callback should return a Promise that resolves with a Response.
* If a value is returned by the match callback it will be passed in as the context.params argument.
*/
type HandlerCallback = (context: IHandlerContext) => Promise<Response>;
/**
* ===== NavigationRoute =====
*/
interface IHandlerOptions {
url: string;
event: FetchEvent;
params: URLSearchParams;
}
interface INavigationRouteOptions {
/**
* If any of these patterns match, the route will not handle the request (even if a whitelist RegExp matches).
*/
blacklist: RegExp[];
/**
* If any of these patterns match the URL's pathname and search parameter,
* the route will handle the request (assuming the blacklist doesn't match).
*/
whitelist: RegExp[];
}
/**
* NavigationRoute makes it easy to create a Route that matches for browser navigation requests.
* It will only match incoming Requests whose mode is set to navigate.
* You can optionally only apply this route to a subset of navigation requests by using one or both of the blacklist and whitelist parameters.
*/
declare class NavigationRoute {
}
/**
* If both blacklist and whitelist are provided, the blacklist will take precedence and the request will not match this route.
* The regular expressions in whitelist and blacklist are matched against the concatenated pathname and search portions of the requested URL.
*/
interface INavigationRouteConstructor {
new (handler: HandlerCallback, options: Partial<INavigationRouteOptions>): NavigationRoute;
}
/**
* ===== BroadcastUpdatePlugin =====
*/
/**
* This plugin will automatically broadcast a message whenever a cached response is updated.
*/
declare class BroadcastUpdatePlugin {
}
/**
* Construct a new instance with a specific channelName to broadcast messages on
*/
interface IBroadcastUpdatePluginConstructor {
new (channelName: string, options?: Partial<IBroadcastCacheUpdateOptions>): BroadcastUpdatePlugin;
}
/**
* ===== BroadcastUpdatePlugin =====
*/
/**
* The range request plugin makes it easy for a request with a 'Range' header to be fulfilled by a cached response.
* It does this by intercepting the cachedResponseWillBeUsed plugin callback and returning the appropriate subset of the cached response body.
*/
declare class RangeRequestsPlugin {
}
/**
* Instantiates a new RangeRequestsPlugin
*/
interface IRangeRequestsPluginConstructor {
new (): RangeRequestsPlugin;
}
/**
* ===== CacheableResponsePlugin =====
*/
/**
* A class implementing the cacheWillUpdate lifecycle callback.
* This makes it easier to add in cacheability checks to requests made via Workbox's built-in strategies.
*/
declare class CacheableResponsePlugin {
}
/**
* To construct a new cacheable response Plugin instance you must provide at least one of the config properties.
* If both statuses and headers are specified, then both conditions must be met for the Response to be considered cacheable.
*/
interface ICacheableResponsePluginConstructor {
new (config: Partial<ICacheableResponseOptions>): CacheableResponsePlugin;
}
/**
* ===== BackgroundSyncPlugin =====
*/
/**
* A class implementing the fetchDidFail lifecycle callback.
* This makes it easier to add failed requests to a background sync Queue.
*/
declare class BackgroundSyncPlugin {
}
/**
* Instantiates a new BackgroundSyncPlugin
*/
interface IBackgroundSyncPluginConstructor {
new (...queueArgs: any[]): BackgroundSyncPlugin;
}
/**
* ===== ExpirationPlugin =====
*/
/**
* This plugin can be used in the Workbox API's to regularly enforce a limit on the age and / or the number of cached requests.
* Whenever a cached request is used or updated, this plugin will look at the used Cache and remove any old or extra requests.
* When using maxAgeSeconds, requests may be used once after expiring because the expiration clean up will not have occurred
* until after the cached request has been used. If the request has a "Date" header, then a light weight expiration check is
* performed and the request will not be used immediately.
* When using maxEntries, the last request to be used will be the request that is removed from the Cache.
*/
declare class ExpirationPlugin {
}
/**
* Instantiates a new ExpirationPlugin
*/
interface IExpirationPluginConstructor {
new (config: Partial<ICacheExpirationOptions>): ExpirationPlugin;
}
/**
* ===== ExpirationPlugin =====
*/
type Plugin = BroadcastUpdatePlugin|RangeRequestsPlugin|CacheableResponsePlugin|BackgroundSyncPlugin|ExpirationPlugin|WorkboxPlugin;
/**
* ===== BackgroundSync =====
*/
interface IStorableRequestOptions {
url: string;
/**
* See: https://fetch.spec.whatwg.org/#requestinit
*/
requestInit: RequestInit;
/**
* The time the request was created, defaulting to the current time if not specified.
*/
timestamp: number;
}
/**
* A class to make it easier to serialize and de-serialize requests so they can be stored in IndexedDB.
*/
declare class StorableRequest {
readonly timestamp: number;
toObject (): IStorableRequestOptions;
toRequest (): Request;
clone (): StorableRequest;
}
/**
* Accepts a URL and RequestInit dictionary that can be used to create a
* new Request object. A timestamp is also generated so consumers can
* reference when the object was created.
*/
interface IStorableRequestConstructor {
new (options: IStorableRequestOptions): StorableRequest;
fromRequest (request: Request): StorableRequest;
}
/**
* ===== PrecacheController =====
*/
interface ICleanupResult {
/**
* List of URLs that were deleted from the precache cache.
*/
deletedCacheRequests: string[];
/**
* List of URLs that were deleted from the precache cache.
*/
deletedRevisionDetails: string[];
}
interface IActivateOptions {
/**
* Plugins to be used for fetching and caching during install.
*/
plugins: Plugin[];
}
interface IInstallOptions {
/**
* Suppress warning messages.
*/
suppressWarnings: boolean;
/**
* Plugins to be used for fetching and caching during install.
*/
plugins: Plugin[];
}
interface IPrecacheEntry {
url: string;
revision: string;
}
interface IInstallResult {
/**
* List of entries supplied for precaching that were precached.
*/
updatedEntries: (string|IPrecacheEntry)[];
/**
* List of entries supplied for precaching that were already precached.
*/
notUpdatedEntries: (string|IPrecacheEntry)[];
}
/**
* Performs efficient precaching of assets.
*/
declare class PrecacheController {
/**
* Takes the current set of temporary files and moves them to the final cache, deleting the temporary cache once copying is complete.
* @param {IActivateOptions} options
* @returns {Promise<ICleanupResult>} Resolves with an object containing details of the deleted cache requests and precache revision details.
*/
activate (options: Partial<IActivateOptions>): Promise<ICleanupResult>;
/**
* This method will add items to the precache list, removing duplicates and ensuring the information is valid.
* @param {(string | IPrecacheEntry)[]} entries - Array of entries to precache.
*/
addToCacheList (entries: (string|IPrecacheEntry)[]): void;
/**
* Returns an array of fully qualified URL's that will be precached.
* @returns {string[]} An array of URLs.
*/
getCachedUrls (): string[];
/**
* Call this method from a service work install event to start precaching assets.
* @param {Partial<IInstallOptions>} options
* @returns {Promise<IInstallResult>}
*/
install (options?: Partial<IInstallOptions>): Promise<IInstallResult>;
}
/**
* Create a new PrecacheController.
*/
interface IPrecacheControllerConstructor {
new (cacheName?: string): PrecacheController;
}
/**
* ===== Queue =====
*/
interface IQueueCallback {
/**
* Invoked immediately before the request is stored to IndexedDB. Use this callback to modify request data at store time.
* @param {StorableRequest} request
*/
requestWillEnqueue (request: StorableRequest): void;
/**
* Invoked immediately before the request is re-fetched. Use this callback to modify request data at fetch time.
* @param {StorableRequest} request
*/
requestWillReplay (request: StorableRequest): void;
/**
* Invoked after all requests in the queue have successfully replayed.
* @param {StorableRequest[]} requests
*/
queueDidReplay (requests: StorableRequest[]): void;
}
interface IQueueOptions {
/**
* The amount of time (in minutes) a request may be retried. After this amount of time has passed, the request will be deleted from the queue.
*/
maxRetentionTime: number;
/**
* Callbacks to observe the lifecycle of queued requests. Use these to respond to or modify the requests during the replay process.
*/
callbacks: Partial<IQueueCallback>;
}
/**
* A class to manage storing failed requests in IndexedDB and retrying them later.
* All parts of the storing and replaying process are observable via callbacks.
*/
declare class Queue {
readonly name: string;
/**
* Stores the passed request into IndexedDB. The database used is workbox-background-sync and
* the object store name is the same as the name this instance was created with (to guarantee it's unique).
* @param {Request} request - The request object to store.
* @returns {Promise<void>}
*/
addRequest (request: Request): Promise<void>;
/**
* Retrieves all stored requests in IndexedDB and retries them. If the queue contained requests that
* were successfully replayed, the queueDidReplay callback is invoked (which implies the queue is now empty).
* If any of the requests fail, a new sync registration is created to retry again later.
* @returns {Promise<void>}
*/
replayRequests (): Promise<void>;
}
/**
* Creates an instance of Queue with the given options
*/
interface IQueueConstructor {
/**
* @param {string} name - The unique name for this queue. This name must be unique as it's used to register
* sync events and store requests in IndexedDB specific to this instance. An error will be thrown if a
* duplicate name is detected.
* @param {Partial<IQueueOptions>} options
* @returns {Queue}
*/
new (name: string, options?: Partial<IQueueOptions>): Queue;
}
/**
* ===== Route =====
*/
/**
* A Route consists of a pair of callback functions, "match" and "handler".
* The "match" callback determine if a route should be used to "handle" a request by
* returning a non-falsy value if it can. The "handler" callback is called when there is a match
* and should return a Promise that resolves to a Response.
*/
declare class Route {
}
/**
* Constructor for Route class.
*/
interface IRouteConstructor {
/**
*
* @param {MatchCallback} match - A callback function that determines whether the route matches a given fetch event by returning a non-falsy value.
* @param {HandlerCallback} handler - A callback function that returns a Promise resolving to a Response.
* @param {string} [method] - The HTTP method to match the Route against.
* @returns {Route}
*/
new (match: MatchCallback, handler: HandlerCallback, method?: string): Route;
}
/**
* ===== RegExpRoute =====
*/
/**
* RegExpRoute makes it easy to create a regular expression based Route.
* For same-origin requests the RegExp only needs to match part of the URL. For requests against third-party servers, you must define a RegExp that matches the start of the URL.
*/
declare class RegExpRoute extends Route {
}
/**
* If the regular expression contains capture groups, the captured values will be passed to the handler's params argument.
*/
interface IRegExpRouteConstructor {
/**
*
* @param {RegExp} regExp - The regular expression to match against URLs.
* @param {HandlerCallback} handler - A callback function that returns a Promise resulting in a Response.
* @param {string} [method] - The HTTP method to match the Route against.
* @returns {RegExpRoute}
*/
new (regExp: RegExp, handler: HandlerCallback, method?: string): RegExpRoute;
}
/**
* ===== Router =====
*/
/**
* The Router can be used to process a FetchEvent through one or more Routes responding with a Request if a matching route exists.
* If no route matches a given a request, the Router will use a "default" handler if one is defined.
* Should the matching Route throw an error, the Router will use a "catch" handler if one is defined to gracefully deal with issues and respond with a Request.
* If a request matches multiple routes, the earliest registered route will be used to respond to the request.
*/
declare class Router {
/**
* Apply the routing rules to a FetchEvent object to get a Response from an appropriate Route's handler.
* @param {FetchEvent} event - The event from a service worker's 'fetch' event listener.
* @returns {Promise<Response>?} A promise is returned if a registered route can handle the FetchEvent's request.
* If there is no matching route and there's no defaultHandler, undefined is returned.
*/
handleRequest (event: FetchEvent): Promise<Response>|undefined;
/**
* Registers a route with the router.
* @param {Route} route
*/
registerRoute (route: Route): void;
/**
* If a Route throws an error while handling a request, this handler will be called and given a chance to provide a response.
* @param {HandlerCallback} handler - A callback function that returns a Promise resulting in a Response.
*/
setCatchHandler (handler: HandlerCallback): void;
/**
* Define a default handler that's called when no routes explicitly match the incoming request.
* Without a default handler, unmatched requests will go against the network as if there were no service worker present.
* @param {HandlerCallback} handler - A callback function that returns a Promise resulting in a Response.
*/
setDefaultHandler (handler: HandlerCallback): void;
/**
* Unregisters a route with the router.
* @param {Route} route - The route to unregister.
*/
unregisterRoute (route: Route): void;
}
/**
* Initializes a new Router.
*/
interface IRouterConstructor {
new (): Router;
}
/**
* ===== CoreNamespace =====
*/
interface ICacheNames {
precache: string;
runtime: string;
googleAnalytics: string;
}
interface ILogLevel {
/**
* Prints all logs from Workbox. Useful for debugging.
*/
debug: 0;
/**
* Prints console log, warn, error and groups. Default for debug builds.
*/
log: 1;
/**
* Prints console warn, error and groups. Default for non-debug builds.
*/
warn: 2;
/**
* Print console error and groups.
*/
error: 3;
/**
* Force no logging from Workbox.
*/
silent: 4;
}
interface ICacheNameDetails {
prefix: string;
suffix: string;
precache: string;
runtime: string;
googleAnalytics: string;
}
/**
* All of the Workbox service worker libraries use workbox-core for shared code as well as setting default values that need to be shared (like cache names).
*/
declare class CoreNamespace {
/**
* cacheNames.precache is used for precached assets, cacheNames.googleAnalytics is used by workbox-google-analytics to store analytics.js, and cacheNames.runtime is used for everything else.
*/
static readonly cacheNames: ICacheNames;
/**
* The available log levels in Workbox: debug, log, warn, error and silent.
*/
static readonly LOG_LEVELS: ILogLevel;
/**
* Get the current log level.
*/
static readonly logLevel: ILogLevel[keyof ILogLevel];
/**
* You can alter the default cache names used by the Workbox modules by changing the cache name details.
* Cache names are generated as <prefix>-<Cache Name>-<suffix>.
* @param {Partial<ICacheNameDetails>} details
*/
static setCacheNameDetails (details: Partial<ICacheNameDetails>): void;
/**
* Set the current log level passing in one of the values from LOG_LEVELS.
* @param {number} logLevel - The new log level to use.
*/
static setLogLevel (logLevel: ILogLevel[keyof ILogLevel]): void;
}
/**
* ===== PrecachingNamespace =====
*/
interface IURLContext {
/**
* The request's URL.
*/
url: URL;
}
/**
* The "urlManipulation" callback can be used to determine if there are any additional permutations of a URL that should be used to check against the available precached files.
* For example, Workbox supports checking for '/index.html' when the URL '/' is provided. This callback allows additional, custom checks.
* @param {IURLContext} context
* @returns {URL[]} To add additional urls to test, return an Array of URL's. Please note that these should not be Strings, but URL objects.
*/
type UrlManipulation = (context: IURLContext) => URL[];
interface IRouteOptions {
/**
* The directoryIndex will check cache entries for a URLs ending with '/' to see if there is a hit when appending the directoryIndex value.
*/
directoryIndex: string|null;
/**
* An array of regex's to remove search params when looking for a cache match.
*/
ignoreUrlParametersMatching: RegExp[];
/**
* The cleanUrls option will check the cache for the URL with a .html added to the end of the end.
*/
cleanUrls: boolean;
/**
* This is a function that should take a URL and return an array of alternative URL's that should be checked for precache matches.
*/
urlManipulation: UrlManipulation;
}
/**
* Most consumers of this module will want to use the precacheAndRoute() method to add assets to the Cache and respond to network requests with these cached assets.
* If you require finer grained control, you can use the PrecacheController to determine when performed.
*/
declare class PrecachingNamespace {
/**
* Performs efficient precaching of assets.
*/
static readonly PrecacheController: IPrecacheControllerConstructor;
/**
* Add plugins to precaching.
* @param {Plugin[]} newPlugins
*/
static addPlugins (newPlugins: Plugin[]): void;
/**
* Add a fetch listener to the service worker that will respond to network requests with precached assets.
* Requests for assets that aren't precached, the FetchEvent will not be responded to, allowing the event to fall through to other fetch event listeners.
* @param {Partial<IRouteOptions>} route
*/
static addRoute (route: Partial<IRouteOptions>): void;
/**
* Add items to the precache list, removing any duplicates and store the files in the "precache cache" when the service worker installs.
* This method can be called multiple times.
* Please note: This method will not serve any of the cached files for you, it only precaches files. To respond to a network request you call addRoute().
* If you have a single array of files to precache, you can just call precacheAndRoute().
* @param {(string | IPrecacheEntry)[]} entries
*/
static precache (entries: (string|IPrecacheEntry)[]): void;
/**
* This method will add entries to the precache list and add a route to respond to fetch events.
* This is a convenience method that will call precache() and addRoute() in a single call.
* @param {(string | IPrecacheEntry)[]} entries - Array of entries to precache.
* @param {Partial<IRouteOptions>} [route] - see addRoute() options
*/
static precacheAndRoute (entries: (string|IPrecacheEntry)[], route?: Partial<IRouteOptions>): void;
/**
* Warnings will be logged if any of the precached assets are entered without a revision property.
* This is extremely dangerous if the URL's aren't revisioned.
* However, the warnings can be supressed with this method.
* @param {boolean} suppress
*/
static suppressWarnings (suppress: boolean): void;
}
/**
* ===== RoutingNamespace =====
*/
interface IRegisterNavigationRouteOptions extends INavigationRouteOptions {
cacheName: string;
}
declare class RoutingNamespace {
/**
* NavigationRoute makes it easy to create a Route that matches for browser navigation requests.
* It will only match incoming Requests whose mode is set to navigate.
* You can optionally only apply this route to a subset of navigation requests by using one or
* both of the blacklist and whitelist parameters.
*/
static readonly NavigationRoute: INavigationRouteConstructor;
/**
* RegExpRoute makes it easy to create a regular expression based Route.
* For same-origin requests the RegExp only needs to match part of the URL. For requests against third-party servers, you must define a RegExp that matches the start of the URL.
*/
static readonly RegExpRoute: IRegExpRouteConstructor;
/**
* A Route consists of a pair of callback functions, "match" and "handler". The "match" callback determine if a
* route should be used to "handle" a request by returning a non-falsy value if it can.
* The "handler" callback is called when there is a match and should return a Promise that resolves to a Response.
*/
static readonly Route: IRouteConstructor;
/**
* The Router can be used to process a FetchEvent through one or more Routes responding with a Request if a matching route exists.
* If no route matches a given a request, the Router will use a "default" handler if one is defined.
* Should the matching Route throw an error, the Router will use a "catch" handler if one is defined to gracefully deal with issues and respond with a Request.
* If a request matches multiple routes, the earliest registered route will be used to respond to the request.
*/
static readonly Router: IRouterConstructor;
/**
* Register a route that will return a precached file for a navigation request. This is useful for the application shell pattern.
* This method will generate a NavigationRoute and call Router.registerRoute().
* @param {string} cachedAssetUrl
* @param {Partial<IRegisterNavigationRouteOptions>} [options]
* @returns {NavigationRoute} Returns the generated Route.
*/
static registerNavigationRoute (cachedAssetUrl: string, options?: Partial<IRegisterNavigationRouteOptions>): NavigationRoute;
/**
* Easily register a RegExp, string, or function with a caching strategy to the Router.
* This method will generate a Route for you if needed and call Router.registerRoute().
* @param {string | RegExp | MatchCallback | Route} capture - If the capture param is a Route, all other arguments will be ignored.
* @param {HandlerCallback} handler - A callback function that returns a Promise resulting in a Response.
* @param {string} method - The HTTP method to match the Route against.
* @returns {Route} The generated Route(Useful for unregistering).
*/
static registerRoute (capture: string|RegExp|MatchCallback|Route, handler: HandlerCallback, method?: string): Route;
/**
* If a Route throws an error while handling a request, this handler will be called and given a chance to provide a response.
* @param {IHandlerOptions} handler - A callback function that returns a Promise resulting in a Response.
* @returns {Promise<Response>}
*/
static setCatchHandler (handler: IHandlerOptions): Promise<Response>;
/**
* Define a default handler that's called when no routes explicitly match the incoming request.
* Without a default handler, unmatched requests will go against the network as if there were no service worker present.
* @param {IHandlerOptions} handler - A callback function that returns a Promise resulting in a Response.
* @returns {Promise<Response>}
*/
static setDefaultHandler (handler: IHandlerOptions): Promise<Response>;
/**
* Unregisters a route with the router.
* @param {Route} route - The route to unregister
*/
static unregisterRoute (route: Route): void;
}
/**
* ===== StrategiesNamespace =====
*/
interface IStrategyOptions {
/**
* Name of cache to use for caching (both lookup and updating).
*/
cacheName: string;
/**
* Defining this object will add a cache expiration plugins to this strategy.
*/
cacheExpiration: Partial<ICacheExpirationOptions>;
/**
* The Plugins to use along with the Strategy
*/
plugins: Plugin[];
}
/**
* There are common caching strategies that most service workers will need and use. This module provides simple implementations of these strategies.
*/
declare class StrategiesNamespace {
/**
* An implementation of a cache-first request strategy.
* A cache first strategy is useful for assets that have been revisioned, such as URLs like /styles/example.a8f5f1.css, since they can be cached for long periods of time.
*/
static readonly CacheFirst: ICacheFirstConstructor;
/**
* An implementation of a cache-only request strategy.
* This class is useful if you want to take advantage of any Workbox plugins.
*/
static readonly CacheOnly: ICacheOnlyConstructor;
/**
* An implementation of a network first request strategy.
* By default, this strategy will cache responses with a 200 status code as well as opaque responses. Opaque responses are are cross-origin requests where the response doesn't support CORS.
*/
static readonly NetworkFirst: INetworkFirstConstructor;
/**
* An implementation of a network-only request strategy.
* This class is useful if you want to take advantage of any Workbox plugins.
*/
static readonly NetworkOnly: INetworkOnlyConstructor;
/**
* An implementation of a stale-while-revalidate request strategy.
* Resources are requested from both the cache and the network in parallel.
* The strategy will respond with the cached version if available, otherwise wait for the network response.
* The cache is updated with the network response with each successful request.
* By default, this strategy will cache responses with a 200 status code as well as opaque responses.
* Opaque responses are are cross-origin requests where the response doesn't support CORS.
*/
static readonly StaleWhileRevalidate: IStaleWhileRevalidateConstructor;
/**
* Instantiates a new CacheFirst strategy
* @param {Partial<IStrategyOptions>} [options]
* @returns {HandlerCallback}
*/
static cacheFirst (options?: Partial<IStrategyOptions>): HandlerCallback;
/**
* Instantiates a new CacheOnly strategy
* @param {Partial<IStrategyOptions>} [options]
* @returns {HandlerCallback}
*/
static cacheOnly (options?: Partial<IStrategyOptions>): HandlerCallback;
/**
* Instantiates a new NetworkFirst strategy
* @param {Partial<IStrategyOptions>} [options]
* @returns {HandlerCallback}
*/
static networkFirst (options?: Partial<IStrategyOptions>): HandlerCallback;
/**
* Instantiates a new NetworkOnly strategy
* @param {Partial<IStrategyOptions>} [options]
* @returns {HandlerCallback}
*/
static networkOnly (options?: Partial<IStrategyOptions>): HandlerCallback;
/**
* Instantiates a new StaleWhileRevalidate strategy
* @param {Partial<IStrategyOptions>} [options]
* @returns {StaleWhileRevalidate}
*/
static staleWhileRevalidate (options?: Partial<IStrategyOptions>): HandlerCallback;
}
/**
* ===== StreamsNamespace =====
*/
type StreamSource = Response|ReadableStream|BodyInit;
interface IConcatenateResult {
done: Promise<StreamSource>;
stream: ReadableStream;
}
interface IConcatenateToResponseResult {
done: Promise<StreamSource>;
response: Response;
}
declare class StreamsNamespace {
/**
* Takes multiple source Promises, each of which could resolve to a Response, a ReadableStream, or a BodyInit.
* Returns an object exposing a ReadableStream with each individual stream's data returned in sequence,
* along with a Promise which signals when the stream is finished (useful for passing to a FetchEvent's waitUntil()).
* @param {Promise<StreamSource>[]} sourcePromises - Array of Promise containing StreamSource
* @returns {IConcatenateResult}
*/
static concatenate (sourcePromises: Promise<StreamSource>[]): IConcatenateResult;
/**
* Takes multiple source Promises, each of which could resolve to a Response, a ReadableStream, or a BodyInit,along with a HeadersInit.
* Returns an object exposing a Response whose body consists of each individual stream's data returned in sequence,
* along with a Promise which signals when the stream is finished (useful for passing to a FetchEvent's waitUntil()).
* @param {Promise<StreamSource>[]} sourcePromises - Array of Promise containing StreamSource
* @param {HeadersInit} [headersInit] - If there's no Content-Type specified, 'text/html' will be used by default.
* @returns {IConcatenateToResponseResult}
*/
static concatenateToResponse (sourcePromises: Promise<StreamSource>[], headersInit?: HeadersInit): IConcatenateToResponseResult;
/**
* This is a utility method that determines whether the current browser supports the features required to create streamed responses. Currently, it checks if ReadableStream is available.
* @param {HeadersInit} [headersInit] - If there's no Content-Type specified, 'text/html' will be used by default.
* @returns {boolean} - true, if the current browser meets the requirements for streaming responses, and false otherwise.
*/
static createHeaders (headersInit?: HeadersInit): boolean;
/**
* This is a utility method that determines whether the current browser supports the features required to create streamed responses. Currently, it checks if ReadableStream is available.
* @returns {boolean} - true, if the current browser meets the requirements for streaming responses, and false otherwise.
*/
static isSupported (): boolean;
/**
* A shortcut to create a strategy that could be dropped-in to Workbox's router.
* On browsers that do not support constructing new ReadableStreams, this strategy will automatically wait for
* all the sourceFunctions to complete, and create a final response that concatenates their values together.
* @param {HandlerCallback[]} sourceFunctions - Each function should return a workbox.streams.StreamSource (or a Promise which resolves to one).
* @param {HeadersInit} headersInit . If there's no Content-Type specified, 'text/html' will be used by default.
* @returns {HandlerCallback}
*/
static strategy (sourceFunctions: HandlerCallback[], headersInit?: HeadersInit): HandlerCallback;
}
/**
* ===== ExpirationNamespace =====
*/
declare class ExpirationNamespace {
/**
* The CacheExpiration class allows you define an expiration and / or limit on the number of responses stored in a Cache.
*/
static readonly CacheExpiration: ICacheExpirationConstructor;
/**
* This plugin can be used in the Workbox API's to regularly enforce a limit on the age and / or the number of cached requests.
* Whenever a cached request is used or updated, this plugin will look at the used Cache and remove any old or extra requests.
* When using maxAgeSeconds, requests may be used once after expiring because the expiration clean up will not
* have occurred until after the cached request has been used. If the request has a "Date" header, then a light weight
* expiration check is performed and the request will not be used immediately.
* When using maxEntries, the last request to be used will be the request that is removed from the Cache.
*/
static readonly Plugin: IExpirationPluginConstructor;
}
/**
* ===== BackgroundSyncNamespace =====
*/
declare class BackgroundSyncNamespace {
/**
* A class implementing the fetchDidFail lifecycle callback. This makes it easier to add failed requests to a background sync Queue.
*/
static readonly Plugin: IBackgroundSyncPluginConstructor;
/**
* A class to manage storing failed requests in IndexedDB and retrying them later. All parts of the storing and replaying process are observable via callbacks.
*/
static readonly Queue: IQueueConstructor;
}
/**
* ===== GoogleAnalyticsNamespace =====
*/
interface IGoogleAnalyticsInitializeOptions {
/**
* The cache name to store and retrieve analytics.js. Defaults to the cache names provided by workbox-core.
*/
cacheName: string;
/**
* Measurement Protocol parameters, expressed as key/value pairs, to be added to replayed Google Analytics requests.
* This can be used to, e.g., set a custom dimension indicating that the request was replayed.
*/
parameterOverrides: { [key: string]: string };
/**
* A function that allows you to modify the hit parameters prior to replaying the hit. The function is invoked with the original hit's URLSearchParams object as its only argument.
* @param {URLSearchParams} params
*/
hitFilter (params: URLSearchParams): void;
}
declare class GoogleAnalyticsNamespace {
static initialize (options: Partial<IGoogleAnalyticsInitializeOptions>): void;
}
/**
* ===== CacheableResponseNamespace =====
*/
declare class CacheableResponseNamespace {
/**
* This class allows you to set up rules determining what status codes and/or headers need to be present in order for a Response to be considered cacheable.
*/
static readonly CacheableResponse: ICacheableResponseConstructor;
/**
* A class implementing the cacheWillUpdate lifecycle callback. This makes it easier to add in cacheability checks to requests made via Workbox's built-in strategies.
*/
static readonly Plugin: ICacheableResponsePluginConstructor;
}
/**
* ===== BroadcastUpdateNamespace =====
*/
declare class BroadcastUpdateNamespace {
/**
* Uses the Broadcast Channel API to notify interested parties when a cached response has been updated.
* For efficiency's sake, the underlying response bodies are not compared; only specific response headers are checked.
*/
static readonly BroadcastCacheUpdate: IBroadcastCacheUpdateConstructor;
/**
* This plugin will automatically broadcast a message whenever a cached response is updated.
*/
static readonly Plugin: IBroadcastUpdatePluginConstructor;
/**
* You would not normally call this method directly;
* it's called automatically by an instance of the BroadcastCacheUpdate class.
* It's exposed here for the benefit of developers who would rather not use the full BroadcastCacheUpdate implementation.
* Calling this will dispatch a message on the provided Broadcast Channel to notify interested subscribers about a
* change to a cached resource.
* The message that's posted has a formation inspired by the Flux standard action format like so:
* @param {BroadcastChannel} channel - The BroadcastChannel to use.
* @param {string} cacheName - The name of the cache in which the updated Response was stored.
* @param {string} url - The URL associated with the updated Response.
* @param {string} source - A string identifying this library as the source of the update message.
*/
static broadCastUpdate (channel: BroadcastChannel, cacheName: string, url: string, source: string): void;
}
/**
* ===== RangeRequestsNamespace =====
*/
declare class RangeRequestsNamespace {
/**
* The range request plugin makes it easy for a request with a 'Range' header to be fulfilled by a cached response.
* It does this by intercepting the cachedResponseWillBeUsed plugin callback and returning the appropriate subset of the cached response body.
*/
static readonly Plugin: IRangeRequestsPluginConstructor;
/**
* Given a Request and Response objects as input, this will return a promise for a new Response.
* @param {Request} request - A request, which should contain a Range: header.
* @param {Response} originalResponse - An original response containing the full content.
* @returns {Promise<Response>} Either a 206 Partial Content response, with the response body set to the slice of
* content specified by the request's Range: header, or a 416 Range Not Satisfiable response if the conditions of
* the Range: header can't be met.
*/
static createPartialResponse (request: Request, originalResponse: Response): Promise<Response>;
}
/**
* ===== Workbox Plugin =====
*/
interface WorkboxPlugin {
/**
* Called before a Response is used to update a cache. You can alter the Response before it’s added to the cache or return null to avoid updating the cache at all.
* @param {CacheWillUpdatePluginContext} context
* @returns {Promise<Response>|Response|null}
*/
readonly cacheWillUpdate?: ((context: CacheWillUpdatePluginContext) => Promise<Response>|Response|null) | undefined;
/**
* Called when a new entry is added to a cache or it’s updated. Useful if you wish to perform an action after a cache update.
* @param {CacheDidUpdatePluginContext} context
* @returns {void}
*/
readonly cacheDidUpdate?: ((context: CacheDidUpdatePluginContext) => void) | undefined;
/**
* Before a cached Response is used to respond to a fetch event, this callback can be used to allow or block the Response from being used.
* @param {CacheResponseWillBeUsedPluginContext} context
* @returns {Promise<Response>|Response|null}
*/
readonly cachedResponseWillBeUsed?: ((context: CacheResponseWillBeUsedPluginContext) => Promise<Response>|Response|null) | undefined;
/**
* This is called whenever a fetch event is about to be made. You can alter the Request in this callback.
* @param {RequestWillFetchPluginContext} context
* @returns {Request}
*/
readonly requestWillFetch?: ((context: RequestWillFetchPluginContext) => Request) | undefined;
/**
* Called when a fetch event fails (note this is when the network request can’t be made at all and not when a request is a non-200 request).
* @param {FetchDidFailPluginContext}
* @returns {void}
*/
readonly fetchDidFail?: ((context: FetchDidFailPluginContext) => void) | undefined;
}
interface CacheWillUpdatePluginContext {
readonly request: Request;
readonly response: Response;
}
interface CacheDidUpdatePluginContext {
readonly cacheName: string;
readonly request: Request;
readonly oldResponse: Response;
readonly newResponse: Response;
}
interface CacheResponseWillBeUsedPluginContext {
readonly cacheName: string;
readonly request: Request;
readonly matchOptions: any;
readonly cachedResponse: Response;
}
interface RequestWillFetchPluginContext {
readonly request: Request;
}
interface FetchDidFailPluginContext {
readonly originalRequest: Request;
readonly request: Request;
readonly error: Error;
}
/**
* ===== WorkboxNamespace =====
*/
/**
* A ModulePathCallback function can be used to modify the modify the where Workbox modules are loaded.
* @param {string} moduleName - The name of the module to load (i.e. 'workbox-core', 'workbox-precaching' etc.).
* @param {boolean} debug - When true, dev builds should be loaded, otherwise load prod builds.
* @returns {string} This callback should return a path of module. This will be passed to importScripts().
*/
type ModulePathCallback = (moduleName: string, debug: boolean) => string;
interface IConfigOptions {
/**
* If true, dev builds are using, otherwise prod builds are used. By default, prod is used unless on localhost.
*/
debug: boolean;
/**
* To avoid using the CDN with workbox-sw set the path prefix of where modules should be loaded from. For example modulePathPrefix: '/third_party/workbox/v3.0.0/'.
*/
modulePathPrefix: string;
/**
* If defined, this callback will be responsible for determining the path of each workbox module.
*/
modulePathCb: ModulePathCallback;
}
declare class WorkboxNamespace {
static readonly backgroundSync: typeof BackgroundSyncNamespace;
static readonly broadcastUpdate: typeof BroadcastUpdateNamespace;
static readonly cacheableResponse: typeof CacheableResponseNamespace;
static readonly core: typeof CoreNamespace;
static readonly expiration: typeof ExpirationNamespace;
static readonly googleAnalytics: typeof GoogleAnalyticsNamespace;
static readonly precaching: typeof PrecachingNamespace;
static readonly rangeRequests: typeof RangeRequestsNamespace;
static readonly routing: typeof RoutingNamespace;
static readonly strategies: typeof StrategiesNamespace;
static readonly streams: typeof StreamsNamespace;
/**
* Claim any currently available clients once the service worker becomes active. This is normally used in conjunction with skipWaiting().
*/
static clientsClaim (): void;
/**
* Load a Workbox module by passing in the appropriate module name.
* This is not generally needed unless you know there are modules that are dynamically used and you want to safe guard use of the module while the user may be offline.
* @param {string} moduleName
*/
static loadModule (moduleName: string): void;
/**
* Updates the configuration options. You can specify whether to treat as a debug build and whether to use a CDN or a specific path when importing other workbox-modules
* @param {Partial<IConfigOptions>} config
*/
static setConfig (config?: Partial<IConfigOptions>): void;
/**
* Force a service worker to become active, instead of waiting. This is normally used in conjunction with clientsClaim().
*/
static skipWaiting (): void;
}
export = WorkboxNamespace; | the_stack |
import { RangeSliderDemoPage } from './range-slider-demo.po';
import { approximateGeometryMatchers, expect } from '../utils';
import { Key, browser } from 'protractor';
describe('range slider', () => {
let page: RangeSliderDemoPage;
beforeEach(() => {
jasmine.addMatchers(approximateGeometryMatchers);
page = new RangeSliderDemoPage();
page.navigateTo('range-slider');
});
describe('initial state', () => {
it('displays starting values and position elements correctly', () => {
expect(page.getSliderFloorLabel().getText()).toBe('0');
expect(page.getSliderCeilLabel().getText()).toBe('250');
expect(page.getSliderLowPointerLabel().getText()).toBe('50');
expect(page.getLowValueInput().getAttribute('value')).toBe('50');
expect(page.getSliderHighPointerLabel().getText()).toBe('200');
expect(page.getHighValueInput().getAttribute('value')).toBe('200');
expect(page.getSliderFullBar().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 0, y: 3});
expect(page.getSliderFullBar().getSize()).toBeApproximateSize({width: 758, height: 32});
expect(page.getSliderFloorLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 0, y: -3});
expect(page.getSliderCeilLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 725, y: -3});
expect(page.getSliderLowPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 145, y: 21});
expect(page.getSliderLowPointer().getSize()).toBeApproximateSize({width: 32, height: 32});
expect(page.getSliderLowPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 149, y: -3});
expect(page.getSliderHighPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 581, y: 21});
expect(page.getSliderHighPointer().getSize()).toBeApproximateSize({width: 32, height: 32});
expect(page.getSliderHighPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 580, y: -3});
expect(page.getSliderSelectionBar().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 161, y: 3});
expect(page.getSliderSelectionBar().getSize()).toBeApproximateSize({width: 436, height: 32});
});
});
describe('after dragging the low slider pointer', () => {
const testCases: () => void = (): void => {
it('moves the low pointer to new position', () => {
expect(page.getSliderLowPointerLabel().getText()).toBe('125');
expect(page.getLowValueInput().getAttribute('value')).toBe('125');
expect(page.getHighValueInput().getAttribute('value')).toBe('200');
expect(page.getSliderHighPointerLabel().getText()).toBe('200');
expect(page.getSliderLowPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 363, y: 21});
expect(page.getSliderLowPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 363, y: -3});
expect(page.getSliderHighPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 581, y: 21});
expect(page.getSliderHighPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 580, y: -3});
expect(page.getSliderSelectionBar().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 379, y: 3});
expect(page.getSliderSelectionBar().getSize()).toBeApproximateSize({width: 218, height: 32});
});
};
describe('with mouse', () => {
beforeEach(() => {
page.getSliderLowPointer().mouseDragSync(218, -50);
});
testCases();
});
describe('with touch gesture', () => {
beforeEach(() => {
page.getSliderLowPointer().touchDragSync(218, 50);
});
testCases();
});
});
describe('after dragging the high slider pointer', () => {
const testCases: () => void = (): void => {
it('moves the high pointer to new position', () => {
expect(page.getSliderLowPointerLabel().getText()).toBe('50');
expect(page.getLowValueInput().getAttribute('value')).toBe('50');
expect(page.getSliderHighPointerLabel().getText()).toBe('125');
expect(page.getHighValueInput().getAttribute('value')).toBe('125');
expect(page.getSliderLowPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 145, y: 21});
expect(page.getSliderLowPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 149, y: -3});
expect(page.getSliderHighPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 363, y: 21});
expect(page.getSliderHighPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 363, y: -3});
expect(page.getSliderSelectionBar().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 161, y: 3});
expect(page.getSliderSelectionBar().getSize()).toBeApproximateSize({width: 218, height: 32});
});
};
describe('with mouse', () => {
beforeEach(() => {
page.getSliderHighPointer().mouseDragSync(-218, -50);
});
testCases();
});
describe('with touch gesture', () => {
beforeEach(() => {
page.getSliderHighPointer().touchDragSync(-218, 50);
});
testCases();
});
});
describe('after dragging the low and high pointers to the same position', () => {
beforeEach(() => {
page.getSliderLowPointer().mouseDragSync(379, 0);
page.getSliderHighPointer().mouseDragSync(-59, 0);
});
it('shows only the combined label instead of normal labels', () => {
expect(page.getLowValueInput().getAttribute('value')).toBe('180');
expect(page.getHighValueInput().getAttribute('value')).toBe('180');
expect(page.getSliderCombinedLabel().isVisible()).toBe(true);
expect(page.getSliderLowPointerLabel().isVisible()).toBe(false);
expect(page.getSliderHighPointerLabel().isVisible()).toBe(false);
expect(page.getSliderCombinedLabel().getText()).toBe('180 - 180');
expect(page.getSliderLowPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 523, y: 21});
expect(page.getSliderHighPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 523, y: 21});
expect(page.getSliderCombinedLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 502, y: -3});
expect(page.getSliderSelectionBar().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 539, y: 3});
expect(page.getSliderSelectionBar().getSize()).toBeApproximateSize({width: 0, height: 32});
});
});
describe('after dragging the low pointer past the high pointer', () => {
beforeEach(() => {
page.getSliderLowPointer().mouseDragSync(495, 0);
});
it('switches the low and high pointers and moves the high pointer to the new position', () => {
expect(page.getSliderLowPointerLabel().getText()).toBe('200');
expect(page.getLowValueInput().getAttribute('value')).toBe('200');
expect(page.getSliderHighPointerLabel().getText()).toBe('220');
expect(page.getHighValueInput().getAttribute('value')).toBe('220');
expect(page.getSliderLowPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 581, y: 21});
expect(page.getSliderLowPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 580, y: -3});
expect(page.getSliderHighPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 639, y: 21});
expect(page.getSliderHighPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 639, y: -3});
expect(page.getSliderSelectionBar().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 597, y: 3});
expect(page.getSliderSelectionBar().getSize()).toBeApproximateSize({width: 58, height: 32});
});
});
describe('after dragging the high pointer past the low pointer', () => {
beforeEach(() => {
page.getSliderHighPointer().mouseDragSync(-495, 0);
});
it('switches the low and high pointers and moves the low pointer to the new position', () => {
expect(page.getSliderLowPointerLabel().getText()).toBe('30');
expect(page.getLowValueInput().getAttribute('value')).toBe('30');
expect(page.getSliderHighPointerLabel().getText()).toBe('50');
expect(page.getHighValueInput().getAttribute('value')).toBe('50');
expect(page.getSliderLowPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 87, y: 21});
expect(page.getSliderLowPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 91, y: -3});
expect(page.getSliderHighPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 145, y: 21});
expect(page.getSliderHighPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 149, y: -3});
expect(page.getSliderSelectionBar().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 103, y: 3});
expect(page.getSliderSelectionBar().getSize()).toBeApproximateSize({width: 58, height: 32});
});
});
describe('after clicking on slider bar', () => {
describe('below low pointer', () => {
const testCases: () => void = (): void => {
it('moves the low pointer element to the click position', () => {
expect(page.getSliderLowPointerLabel().getText()).toBe('40');
expect(page.getLowValueInput().getAttribute('value')).toBe('40');
expect(page.getSliderHighPointerLabel().getText()).toBe('200');
expect(page.getHighValueInput().getAttribute('value')).toBe('200');
expect(page.getSliderLowPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 116, y: 21});
expect(page.getSliderLowPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 120, y: -3});
expect(page.getSliderHighPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 581, y: 21});
expect(page.getSliderHighPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 581, y: -3});
expect(page.getSliderSelectionBar().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 132, y: 3});
expect(page.getSliderSelectionBar().getSize()).toBeApproximateSize({width: 465, height: 32});
});
};
describe('with mouse', () => {
beforeEach(() => {
page.getSliderFullBar().mouseClick(-248, 0);
});
testCases();
});
describe('with touch gesture', () => {
beforeEach(() => {
page.getSliderFullBar().touchTap(-248, 0);
});
testCases();
});
});
describe('above high pointer', () => {
const testCases: () => void = (): void => {
it('moves the high pointer element to the click position', () => {
expect(page.getSliderLowPointerLabel().getText()).toBe('50');
expect(page.getLowValueInput().getAttribute('value')).toBe('50');
expect(page.getHighValueInput().getAttribute('value')).toBe('210');
expect(page.getSliderHighPointerLabel().getText()).toBe('210');
expect(page.getSliderLowPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 145, y: 21});
expect(page.getSliderLowPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 149, y: -3});
expect(page.getSliderHighPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 610, y: 21});
expect(page.getSliderHighPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 610, y: -3});
expect(page.getSliderSelectionBar().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 161, y: 3});
expect(page.getSliderSelectionBar().getSize()).toBeApproximateSize({width: 465, height: 32});
});
};
describe('with mouse', () => {
beforeEach(() => {
page.getSliderFullBar().mouseClick(248, 0);
});
testCases();
});
describe('with touch gesture', () => {
beforeEach(() => {
page.getSliderFullBar().touchTap(248, 0);
});
testCases();
});
});
});
describe('after clicking on selection bar', () => {
describe('closer to low pointer', () => {
const testCases: () => void = (): void => {
it('moves the low pointer element to the click position', () => {
expect(page.getSliderLowPointerLabel().getText()).toBe('90');
expect(page.getLowValueInput().getAttribute('value')).toBe('90');
expect(page.getSliderHighPointerLabel().getText()).toBe('200');
expect(page.getHighValueInput().getAttribute('value')).toBe('200');
expect(page.getSliderLowPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 261, y: 21});
expect(page.getSliderLowPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 265, y: -3});
expect(page.getSliderHighPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 581, y: 21});
expect(page.getSliderHighPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 581, y: -3});
expect(page.getSliderSelectionBar().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 277, y: 3});
expect(page.getSliderSelectionBar().getSize()).toBeApproximateSize({width: 319, height: 32});
});
};
describe('with mouse', () => {
beforeEach(() => {
page.getSliderSelectionBar().mouseClick(-102, 0);
});
testCases();
});
describe('with touch gesture', () => {
beforeEach(() => {
page.getSliderSelectionBar().touchTap(-102, 0);
});
testCases();
});
});
describe('closer to high pointer', () => {
const testCases: () => void = (): void => {
it('moves the high pointer element to the click position', () => {
expect(page.getSliderLowPointerLabel().getText()).toBe('50');
expect(page.getLowValueInput().getAttribute('value')).toBe('50');
expect(page.getSliderHighPointerLabel().getText()).toBe('160');
expect(page.getHighValueInput().getAttribute('value')).toBe('160');
expect(page.getSliderLowPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 145, y: 21});
expect(page.getSliderLowPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 149, y: -3});
expect(page.getSliderHighPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 465, y: 21});
expect(page.getSliderHighPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 465, y: -3});
expect(page.getSliderSelectionBar().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 161, y: 3});
expect(page.getSliderSelectionBar().getSize()).toBeApproximateSize({width: 319, height: 32});
});
};
describe('with mouse', () => {
beforeEach(() => {
page.getSliderSelectionBar().mouseClick(102, 0);
});
testCases();
});
describe('with touch gesture', () => {
beforeEach(() => {
page.getSliderSelectionBar().touchTap(102, 0);
});
testCases();
});
});
});
describe('keyboard input', () => {
describe('on the low pointer element', () => {
const incrementByStepTestCases: () => void = (): void => {
it('increases the low value by step', () => {
expect(page.getSliderLowPointerLabel().getText()).toBe('51');
expect(page.getLowValueInput().getAttribute('value')).toBe('51');
expect(page.getSliderHighPointerLabel().getText()).toBe('200');
expect(page.getHighValueInput().getAttribute('value')).toBe('200');
expect(page.getSliderLowPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 148, y: 21});
expect(page.getSliderLowPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 152, y: -3});
expect(page.getSliderHighPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 581, y: 21});
expect(page.getSliderHighPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 581, y: -3});
expect(page.getSliderSelectionBar().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 164, y: 3});
expect(page.getSliderSelectionBar().getSize()).toBeApproximateSize({width: 433, height: 32});
});
};
describe('after pressing right arrow', () => {
beforeEach(() => {
page.getSliderLowPointer().sendKeys(Key.ARROW_RIGHT);
});
incrementByStepTestCases();
});
describe('after pressing up arrow', () => {
beforeEach(() => {
page.getSliderLowPointer().sendKeys(Key.ARROW_UP);
});
incrementByStepTestCases();
});
const decrementByStepTestCases: () => void = (): void => {
it('decreases the low value by step', () => {
expect(page.getSliderLowPointerLabel().getText()).toBe('49');
expect(page.getLowValueInput().getAttribute('value')).toBe('49');
expect(page.getSliderHighPointerLabel().getText()).toBe('200');
expect(page.getHighValueInput().getAttribute('value')).toBe('200');
expect(page.getSliderLowPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 142, y: 21});
expect(page.getSliderLowPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 146, y: -3});
expect(page.getSliderHighPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 581, y: 21});
expect(page.getSliderHighPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 581, y: -3});
expect(page.getSliderSelectionBar().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 158, y: 3});
expect(page.getSliderSelectionBar().getSize()).toBeApproximateSize({width: 439, height: 32});
});
};
describe('after pressing left arrow', () => {
beforeEach(() => {
page.getSliderLowPointer().sendKeys(Key.ARROW_LEFT);
});
decrementByStepTestCases();
});
describe('after pressing down arrow', () => {
beforeEach(() => {
page.getSliderLowPointer().sendKeys(Key.ARROW_DOWN);
});
decrementByStepTestCases();
});
describe('after pressing page up', () => {
beforeEach(() => {
page.getSliderLowPointer().sendKeys(Key.PAGE_UP);
});
it('increases the low value by larger offset', () => {
expect(page.getSliderLowPointerLabel().getText()).toBe('75');
expect(page.getLowValueInput().getAttribute('value')).toBe('75');
expect(page.getSliderHighPointerLabel().getText()).toBe('200');
expect(page.getHighValueInput().getAttribute('value')).toBe('200');
expect(page.getSliderLowPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 218, y: 21});
expect(page.getSliderLowPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 222, y: -3});
expect(page.getSliderHighPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 581, y: 21});
expect(page.getSliderHighPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 581, y: -3});
expect(page.getSliderSelectionBar().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 234, y: 3});
expect(page.getSliderSelectionBar().getSize()).toBeApproximateSize({width: 363, height: 32});
});
});
describe('after pressing page down', () => {
beforeEach(() => {
page.getSliderLowPointer().sendKeys(Key.PAGE_DOWN);
});
it('decreases the low value by larger offset', () => {
expect(page.getSliderLowPointerLabel().getText()).toBe('25');
expect(page.getLowValueInput().getAttribute('value')).toBe('25');
expect(page.getSliderHighPointerLabel().getText()).toBe('200');
expect(page.getHighValueInput().getAttribute('value')).toBe('200');
expect(page.getSliderLowPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 73, y: 21});
expect(page.getSliderLowPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 77, y: -3});
expect(page.getSliderHighPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 581, y: 21});
expect(page.getSliderHighPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 581, y: -3});
expect(page.getSliderSelectionBar().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 89, y: 3});
expect(page.getSliderSelectionBar().getSize()).toBeApproximateSize({width: 508, height: 32});
});
});
describe('after pressing home', () => {
beforeEach(() => {
page.getSliderLowPointer().sendKeys(Key.HOME);
});
it('sets the value to minimum and hides the floor label', () => {
expect(page.getSliderLowPointerLabel().getText()).toBe('0');
expect(page.getLowValueInput().getAttribute('value')).toBe('0');
expect(page.getSliderFloorLabel().isVisible()).toBe(false);
expect(page.getSliderHighPointerLabel().getText()).toBe('200');
expect(page.getHighValueInput().getAttribute('value')).toBe('200');
expect(page.getSliderCeilLabel().isVisible()).toBe(true);
expect(page.getSliderLowPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 0, y: 21});
expect(page.getSliderLowPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 9, y: -3});
expect(page.getSliderHighPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 581, y: 21});
expect(page.getSliderHighPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 581, y: -3});
expect(page.getSliderSelectionBar().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 16, y: 3});
expect(page.getSliderSelectionBar().getSize()).toBeApproximateSize({width: 581, height: 32});
});
});
describe('after pressing end', () => {
beforeEach(() => {
page.getSliderLowPointer().sendKeys(Key.END);
});
it('sets the value to maximum, switching pointers and hiding the ceil label', () => {
expect(page.getSliderLowPointerLabel().getText()).toBe('200');
expect(page.getLowValueInput().getAttribute('value')).toBe('200');
expect(page.getSliderFloorLabel().isVisible()).toBe(true);
expect(page.getSliderHighPointerLabel().getText()).toBe('250');
expect(page.getHighValueInput().getAttribute('value')).toBe('250');
expect(page.getSliderCeilLabel().isVisible()).toBe(false);
expect(page.getSliderLowPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 581, y: 21});
expect(page.getSliderLowPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 581, y: -3});
expect(page.getSliderHighPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 726, y: 21});
expect(page.getSliderHighPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 726, y: -3});
expect(page.getSliderSelectionBar().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 597, y: 3});
expect(page.getSliderSelectionBar().getSize()).toBeApproximateSize({width: 145, height: 32});
});
});
});
describe('on the high pointer element', () => {
const incrementByStepTestCases: () => void = (): void => {
it('increases the high value by step', () => {
expect(page.getSliderLowPointerLabel().getText()).toBe('50');
expect(page.getLowValueInput().getAttribute('value')).toBe('50');
expect(page.getSliderHighPointerLabel().getText()).toBe('201');
expect(page.getHighValueInput().getAttribute('value')).toBe('201');
expect(page.getSliderLowPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 145, y: 21});
expect(page.getSliderLowPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 149, y: -3});
expect(page.getSliderHighPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 584, y: 21});
expect(page.getSliderHighPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 584, y: -3});
expect(page.getSliderSelectionBar().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 161, y: 3});
expect(page.getSliderSelectionBar().getSize()).toBeApproximateSize({width: 439, height: 32});
});
};
describe('after pressing right arrow', () => {
beforeEach(() => {
page.getSliderHighPointer().sendKeys(Key.ARROW_RIGHT);
});
incrementByStepTestCases();
});
describe('after pressing up arrow', () => {
beforeEach(() => {
page.getSliderHighPointer().sendKeys(Key.ARROW_UP);
});
incrementByStepTestCases();
});
const decrementByStepTestCases: () => void = (): void => {
it('decreases the high value by step', () => {
expect(page.getSliderLowPointerLabel().getText()).toBe('50');
expect(page.getLowValueInput().getAttribute('value')).toBe('50');
expect(page.getSliderHighPointerLabel().getText()).toBe('199');
expect(page.getHighValueInput().getAttribute('value')).toBe('199');
expect(page.getSliderLowPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 145, y: 21});
expect(page.getSliderLowPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 149, y: -3});
expect(page.getSliderHighPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 578, y: 21});
expect(page.getSliderHighPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 578, y: -3});
expect(page.getSliderSelectionBar().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 161, y: 3});
expect(page.getSliderSelectionBar().getSize()).toBeApproximateSize({width: 433, height: 32});
});
};
describe('after pressing left arrow', () => {
beforeEach(() => {
page.getSliderHighPointer().sendKeys(Key.ARROW_LEFT);
});
decrementByStepTestCases();
});
describe('after pressing down arrow', () => {
beforeEach(() => {
page.getSliderHighPointer().sendKeys(Key.ARROW_DOWN);
});
decrementByStepTestCases();
});
describe('after pressing page up', () => {
beforeEach(() => {
page.getSliderHighPointer().sendKeys(Key.PAGE_UP);
});
it('increases the high value by larger offset', () => {
expect(page.getSliderLowPointerLabel().getText()).toBe('50');
expect(page.getLowValueInput().getAttribute('value')).toBe('50');
expect(page.getSliderHighPointerLabel().getText()).toBe('225');
expect(page.getHighValueInput().getAttribute('value')).toBe('225');
expect(page.getSliderLowPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 145, y: 21});
expect(page.getSliderLowPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 149, y: -3});
expect(page.getSliderHighPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 653, y: 21});
expect(page.getSliderHighPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 653, y: -3});
expect(page.getSliderSelectionBar().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 161, y: 3});
expect(page.getSliderSelectionBar().getSize()).toBeApproximateSize({width: 508, height: 32});
});
});
describe('after pressing page down', () => {
beforeEach(() => {
page.getSliderHighPointer().sendKeys(Key.PAGE_DOWN);
});
it('decreases the high value by larger offset', () => {
expect(page.getSliderLowPointerLabel().getText()).toBe('50');
expect(page.getLowValueInput().getAttribute('value')).toBe('50');
expect(page.getSliderHighPointerLabel().getText()).toBe('175');
expect(page.getHighValueInput().getAttribute('value')).toBe('175');
expect(page.getSliderLowPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 145, y: 21});
expect(page.getSliderLowPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 149, y: -3});
expect(page.getSliderHighPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 508, y: 21});
expect(page.getSliderHighPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 508, y: -3});
expect(page.getSliderSelectionBar().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 161, y: 3});
expect(page.getSliderSelectionBar().getSize()).toBeApproximateSize({width: 363, height: 32});
});
});
describe('after pressing home', () => {
beforeEach(() => {
page.getSliderHighPointer().sendKeys(Key.HOME);
});
it('sets the value to minimum, switching pointers and hiding the floor label', () => {
expect(page.getSliderLowPointerLabel().getText()).toBe('0');
expect(page.getLowValueInput().getAttribute('value')).toBe('0');
expect(page.getSliderFloorLabel().isVisible()).toBe(false);
expect(page.getSliderHighPointerLabel().getText()).toBe('50');
expect(page.getHighValueInput().getAttribute('value')).toBe('50');
expect(page.getSliderCeilLabel().isVisible()).toBe(true);
expect(page.getSliderLowPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 0, y: 21});
expect(page.getSliderLowPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 9, y: -3});
expect(page.getSliderHighPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 145, y: 21});
expect(page.getSliderHighPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 149, y: -3});
expect(page.getSliderSelectionBar().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 16, y: 3});
expect(page.getSliderSelectionBar().getSize()).toBeApproximateSize({width: 145, height: 32});
});
});
describe('after pressing end', () => {
beforeEach(() => {
page.getSliderHighPointer().sendKeys(Key.END);
});
it('sets the high value to maximum and hides the ceil label', () => {
expect(page.getSliderLowPointerLabel().getText()).toBe('50');
expect(page.getLowValueInput().getAttribute('value')).toBe('50');
expect(page.getSliderFloorLabel().isVisible()).toBe(true);
expect(page.getSliderHighPointerLabel().getText()).toBe('250');
expect(page.getHighValueInput().getAttribute('value')).toBe('250');
expect(page.getSliderCeilLabel().isVisible()).toBe(false);
expect(page.getSliderLowPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 145, y: 21});
expect(page.getSliderLowPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 149, y: -3});
expect(page.getSliderHighPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 726, y: 21});
expect(page.getSliderHighPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 725, y: -3});
expect(page.getSliderSelectionBar().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 161, y: 3});
expect(page.getSliderSelectionBar().getSize()).toBeApproximateSize({width: 581, height: 32});
});
});
});
});
describe('after changing low input value in the form', () => {
beforeEach(() => {
// Due to normalisation checks, we need to ensure that inputs contain valid data at all times while editing
// Low value: 50 -> 5 -> 25 -> 125
page.getLowValueInput().sendKeys(Key.END, Key.BACK_SPACE).then(() => {
browser.sleep(200).then(() => {
page.getLowValueInput().sendKeys(Key.HOME, '2').then(() => {
browser.sleep(200).then(() => {
page.getLowValueInput().sendKeys(Key.HOME, '1');
});
});
});
});
});
it('sets the low value to new input', () => {
expect(page.getLowValueInput().getAttribute('value')).toBe('125');
expect(page.getSliderLowPointerLabel().getText()).toBe('125');
expect(page.getHighValueInput().getAttribute('value')).toBe('200');
expect(page.getSliderHighPointerLabel().getText()).toBe('200');
expect(page.getSliderLowPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 363, y: 21});
expect(page.getSliderLowPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 363, y: -3});
expect(page.getSliderHighPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 581, y: 21});
expect(page.getSliderHighPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 581, y: -3});
expect(page.getSliderSelectionBar().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 379, y: 3});
expect(page.getSliderSelectionBar().getSize()).toBeApproximateSize({width: 218, height: 32});
});
});
describe('after changing high input value in the form', () => {
beforeEach(() => {
// Due to normalisation checks, we need to change both inputs and ensure that they contain valid data at all times while editing
// We also need to wait between edits, so that changes are propagated correctly due to throttling
// Low value: 50 -> 0
page.getLowValueInput().sendKeys(Key.END, Key.LEFT, Key.BACK_SPACE).then(() => {
browser.sleep(200).then(() => {
// High value: 200 -> 20
page.getHighValueInput().sendKeys(Key.END, Key.BACK_SPACE).then(() => {
browser.sleep(200).then(() => {
// 20 -> 2
page.getHighValueInput().sendKeys(Key.END, Key.BACK_SPACE).then(() => {
browser.sleep(200).then(() => {
// 2 -> 25
page.getHighValueInput().sendKeys(Key.END, '5').then(() => {
browser.sleep(200).then(() => {
// 2 -> 25
page.getHighValueInput().sendKeys(Key.HOME, '1');
});
});
});
});
});
});
});
});
});
it('sets the high value to new input', () => {
browser.sleep(1200).then(() => {
expect(page.getSliderLowPointerLabel().getText()).toBe('0');
expect(page.getLowValueInput().getAttribute('value')).toBe('0');
expect(page.getSliderHighPointerLabel().getText()).toBe('125');
expect(page.getHighValueInput().getAttribute('value')).toBe('125');
expect(page.getSliderLowPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 0, y: 21});
expect(page.getSliderLowPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 9, y: -3});
expect(page.getSliderHighPointer().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 363, y: 21});
expect(page.getSliderHighPointerLabel().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 363, y: -3});
expect(page.getSliderSelectionBar().getRelativeLocationWithoutMargins()).toBeApproximateLocation({x: 16, y: 3});
expect(page.getSliderSelectionBar().getSize()).toBeApproximateSize({width: 363, height: 32});
});
});
});
}); | the_stack |
import {
Renderer,
SnappableProps,
SnappableState,
SnapGuideline,
SnapInfo,
BoundInfo,
ScalableProps,
SnapPosInfo,
RotatableProps,
RectInfo,
DraggableProps,
SnapOffsetInfo,
GapGuideline,
MoveableManagerInterface,
SnappableRenderType,
BoundType,
SnapBoundInfo,
MoveableGroupInterface,
} from "../types";
import {
prefix,
calculatePoses,
getRect,
getAbsolutePosesByState,
getAbsolutePoses,
getDistSize,
groupBy,
flat,
maxOffset,
minOffset,
triggerEvent,
calculateInversePosition,
directionCondition,
getClientRect,
getRefTarget,
getDragDistByState,
} from "../utils";
import {
IObject, findIndex, hasClass, getRad, getDist,
throttle,
} from "@daybrush/utils";
import {
getPosByReverseDirection,
getDragDist,
scaleMatrix,
getPosByDirection,
} from "../gesto/GestoUtils";
import { minus, rotate, plus } from "@scena/matrix";
import { dragControlCondition as rotatableDragControlCondtion } from "./Rotatable";
import { FLOAT_POINT_NUM, TINY_NUM } from "../consts";
import {
getInnerBoundInfo,
getCheckInnerBoundLines,
getInnerBoundDragInfo,
checkRotateInnerBounds,
checkInnerBoundPoses,
} from "./snappable/innerBounds";
import {
checkBoundPoses,
checkRotateBounds,
checkBoundKeepRatio,
getBounds,
} from "./snappable/bounds";
import {
checkSnaps,
getSnapInfosByDirection,
checkMoveableSnapPoses,
getNearestSnapGuidelineInfo,
getNearOffsetInfo,
checkSnapKeepRatio,
checkSnapPoses,
getElementGuidelines,
calculateContainerPos,
getTotalGuidelines,
} from "./snappable/snap";
import {
renderElementGroups, renderSnapPoses,
renderGuidelines, renderGapGuidelines,
filterElementInnerGuidelines,
} from "./snappable/render";
interface DirectionSnapType<T> {
vertical: T;
horizontal: T;
}
export function snapStart(
moveable: MoveableManagerInterface<SnappableProps, SnappableState>
) {
const state = moveable.state;
if (state.guidelines && state.guidelines.length) {
return;
}
const container = moveable.state.container;
const snapContainer = moveable.props.snapContainer || container!;
const containerClientRect = state.containerClientRect;
const snapOffset = {
left: 0,
top: 0,
bottom: 0,
right: 0,
};
if (container !== snapContainer) {
const snapContainerTarget = getRefTarget(snapContainer, true);
if (snapContainerTarget) {
const snapContainerRect = getClientRect(snapContainerTarget);
const offset1 = getDragDistByState(state, [
snapContainerRect.left - containerClientRect.left,
snapContainerRect.top - containerClientRect.top,
]);
const offset2 = getDragDistByState(state, [
snapContainerRect.right - containerClientRect.right,
snapContainerRect.bottom - containerClientRect.bottom,
]);
snapOffset.left = throttle(offset1[0], 0.1);
snapOffset.top = throttle(offset1[1], 0.1);
snapOffset.right = throttle(offset2[0], 0.1);
snapOffset.bottom = throttle(offset2[1], 0.1);
}
}
state.snapOffset = snapOffset;
state.elementGuidelineValues = [];
state.staticGuidelines = getElementGuidelines(moveable, false);
state.guidelines = getTotalGuidelines(moveable);
state.enableSnap = true;
}
export function hasGuidelines(
moveable: MoveableManagerInterface<any, any>,
ableName: string
): moveable is MoveableManagerInterface<SnappableProps, SnappableState> {
const {
props: {
snappable,
bounds,
innerBounds,
verticalGuidelines,
horizontalGuidelines,
snapGridWidth,
snapGridHeight,
},
state: { guidelines, enableSnap },
} = moveable;
if (
!snappable ||
!enableSnap ||
(ableName && snappable !== true && snappable.indexOf(ableName) < 0)
) {
return false;
}
if (
snapGridWidth ||
snapGridHeight ||
bounds ||
innerBounds ||
(guidelines && guidelines.length) ||
(verticalGuidelines && verticalGuidelines.length) ||
(horizontalGuidelines && horizontalGuidelines.length)
) {
return true;
}
return false;
}
function solveNextOffset(
pos1: number[],
pos2: number[],
offset: number,
isVertical: boolean,
datas: IObject<any>
) {
const sizeOffset = solveEquation(pos1, pos2, offset, isVertical);
if (!sizeOffset) {
return {
isOutside: false,
offset: [0, 0],
};
}
const size = getDist(pos1, pos2);
const dist1 = getDist(sizeOffset, pos1);
const dist2 = getDist(sizeOffset, pos2);
const isOutside = dist1 > size || dist2 > size;
const [widthOffset, heightOffset] = getDragDist({
datas,
distX: sizeOffset[0],
distY: sizeOffset[1],
});
return {
offset: [widthOffset, heightOffset],
isOutside,
};
}
function getNextFixedPoses(
matrix: number[],
width: number,
height: number,
fixedPos: number[],
direction: number[],
is3d: boolean
) {
const nextPoses = calculatePoses(matrix, width, height, is3d ? 4 : 3);
const nextPos = getPosByReverseDirection(nextPoses, direction);
return getAbsolutePoses(nextPoses, minus(fixedPos, nextPos));
}
function getSnapBoundOffset(boundInfo: BoundInfo, snapInfo: SnapOffsetInfo) {
if (boundInfo.isBound) {
return boundInfo.offset;
} else if (snapInfo.isSnap) {
return snapInfo.offset;
}
return 0;
}
function getSnapBound(boundInfo: BoundInfo, snapInfo: SnapInfo) {
if (boundInfo.isBound) {
return boundInfo.offset;
} else if (snapInfo.isSnap) {
return getNearestSnapGuidelineInfo(snapInfo).offset;
}
return 0;
}
export function checkSnapBoundsKeepRatio(
moveable: MoveableManagerInterface<SnappableProps, SnappableState>,
startPos: number[],
endPos: number[],
isRequest: boolean
): DirectionSnapType<SnapBoundInfo> {
const {
horizontal: horizontalBoundInfo,
vertical: verticalBoundInfo,
} = checkBoundKeepRatio(moveable, startPos, endPos);
const {
horizontal: horizontalSnapInfo,
vertical: verticalSnapInfo,
} = isRequest ? ({
horizontal: { isSnap: false },
vertical: { isSnap: false },
} as any) : checkSnapKeepRatio(moveable, startPos, endPos);
const horizontalOffset = getSnapBoundOffset(
horizontalBoundInfo,
horizontalSnapInfo
);
const verticalOffset = getSnapBoundOffset(
verticalBoundInfo,
verticalSnapInfo
);
const horizontalDist = Math.abs(horizontalOffset);
const verticalDist = Math.abs(verticalOffset);
return {
horizontal: {
isBound: horizontalBoundInfo.isBound,
isSnap: horizontalSnapInfo.isSnap,
offset: horizontalOffset,
dist: horizontalDist,
},
vertical: {
isBound: verticalBoundInfo.isBound,
isSnap: verticalSnapInfo.isSnap,
offset: verticalOffset,
dist: verticalDist,
},
};
}
export function checkMoveableSnapBounds(
moveable: MoveableManagerInterface<SnappableProps, SnappableState>,
isRequest: boolean,
poses: number[][],
boundPoses: number[][] = poses
): DirectionSnapType<Required<SnapBoundInfo>> {
const {
horizontal: horizontalBoundInfos,
vertical: verticalBoundInfos,
} = checkBoundPoses(
getBounds(moveable),
boundPoses.map((pos) => pos[0]),
boundPoses.map((pos) => pos[1])
);
const {
horizontal: horizontalSnapInfo,
vertical: verticalSnapInfo,
} = isRequest ? {
horizontal: { isSnap: false, index: -1 } as SnapInfo,
vertical: { isSnap: false, index: -1 } as SnapInfo,
} : checkMoveableSnapPoses(
moveable,
poses.map((pos) => pos[0]),
poses.map((pos) => pos[1]),
moveable.props.snapCenter
);
const horizontalOffset = getSnapBound(
horizontalBoundInfos[0],
horizontalSnapInfo
);
const verticalOffset = getSnapBound(
verticalBoundInfos[0],
verticalSnapInfo
);
const horizontalDist = Math.abs(horizontalOffset);
const verticalDist = Math.abs(verticalOffset);
return {
horizontal: {
isBound: horizontalBoundInfos[0].isBound,
isSnap: horizontalSnapInfo.isSnap,
snapIndex: horizontalSnapInfo.index,
offset: horizontalOffset,
dist: horizontalDist,
bounds: horizontalBoundInfos,
snap: horizontalSnapInfo,
},
vertical: {
isBound: verticalBoundInfos[0].isBound,
isSnap: verticalSnapInfo.isSnap,
snapIndex: verticalSnapInfo.index,
offset: verticalOffset,
dist: verticalDist,
bounds: verticalBoundInfos,
snap: verticalSnapInfo,
},
};
}
export function checkSnapBounds(
guideines: SnapGuideline[],
bounds: BoundType | undefined | false,
posesX: number[],
posesY: number[],
options: {
isRequest?: boolean;
snapThreshold?: number;
snapCenter?: boolean;
snapElement?: boolean;
} = {}
): DirectionSnapType<Required<SnapBoundInfo>> {
const {
horizontal: horizontalBoundInfos,
vertical: verticalBoundInfos,
} = checkBoundPoses(bounds, posesX, posesY);
const {
horizontal: horizontalSnapInfo,
vertical: verticalSnapInfo,
} = options.isRequest ? {
horizontal: { isSnap: false, index: -1 } as SnapInfo,
vertical: { isSnap: false, index: -1 } as SnapInfo,
} : checkSnapPoses(guideines, posesX, posesY, options);
const horizontalOffset = getSnapBound(
horizontalBoundInfos[0],
horizontalSnapInfo
);
const verticalOffset = getSnapBound(
verticalBoundInfos[0],
verticalSnapInfo
);
const horizontalDist = Math.abs(horizontalOffset);
const verticalDist = Math.abs(verticalOffset);
return {
horizontal: {
isBound: horizontalBoundInfos[0].isBound,
isSnap: horizontalSnapInfo.isSnap,
snapIndex: horizontalSnapInfo.index,
offset: horizontalOffset,
dist: horizontalDist,
bounds: horizontalBoundInfos,
snap: horizontalSnapInfo,
},
vertical: {
isBound: verticalBoundInfos[0].isBound,
isSnap: verticalSnapInfo.isSnap,
snapIndex: verticalSnapInfo.index,
offset: verticalOffset,
dist: verticalDist,
bounds: verticalBoundInfos,
snap: verticalSnapInfo,
},
};
}
export function normalized(value: number) {
return value ? value / Math.abs(value) : 0;
}
export function checkMaxBounds(
moveable: MoveableManagerInterface<SnappableProps>,
poses: number[][],
direction: number[],
fixedPosition: number[],
datas: any
) {
const fixedDirection = [-direction[0], -direction[1]];
const { width, height } = moveable.state;
const bounds = moveable.props.bounds;
let maxWidth = Infinity;
let maxHeight = Infinity;
if (bounds) {
const directions = [
[direction[0], -direction[1]],
[-direction[0], direction[1]],
];
const {
left = -Infinity,
top = -Infinity,
right = Infinity,
bottom = Infinity,
} = bounds;
directions.forEach((otherDirection) => {
const isCheckVertical = otherDirection[0] !== fixedDirection[0];
const isCheckHorizontal = otherDirection[1] !== fixedDirection[1];
const otherPos = getPosByDirection(poses, otherDirection);
const deg = (getRad(fixedPosition, otherPos) * 360) / Math.PI;
if (isCheckHorizontal) {
const nextOtherPos = otherPos.slice();
if (Math.abs(deg - 360) < 2 || Math.abs(deg - 180) < 2) {
nextOtherPos[1] = fixedPosition[1];
}
const {
offset: [, heightOffset],
isOutside: isHeightOutside,
} = solveNextOffset(
fixedPosition,
nextOtherPos,
(fixedPosition[1] < otherPos[1] ? bottom : top) -
otherPos[1],
false,
datas
);
if (!isNaN(heightOffset)) {
maxHeight = height + (isHeightOutside ? 1 : -1) * Math.abs(heightOffset);
}
}
if (isCheckVertical) {
const nextOtherPos = otherPos.slice();
if (Math.abs(deg - 90) < 2 || Math.abs(deg - 270) < 2) {
nextOtherPos[0] = fixedPosition[0];
}
const {
offset: [widthOffset],
isOutside: isWidthOutside,
} = solveNextOffset(
fixedPosition,
nextOtherPos,
(fixedPosition[0] < otherPos[0] ? right : left) - otherPos[0],
true,
datas
);
if (!isNaN(widthOffset)) {
maxWidth = width + (isWidthOutside ? 1 : -1) * Math.abs(widthOffset);
}
}
});
}
return {
maxWidth,
maxHeight,
};
}
function checkSnapRightLine(
startPos: number[],
endPos: number[],
snapBoundInfo: { vertical: SnapBoundInfo; horizontal: SnapBoundInfo },
keepRatio: boolean
) {
const rad = (getRad(startPos, endPos) / Math.PI) * 180;
const {
vertical: {
isBound: isVerticalBound,
isSnap: isVerticalSnap,
dist: verticalDist,
},
horizontal: {
isBound: isHorizontalBound,
isSnap: isHorizontalSnap,
dist: horizontalDist,
},
} = snapBoundInfo;
const rad180 = rad % 180;
const isHorizontalLine = rad180 < 3 || rad180 > 177;
const isVerticalLine = rad180 > 87 && rad180 < 93;
if (horizontalDist < verticalDist) {
if (
isVerticalBound ||
(isVerticalSnap &&
!isVerticalLine &&
(!keepRatio || !isHorizontalLine))
) {
return "vertical";
}
}
if (
isHorizontalBound ||
(isHorizontalSnap &&
!isHorizontalLine &&
(!keepRatio || !isVerticalLine))
) {
return "horizontal";
}
return "";
}
function getSnapBoundInfo(
moveable: MoveableManagerInterface<SnappableProps, SnappableState>,
poses: number[][],
directions: number[][][],
keepRatio: boolean,
isRequest: boolean,
datas: any
) {
return directions.map(([startDirection, endDirection]) => {
const otherStartPos = getPosByDirection(poses, startDirection);
const otherEndPos = getPosByDirection(poses, endDirection);
const snapBoundInfo = keepRatio
? checkSnapBoundsKeepRatio(
moveable,
otherStartPos,
otherEndPos,
isRequest
)
: checkMoveableSnapBounds(moveable, isRequest, [otherEndPos]);
const {
horizontal: {
// dist: otherHorizontalDist,
offset: otherHorizontalOffset,
isBound: isOtherHorizontalBound,
isSnap: isOtherHorizontalSnap,
},
vertical: {
// dist: otherVerticalDist,
offset: otherVerticalOffset,
isBound: isOtherVerticalBound,
isSnap: isOtherVerticalSnap,
},
} = snapBoundInfo;
const multiple = minus(endDirection, startDirection);
if (!otherVerticalOffset && !otherHorizontalOffset) {
return {
isBound: isOtherVerticalBound || isOtherHorizontalBound,
isSnap: isOtherVerticalSnap || isOtherHorizontalSnap,
sign: multiple,
offset: [0, 0],
};
}
const snapLine = checkSnapRightLine(
otherStartPos,
otherEndPos,
snapBoundInfo,
keepRatio
);
if (!snapLine) {
return {
sign: multiple,
isBound: false,
isSnap: false,
offset: [0, 0],
};
}
const isVertical = snapLine === "vertical";
const sizeOffset = solveNextOffset(
otherStartPos,
otherEndPos,
-(isVertical ? otherVerticalOffset : otherHorizontalOffset),
isVertical,
datas,
).offset.map((size, i) => size * (multiple[i] ? 2 / multiple[i] : 0));
return {
sign: multiple,
isBound: isVertical ? isOtherVerticalBound : isOtherHorizontalBound,
isSnap: isVertical ? isOtherVerticalSnap : isOtherHorizontalSnap,
offset: sizeOffset,
};
});
}
export function getCheckSnapDirections(
direction: number[],
keepRatio: boolean
) {
const directions: number[][][] = [];
const fixedDirection = [-direction[0], -direction[1]];
if (direction[0] && direction[1]) {
directions.push(
[fixedDirection, [direction[0], -direction[1]]],
[fixedDirection, [-direction[0], direction[1]]]
);
if (keepRatio) {
// pass two direction condition
directions.push([fixedDirection, direction]);
}
} else if (direction[0]) {
// vertcal
if (keepRatio) {
directions.push(
[fixedDirection, [fixedDirection[0], -1]],
[fixedDirection, [fixedDirection[0], 1]],
[fixedDirection, [direction[0], -1]],
[fixedDirection, direction],
[fixedDirection, [direction[0], 1]]
);
} else {
directions.push(
[
[fixedDirection[0], -1],
[direction[0], -1],
],
[
[fixedDirection[0], 0],
[direction[0], 0],
],
[
[fixedDirection[0], 1],
[direction[0], 1],
]
);
}
} else if (direction[1]) {
// horizontal
if (keepRatio) {
directions.push(
[fixedDirection, [-1, fixedDirection[1]]],
[fixedDirection, [1, fixedDirection[1]]],
[fixedDirection, [-1, direction[1]]],
[fixedDirection, [1, direction[1]]],
[fixedDirection, direction]
);
} else {
directions.push(
[
[-1, fixedDirection[1]],
[-1, direction[1]],
],
[
[0, fixedDirection[1]],
[0, direction[1]],
],
[
[1, fixedDirection[1]],
[1, direction[1]],
]
);
}
} else {
// [0, 0] to all direction
directions.push(
[fixedDirection, [1, 0]],
[fixedDirection, [-1, 0]],
[fixedDirection, [0, -1]],
[fixedDirection, [0, 1]],
[
[1, 0],
[1, -1],
],
[
[1, 0],
[1, 1],
],
[
[0, 1],
[1, 1],
],
[
[0, 1],
[-1, 1],
],
[
[-1, 0],
[-1, -1],
],
[
[-1, 0],
[-1, 1],
],
[
[0, -1],
[1, -1],
],
[
[0, -1],
[-1, -1],
]
);
}
return directions;
}
export function getSizeOffsetInfo(
moveable: MoveableManagerInterface<SnappableProps, SnappableState>,
poses: number[][],
direction: number[],
keepRatio: boolean,
isRequest: boolean,
datas: any
) {
const directions = getCheckSnapDirections(direction, keepRatio);
const lines = getCheckInnerBoundLines(poses, direction, keepRatio);
const offsets = [
...getSnapBoundInfo(
moveable,
poses,
directions,
keepRatio,
isRequest,
datas
),
...getInnerBoundInfo(
moveable,
lines,
getPosByDirection(poses, [0, 0]),
datas
),
];
const widthOffsetInfo = getNearOffsetInfo(offsets, 0);
const heightOffsetInfo = getNearOffsetInfo(offsets, 1);
return {
width: {
isBound: widthOffsetInfo.isBound,
offset: widthOffsetInfo.offset[0],
},
height: {
isBound: heightOffsetInfo.isBound,
offset: heightOffsetInfo.offset[1],
},
};
}
export function recheckSizeByTwoDirection(
moveable: MoveableManagerInterface<SnappableProps, SnappableState>,
poses: number[][],
width: number,
height: number,
maxWidth: number,
maxHeight: number,
direction: number[],
isRequest: boolean,
datas: any
) {
const snapPos = getPosByDirection(poses, direction);
const {
horizontal: { offset: horizontalOffset },
vertical: { offset: verticalOffset },
} = checkMoveableSnapBounds(moveable, isRequest, [snapPos]);
if (verticalOffset || horizontalOffset) {
const [nextWidthOffset, nextHeightOffset] = getDragDist({
datas,
distX: -verticalOffset,
distY: -horizontalOffset,
});
const nextWidth = Math.min(
maxWidth || Infinity,
width + direction[0] * nextWidthOffset
);
const nextHeight = Math.min(
maxHeight || Infinity,
height + direction[1] * nextHeightOffset
);
return [nextWidth - width, nextHeight - height];
}
return [0, 0];
}
export function checkSizeDist(
moveable: MoveableManagerInterface<any, any>,
getNextPoses: (widthOffset: number, heightOffset: number) => number[][],
width: number,
height: number,
direction: number[],
fixedPosition: number[],
isRequest: boolean,
datas: any
) {
const poses = getAbsolutePosesByState(moveable.state);
const keepRatio = moveable.props.keepRatio;
let widthOffset = 0;
let heightOffset = 0;
for (let i = 0; i < 2; ++i) {
const nextPoses = getNextPoses(widthOffset, heightOffset);
const {
width: widthOffsetInfo,
height: heightOffsetInfo,
} = getSizeOffsetInfo(
moveable,
nextPoses,
direction,
keepRatio,
isRequest,
datas
);
const isWidthBound = widthOffsetInfo.isBound;
const isHeightBound = heightOffsetInfo.isBound;
let nextWidthOffset = widthOffsetInfo.offset;
let nextHeightOffset = heightOffsetInfo.offset;
if (i === 1) {
if (!isWidthBound) {
nextWidthOffset = 0;
}
if (!isHeightBound) {
nextHeightOffset = 0;
}
}
if (i === 0 && isRequest && !isWidthBound && !isHeightBound) {
return [0, 0];
}
if (keepRatio) {
const widthDist =
Math.abs(nextWidthOffset) * (width ? 1 / width : 1);
const heightDist =
Math.abs(nextHeightOffset) * (height ? 1 / height : 1);
const isGetWidthOffset =
isWidthBound && isHeightBound
? widthDist < heightDist
: isHeightBound ||
(!isWidthBound && widthDist < heightDist);
if (isGetWidthOffset) {
// width : height = ? : heightOffset
nextWidthOffset = (width * nextHeightOffset) / height;
} else {
// width : height = widthOffset : ?
nextHeightOffset = (height * nextWidthOffset) / width;
}
}
widthOffset += nextWidthOffset;
heightOffset += nextHeightOffset;
}
if (direction[0] && direction[1]) {
const { maxWidth, maxHeight } = checkMaxBounds(
moveable,
poses,
direction,
fixedPosition,
datas
);
const [nextWidthOffset, nextHeightOffset] = recheckSizeByTwoDirection(
moveable,
getNextPoses(widthOffset, heightOffset).map(pos => pos.map(p => throttle(p, FLOAT_POINT_NUM))),
width + widthOffset,
height + heightOffset,
maxWidth,
maxHeight,
direction,
isRequest,
datas
);
widthOffset += nextWidthOffset;
heightOffset += nextHeightOffset;
}
return [widthOffset, heightOffset];
}
export function checkSnapRotate(
moveable: MoveableManagerInterface<SnappableProps & RotatableProps, any>,
rect: RectInfo,
origin: number[],
rotation: number
) {
if (!hasGuidelines(moveable, "rotatable")) {
return rotation;
}
const { pos1, pos2, pos3, pos4 } = rect;
const rad = (rotation * Math.PI) / 180;
const prevPoses = [pos1, pos2, pos3, pos4].map((pos) => minus(pos, origin));
const nextPoses = prevPoses.map((pos) => rotate(pos, rad));
const result = [
...checkRotateBounds(moveable, prevPoses, nextPoses, origin, rotation),
...checkRotateInnerBounds(
moveable,
prevPoses,
nextPoses,
origin,
rotation
),
];
result.sort((a, b) => Math.abs(a - rotation) - Math.abs(b - rotation));
if (result.length) {
return result[0];
} else {
return rotation;
}
}
export function checkSnapResize(
moveable: MoveableManagerInterface<{}, {}>,
width: number,
height: number,
direction: number[],
fixedPosition: number[],
isRequest: boolean,
datas: any
) {
if (!hasGuidelines(moveable, "resizable")) {
return [0, 0];
}
const { allMatrix, is3d } = moveable.state;
return checkSizeDist(
moveable,
(widthOffset: number, heightOffset: number) => {
return getNextFixedPoses(
allMatrix,
width + widthOffset,
height + heightOffset,
fixedPosition,
direction,
is3d
);
},
width,
height,
direction,
fixedPosition,
isRequest,
datas
);
}
export function checkSnapScale(
moveable: MoveableManagerInterface<ScalableProps, any>,
scale: number[],
direction: number[],
isRequest: boolean,
datas: any
) {
const { width, height, fixedPosition } = datas;
if (!hasGuidelines(moveable, "scalable")) {
return [0, 0];
}
const is3d = datas.is3d;
const sizeDist = checkSizeDist(
moveable,
(widthOffset: number, heightOffset: number) => {
return getNextFixedPoses(
scaleMatrix(
datas,
plus(scale, [widthOffset / width, heightOffset / height]),
),
width,
height,
fixedPosition,
direction,
is3d
);
},
width,
height,
direction,
fixedPosition,
isRequest,
datas
);
return [sizeDist[0] / width, sizeDist[1] / height];
}
export function solveEquation(
pos1: number[],
pos2: number[],
snapOffset: number,
isVertical: boolean
) {
let dx = pos2[0] - pos1[0];
let dy = pos2[1] - pos1[1];
if (Math.abs(dx) < TINY_NUM) {
dx = 0;
}
if (Math.abs(dy) < TINY_NUM) {
dy = 0;
}
if (!dx) {
// y = 0 * x + b
// only horizontal
if (!isVertical) {
return [0, snapOffset];
}
return [0, 0];
}
if (!dy) {
// only vertical
if (isVertical) {
return [snapOffset, 0];
}
return [0, 0];
}
// y = ax + b
const a = dy / dx;
const b = pos1[1] - a * pos1[0];
if (isVertical) {
// y = a * x + b
const y = a * (pos2[0] + snapOffset) + b;
return [snapOffset, y - pos2[1]];
} else {
// x = (y - b) / a
const x = (pos2[1] + snapOffset - b) / a;
return [x - pos2[0], snapOffset];
}
}
export function startCheckSnapDrag(
moveable: MoveableManagerInterface<any, any>,
datas: any
) {
datas.absolutePoses = getAbsolutePosesByState(moveable.state);
}
export function checkThrottleDragRotate(
throttleDragRotate: number,
[distX, distY]: number[],
[isVerticalBound, isHorizontalBound]: boolean[],
[isVerticalSnap, isHorizontalSnap]: boolean[],
[verticalOffset, horizontalOffset]: number[]
) {
let offsetX = -verticalOffset;
let offsetY = -horizontalOffset;
if (throttleDragRotate && distX && distY) {
offsetX = 0;
offsetY = 0;
const adjustPoses: number[][] = [];
if (isVerticalBound && isHorizontalBound) {
adjustPoses.push([0, horizontalOffset], [verticalOffset, 0]);
} else if (isVerticalBound) {
adjustPoses.push([verticalOffset, 0]);
} else if (isHorizontalBound) {
adjustPoses.push([0, horizontalOffset]);
} else if (isVerticalSnap && isHorizontalSnap) {
adjustPoses.push([0, horizontalOffset], [verticalOffset, 0]);
} else if (isVerticalSnap) {
adjustPoses.push([verticalOffset, 0]);
} else if (isHorizontalSnap) {
adjustPoses.push([0, horizontalOffset]);
}
if (adjustPoses.length) {
adjustPoses.sort((a, b) => {
return (
getDistSize(minus([distX, distY], a)) -
getDistSize(minus([distX, distY], b))
);
});
const adjustPos = adjustPoses[0];
if (adjustPos[0] && Math.abs(distX) > TINY_NUM) {
offsetX = -adjustPos[0];
offsetY =
(distY * Math.abs(distX + offsetX)) / Math.abs(distX) -
distY;
} else if (adjustPos[1] && Math.abs(distY) > TINY_NUM) {
const prevDistY = distY;
offsetY = -adjustPos[1];
offsetX =
(distX * Math.abs(distY + offsetY)) / Math.abs(prevDistY) -
distX;
}
if (throttleDragRotate && isHorizontalBound && isVerticalBound) {
if (
Math.abs(offsetX) > TINY_NUM &&
Math.abs(offsetX) < Math.abs(verticalOffset)
) {
const scale = Math.abs(verticalOffset) / Math.abs(offsetX);
offsetX *= scale;
offsetY *= scale;
} else if (
Math.abs(offsetY) > TINY_NUM &&
Math.abs(offsetY) < Math.abs(horizontalOffset)
) {
const scale =
Math.abs(horizontalOffset) / Math.abs(offsetY);
offsetX *= scale;
offsetY *= scale;
} else {
offsetX = maxOffset(-verticalOffset, offsetX);
offsetY = maxOffset(-horizontalOffset, offsetY);
}
}
}
} else {
offsetX = distX || isVerticalBound ? -verticalOffset : 0;
offsetY = distY || isHorizontalBound ? -horizontalOffset : 0;
}
return [offsetX, offsetY];
}
export function checkSnapDrag(
moveable: MoveableManagerInterface<SnappableProps & DraggableProps, any>,
distX: number,
distY: number,
throttleDragRotate: number,
isRequest: boolean,
datas: any
) {
if (!hasGuidelines(moveable, "draggable")) {
return [
{
isSnap: false,
isBound: false,
offset: 0,
},
{
isSnap: false,
isBound: false,
offset: 0,
},
];
}
const poses = getAbsolutePoses(datas.absolutePoses, [distX, distY]);
const { left, right, top, bottom } = getRect(poses);
const snapCenter = moveable.props.snapCenter;
const snapPoses = [
[left, top],
[right, top],
[left, bottom],
[right, bottom],
];
if (snapCenter) {
snapPoses.push([(left + right) / 2, (top + bottom) / 2]);
}
const {
vertical: verticalSnapBoundInfo,
horizontal: horizontalSnapBoundInfo,
} = checkMoveableSnapBounds(moveable, isRequest, snapPoses, poses);
const {
vertical: verticalInnerBoundInfo,
horizontal: horizontalInnerBoundInfo,
} = getInnerBoundDragInfo(moveable, poses, datas);
const isVerticalSnap = verticalSnapBoundInfo.isSnap;
const isHorizontalSnap = horizontalSnapBoundInfo.isSnap;
const isVerticalBound =
verticalSnapBoundInfo.isBound || verticalInnerBoundInfo.isBound;
const isHorizontalBound =
horizontalSnapBoundInfo.isBound || horizontalInnerBoundInfo.isBound;
const verticalOffset = maxOffset(
verticalSnapBoundInfo.offset,
verticalInnerBoundInfo.offset
);
const horizontalOffset = maxOffset(
horizontalSnapBoundInfo.offset,
horizontalInnerBoundInfo.offset
);
const [offsetX, offsetY] = checkThrottleDragRotate(
throttleDragRotate,
[distX, distY],
[isVerticalBound, isHorizontalBound],
[isVerticalSnap, isHorizontalSnap],
[verticalOffset, horizontalOffset]
);
return [
{
isBound: isVerticalBound,
isSnap: isVerticalSnap,
offset: offsetX,
},
{
isBound: isHorizontalBound,
isSnap: isHorizontalSnap,
offset: offsetY,
},
];
}
function getSnapGuidelines(posInfos: SnapPosInfo[]) {
const guidelines: SnapGuideline[] = [];
posInfos.forEach((posInfo) => {
posInfo.guidelineInfos.forEach(({ guideline }) => {
if (guidelines.indexOf(guideline) > -1) {
return;
}
guidelines.push(guideline);
});
});
return guidelines;
}
function getGapGuidelinesToStart(
guidelines: SnapGuideline[],
index: number,
targetPos: number[],
targetSizes: number[],
guidelinePos: number[],
gap: number,
otherPos: number
): GapGuideline[] {
const absGap = Math.abs(gap);
let start = guidelinePos[index] + (gap > 0 ? targetSizes[0] : 0);
return guidelines
.filter(({ pos: gapPos }) => gapPos[index] <= targetPos[index])
.sort(({ pos: aPos }, { pos: bPos }) => bPos[index] - aPos[index])
.filter(({ pos: gapPos, sizes: gapSizes }) => {
const nextPos = gapPos[index];
if (
throttle(nextPos + gapSizes![index], FLOAT_POINT_NUM) ===
throttle(start - absGap, FLOAT_POINT_NUM)
) {
start = nextPos;
return true;
}
return false;
})
.map((gapGuideline) => {
const renderPos =
-targetPos[index] +
gapGuideline.pos[index] +
gapGuideline.sizes![index];
return {
...gapGuideline,
gap,
renderPos: index
? [otherPos, renderPos]
: [renderPos, otherPos],
};
});
}
function getGapGuidelinesToEnd(
guidelines: SnapGuideline[],
index: number,
targetPos: number[],
targetSizes: number[],
guidelinePos: number[],
gap: number,
otherPos: number
): GapGuideline[] {
const absGap = Math.abs(gap);
let start = guidelinePos[index] + (gap < 0 ? targetSizes[index] : 0);
return guidelines
.filter(({ pos: gapPos }) => gapPos[index] > targetPos[index])
.sort(({ pos: aPos }, { pos: bPos }) => aPos[index] - bPos[index])
.filter(({ pos: gapPos, sizes: gapSizes }) => {
const nextPos = gapPos[index];
if (
throttle(nextPos, FLOAT_POINT_NUM) === throttle(start + absGap, FLOAT_POINT_NUM)
) {
start = nextPos + gapSizes![index];
return true;
}
return false;
})
.map((gapGuideline) => {
const renderPos =
-targetPos[index] + gapGuideline.pos[index] - absGap;
return {
...gapGuideline,
gap,
renderPos: index
? [otherPos, renderPos]
: [renderPos, otherPos],
};
});
}
function getGapGuidelines(
guidelines: SnapGuideline[],
type: "vertical" | "horizontal",
targetPos: number[],
targetSizes: number[]
): GapGuideline[] {
const elementGuidelines = guidelines.filter(
({ element, gap, type: guidelineType }) =>
element && gap && guidelineType === type
);
const [index, otherIndex] = type === "vertical" ? [0, 1] : [1, 0];
return flat(
elementGuidelines.map((guideline) => {
const pos = guideline.pos;
const gap = guideline.gap!;
const gapGuidelines = guideline.gapGuidelines!;
const sizes = guideline.sizes!;
let offset = minOffset(
pos[otherIndex] + sizes[otherIndex] - targetPos[otherIndex],
pos[otherIndex] -
targetPos[otherIndex] -
targetSizes[otherIndex]
);
const minSize = Math.min(
sizes[otherIndex],
targetSizes[otherIndex]
);
if (offset > 0 && offset > minSize) {
offset = (offset - minSize / 2) * 2;
} else if (offset < 0 && offset < -minSize) {
offset = (offset + minSize / 2) * 2;
}
if (offset === 0) {
return [];
}
const otherPos =
(offset > 0 ? 0 : targetSizes[otherIndex]) + offset / 2;
return [
...getGapGuidelinesToStart(
gapGuidelines,
index,
targetPos,
targetSizes,
pos,
gap,
otherPos
),
...getGapGuidelinesToEnd(
gapGuidelines,
index,
targetPos,
targetSizes,
pos,
gap,
otherPos
),
];
})
);
}
function addBoundGuidelines(
moveable: MoveableManagerInterface<SnappableProps, SnappableState>,
verticalPoses: number[],
horizontalPoses: number[],
verticalSnapPoses: SnappableRenderType[],
horizontalSnapPoses: SnappableRenderType[],
externalBounds?: BoundType | false | null
) {
const {
vertical: verticalBoundInfos,
horizontal: horizontalBoundInfos,
} = checkBoundPoses(
getBounds(moveable, externalBounds),
verticalPoses,
horizontalPoses
);
verticalBoundInfos.forEach((info) => {
if (info.isBound) {
verticalSnapPoses.push({
type: "bounds",
pos: info.pos,
});
}
});
horizontalBoundInfos.forEach((info) => {
if (info.isBound) {
horizontalSnapPoses.push({
type: "bounds",
pos: info.pos,
});
}
});
const {
vertical: verticalInnerBoundPoses,
horizontal: horizontalInnerBoundPoses,
} = checkInnerBoundPoses(moveable);
verticalInnerBoundPoses.forEach((innerPos) => {
if (
findIndex(
verticalSnapPoses,
({ type, pos }) => type === "bounds" && pos === innerPos
) >= 0
) {
return;
}
verticalSnapPoses.push({
type: "bounds",
pos: innerPos,
});
});
horizontalInnerBoundPoses.forEach((innerPos) => {
if (
findIndex(
horizontalSnapPoses,
({ type, pos }) => type === "bounds" && pos === innerPos
) >= 0
) {
return;
}
horizontalSnapPoses.push({
type: "bounds",
pos: innerPos,
});
});
}
/**
* @namespace Moveable.Snappable
* @description Whether or not target can be snapped to the guideline. (default: false)
* @sort 2
*/
export default {
name: "snappable",
props: {
snappable: [Boolean, Array],
snapContainer: Object,
snapCenter: Boolean,
snapHorizontal: Boolean,
snapVertical: Boolean,
snapElement: Boolean,
snapGap: Boolean,
snapGridWidth: Number,
snapGridHeight: Number,
isDisplaySnapDigit: Boolean,
isDisplayInnerSnapDigit: Boolean,
snapDigit: Number,
snapThreshold: Number,
horizontalGuidelines: Array,
verticalGuidelines: Array,
elementGuidelines: Array,
bounds: Object,
innerBounds: Object,
snapDistFormat: Function,
} as const,
events: {
onSnap: "snap",
} as const,
css: [
`:host {
--bounds-color: #d66;
}
.guideline {
pointer-events: none;
z-index: 2;
}
.guideline.bounds {
background: #d66;
background: var(--bounds-color);
}
.guideline-group {
position: absolute;
top: 0;
left: 0;
}
.guideline-group .size-value {
position: absolute;
color: #f55;
font-size: 12px;
font-weight: bold;
}
.guideline-group.horizontal .size-value {
transform-origin: 50% 100%;
transform: translateX(-50%);
left: 50%;
bottom: 5px;
}
.guideline-group.vertical .size-value {
transform-origin: 0% 50%;
top: 50%;
transform: translateY(-50%);
left: 5px;
}
.guideline.gap {
background: #f55;
}
.size-value.gap {
color: #f55;
}
`,
],
render(
moveable: MoveableManagerInterface<SnappableProps, SnappableState>,
React: Renderer
): any[] {
const state = moveable.state;
const {
top: targetTop,
left: targetLeft,
pos1,
pos2,
pos3,
pos4,
snapRenderInfo,
targetClientRect,
containerClientRect,
is3d,
rootMatrix,
} = state;
if (!snapRenderInfo || !hasGuidelines(moveable, "")) {
return [];
}
state.staticGuidelines = getElementGuidelines(moveable, false, state.staticGuidelines);
state.guidelines = getTotalGuidelines(moveable);
const n = is3d ? 4 : 3;
const minLeft = Math.min(pos1[0], pos2[0], pos3[0], pos4[0]);
const minTop = Math.min(pos1[1], pos2[1], pos3[1], pos4[1]);
const containerPos = calculateContainerPos(
rootMatrix,
containerClientRect,
n
);
const [clientLeft, clientTop] = calculateInversePosition(
rootMatrix,
[
targetClientRect.left - containerPos[0],
targetClientRect.top - containerPos[1],
],
n
);
const {
snapThreshold = 5,
snapDigit = 0,
snapDistFormat = (v: number) => v,
} = moveable.props;
const externalPoses = snapRenderInfo.externalPoses || [];
const poses = getAbsolutePosesByState(moveable.state);
const verticalSnapPoses: SnappableRenderType[] = [];
const horizontalSnapPoses: SnappableRenderType[] = [];
const verticalGuidelines: SnapGuideline[] = [];
const horizontalGuidelines: SnapGuideline[] = [];
const snapInfos: Array<{
vertical: SnapInfo;
horizontal: SnapInfo;
}> = [];
const { width, height, top, left, bottom, right } = getRect(poses);
const hasExternalPoses = externalPoses.length > 0;
const externalRect = hasExternalPoses
? getRect(externalPoses)
: ({} as ReturnType<typeof getRect>);
if (!snapRenderInfo.request) {
if (snapRenderInfo.direction) {
snapInfos.push(
getSnapInfosByDirection(
moveable,
poses,
snapRenderInfo.direction
)
);
}
if (snapRenderInfo.snap) {
const rect = getRect(poses);
if (snapRenderInfo.center) {
(rect as any).middle = (rect.top + rect.bottom) / 2;
(rect as any).center = (rect.left + rect.right) / 2;
}
snapInfos.push(checkSnaps(moveable, rect, true, 1));
}
if (hasExternalPoses) {
if (snapRenderInfo.center) {
(externalRect as any).middle =
(externalRect.top + externalRect.bottom) / 2;
(externalRect as any).center =
(externalRect.left + externalRect.right) / 2;
}
snapInfos.push(checkSnaps(moveable, externalRect, true, 1));
}
snapInfos.forEach((snapInfo) => {
const {
vertical: { posInfos: verticalPosInfos },
horizontal: { posInfos: horizontalPosInfos },
} = snapInfo;
verticalSnapPoses.push(
...verticalPosInfos.filter(({ guidelineInfos }) => {
return guidelineInfos.some(({ guideline }) => !guideline.hide);
}).map(
(posInfo) => ({
type: "snap",
pos: posInfo.pos,
} as const)
)
);
horizontalSnapPoses.push(
...horizontalPosInfos.filter(({ guidelineInfos }) => {
return guidelineInfos.some(({ guideline }) => !guideline.hide);
}).map(
(posInfo) => ({
type: "snap",
pos: posInfo.pos,
} as const)
)
);
verticalGuidelines.push(...getSnapGuidelines(verticalPosInfos));
horizontalGuidelines.push(...getSnapGuidelines(horizontalPosInfos));
});
}
addBoundGuidelines(
moveable,
[left, right],
[top, bottom],
verticalSnapPoses,
horizontalSnapPoses
);
if (hasExternalPoses) {
addBoundGuidelines(
moveable,
[externalRect.left, externalRect.right],
[externalRect.top, externalRect.bottom],
verticalSnapPoses,
horizontalSnapPoses,
snapRenderInfo.externalBounds
);
}
const gapHorizontalGuidelines = getGapGuidelines(
verticalGuidelines,
"vertical",
[targetLeft, targetTop],
[width, height]
);
const gapVerticalGuidelines = getGapGuidelines(
horizontalGuidelines,
"horizontal",
[targetLeft, targetTop],
[width, height]
);
const allGuidelines = [...verticalGuidelines, ...horizontalGuidelines];
triggerEvent(
moveable,
"onSnap",
{
guidelines: allGuidelines.filter(({ element }) => !element),
elements: groupBy(
allGuidelines.filter(({ element }) => element),
({ element }) => element
),
gaps: [...gapVerticalGuidelines, ...gapHorizontalGuidelines],
},
true
);
const {
guidelines: nextHorizontalGuidelines,
groups: elementHorizontalGroups,
gapGuidelines: innerGapHorizontalGuidelines,
} = filterElementInnerGuidelines(
moveable,
horizontalGuidelines,
0,
[targetLeft, targetTop],
[clientLeft, clientTop],
[width, height],
);
const {
guidelines: nextVerticalGuidelines,
groups: elementVerticalGroups,
gapGuidelines: innerGapVerticalGuidelines,
} = filterElementInnerGuidelines(
moveable,
verticalGuidelines,
1,
[targetLeft, targetTop],
[clientLeft, clientTop],
[width, height],
);
return [
...renderGapGuidelines(
moveable,
"vertical",
[...gapVerticalGuidelines, ...innerGapVerticalGuidelines],
snapDistFormat,
React
),
...renderGapGuidelines(
moveable,
"horizontal",
[...gapHorizontalGuidelines, ...innerGapHorizontalGuidelines],
snapDistFormat,
React
),
...renderElementGroups(
moveable,
"horizontal",
elementHorizontalGroups,
minLeft,
clientLeft,
width,
targetTop,
snapThreshold,
snapDigit,
0,
snapDistFormat,
React
),
...renderElementGroups(
moveable,
"vertical",
elementVerticalGroups,
minTop,
clientTop,
height,
targetLeft,
snapThreshold,
snapDigit,
1,
snapDistFormat,
React
),
...renderGuidelines(
moveable,
"horizontal",
nextHorizontalGuidelines,
[targetLeft, targetTop],
React
),
...renderGuidelines(
moveable,
"vertical",
nextVerticalGuidelines,
[targetLeft, targetTop],
React
),
...renderSnapPoses(
moveable,
"horizontal",
horizontalSnapPoses,
minLeft,
targetTop,
width,
0,
React
),
...renderSnapPoses(
moveable,
"vertical",
verticalSnapPoses,
minTop,
targetLeft,
height,
1,
React
),
];
},
dragStart(
moveable: MoveableManagerInterface<SnappableProps, SnappableState>,
e: any
) {
moveable.state.snapRenderInfo = {
request: e.isRequest,
snap: true,
center: true,
};
snapStart(moveable);
},
drag(
moveable: MoveableManagerInterface<SnappableProps, SnappableState>
) {
const state = moveable.state;
state.staticGuidelines = getElementGuidelines(moveable, false, state.staticGuidelines);
state.guidelines = getTotalGuidelines(moveable);
},
pinchStart(
moveable: MoveableManagerInterface<SnappableProps, SnappableState>
) {
this.unset(moveable);
},
dragEnd(
moveable: MoveableManagerInterface<SnappableProps, SnappableState>
) {
this.unset(moveable);
},
dragControlCondition(moveable: MoveableManagerInterface, e: any) {
if (directionCondition(moveable, e) || rotatableDragControlCondtion(moveable, e)) {
return true;
}
if (!e.isRequest && e.inputEvent) {
return hasClass(e.inputEvent.target, prefix("snap-control"));
}
},
dragControlStart(
moveable: MoveableManagerInterface<SnappableProps, SnappableState>
) {
moveable.state.snapRenderInfo = null;
snapStart(moveable);
},
dragControl(
moveable: MoveableManagerInterface<SnappableProps, SnappableState>
) {
this.drag(moveable);
},
dragControlEnd(
moveable: MoveableManagerInterface<SnappableProps, SnappableState>
) {
this.unset(moveable);
},
dragGroupStart(moveable: any, e: any) {
this.dragStart(moveable, e);
},
dragGroup(
moveable: MoveableGroupInterface<SnappableProps, SnappableState>
) {
this.drag(moveable);
},
dragGroupEnd(
moveable: MoveableGroupInterface<SnappableProps, SnappableState>
) {
this.unset(moveable);
},
dragGroupControlStart(
moveable: MoveableGroupInterface<SnappableProps, SnappableState>
) {
moveable.state.snapRenderInfo = null;
snapStart(moveable);
},
dragGroupControl(
moveable: MoveableManagerInterface<SnappableProps, SnappableState>
) {
this.drag(moveable);
},
dragGroupControlEnd(
moveable: MoveableGroupInterface<SnappableProps, SnappableState>
) {
this.unset(moveable);
},
unset(moveable: any) {
const state = moveable.state;
state.enableSnap = false;
state.staticGuidelines = [];
state.guidelines = [];
state.snapRenderInfo = null;
},
};
/**
* Whether or not target can be snapped to the guideline. (default: false)
* @name Moveable.Snappable#snappable
* @example
* import Moveable from "moveable";
*
* const moveable = new Moveable(document.body);
*
* moveable.snappable = true;
*/
/**
* A snap container that is the basis for snap, bounds, and innerBounds. (default: null = container)
* @name Moveable.Snappable#snapContainer
* @example
* import Moveable from "moveable";
*
* const moveable = new Moveable(document.querySelector(".container"));
*
* moveable.snapContainer = document.body;
*/
/**
* When you drag, make the snap in the center of the target. (default: false)
* @name Moveable.Snappable#snapCenter
* @example
* import Moveable from "moveable";
*
* const moveable = new Moveable(document.body, {
* snappable: true,
* });
*
* moveable.snapCenter = true;
*/
/**
* When you drag, make the snap in the vertical guidelines. (default: true)
* @name Moveable.Snappable#snapVertical
* @example
* import Moveable from "moveable";
*
* const moveable = new Moveable(document.body, {
* snappable: true,
* snapVertical: true,
* snapHorizontal: true,
* snapElement: true,
* });
*
* moveable.snapVertical = false;
*/
/**
* When you drag, make the snap in the horizontal guidelines. (default: true)
* @name Moveable.Snappable#snapHorizontal
* @example
* import Moveable from "moveable";
*
* const moveable = new Moveable(document.body, {
* snappable: true,
* snapVertical: true,
* snapHorizontal: true,
* snapElement: true,
* });
*
* moveable.snapHorizontal = false;
*/
/**
* When you drag, make the gap snap in the element guidelines. (default: true)
* @name Moveable.Snappable#snapGap
* @example
* import Moveable from "moveable";
*
* const moveable = new Moveable(document.body, {
* snappable: true,
* snapVertical: true,
* snapHorizontal: true,
* snapElement: true,
* snapGap: true,
* });
*
* moveable.snapGap = false;
*/
/**
* When you drag, make the snap in the element guidelines. (default: true)
* @name Moveable.Snappable#snapElement
* @example
* import Moveable from "moveable";
*
* const moveable = new Moveable(document.body, {
* snappable: true,
* snapVertical: true,
* snapHorizontal: true,
* snapElement: true,
* });
*
* moveable.snapElement = false;
*/
/**
* Distance value that can snap to guidelines. (default: 5)
* @name Moveable.Snappable#snapThreshold
* @example
* import Moveable from "moveable";
*
* const moveable = new Moveable(document.body);
*
* moveable.snapThreshold = 5;
*/
/**
* Add guidelines in the horizontal direction. (default: [])
* @name Moveable.Snappable#horizontalGuidelines
* @example
* import Moveable from "moveable";
*
* const moveable = new Moveable(document.body);
*
* moveable.horizontalGuidelines = [100, 200, 500];
*/
/**
* Add guidelines in the vertical direction. (default: [])
* @name Moveable.Snappable#verticalGuidelines
* @example
* import Moveable from "moveable";
*
* const moveable = new Moveable(document.body);
*
* moveable.verticalGuidelines = [100, 200, 500];
*/
/**
* Add guidelines for the element. (default: [])
* @name Moveable.Snappable#elementGuidelines
* @example
* import Moveable from "moveable";
*
* const moveable = new Moveable(document.body);
*
* moveable.elementGuidelines = [
* document.querySelector(".element"),
* ];
*/
/**
* You can set up boundaries. (default: null)
* @name Moveable.Snappable#bounds
* @example
* import Moveable from "moveable";
*
* const moveable = new Moveable(document.body);
*
* moveable.bounds = { left: 0, right: 1000, top: 0, bottom: 1000};
*/
/**
* You can set up inner boundaries. (default: null)
* @name Moveable.Snappable#innerBounds
* @example
* import Moveable from "moveable";
*
* const moveable = new Moveable(document.body);
*
* moveable.innerBounds = { left: 500, top: 500, width: 100, height: 100};
*/
/**
* snap distance digits (default: 0)
* @name Moveable.Snappable#snapDigit
* @example
* import Moveable from "moveable";
*
* const moveable = new Moveable(document.body);
*
* moveable.snapDigit = 0
*/
/**
* If width size is greater than 0, you can vertical snap to the grid. (default: 0)
* @name Moveable.Snappable#snapGridWidth
* @example
* import Moveable from "moveable";
*
* const moveable = new Moveable(document.body);
*
* moveable.snapGridWidth = 5;
*/
/**
* If height size is greater than 0, you can horizontal snap to the grid. (default: 0)
* @name Moveable.Snappable#snapGridHeight
* @example
* import Moveable from "moveable";
*
* const moveable = new Moveable(document.body);
*
* moveable.snapGridHeight = 5;
*/
/**
* Whether to show snap distance (default: true)
* @name Moveable.Snappable#isDisplaySnapDigit
* @example
* import Moveable from "moveable";
*
* const moveable = new Moveable(document.body);
*
* moveable.isDisplaySnapDigit = true;
*/
/**
* Whether to show element inner snap distance (default: false)
* @name Moveable.Snappable#isDisplayInnerSnapDigit
* @example
* import Moveable from "moveable";
*
* const moveable = new Moveable(document.body);
*
* moveable.isDisplayInnerSnapDigit = true;
*/
/**
* You can set the text format of the distance shown in the guidelines. (default: self)
* @name Moveable.Snappable#snapDistFormat
* @example
* import Moveable from "moveable";
*
* const moveable = new Moveable(document.body, {
* snappable: true,
* snapDistFormat: v => v,
* });
* moveable.snapDistFormat = v => `${v}px`;
*/
/**
* When you drag or dragControl, the `snap` event is called.
* @memberof Moveable.Snappable
* @event snap
* @param {Moveable.Snappable.OnSnap} - Parameters for the `snap` event
* @example
* import Moveable from "moveable";
*
* const moveable = new Moveable(document.body, {
* snappable: true
* });
* moveable.on("snap", e => {
* console.log("onSnap", e);
* });
*/ | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/automationAccountOperationsMappers";
import * as Parameters from "../models/parameters";
import { AutomationClientContext } from "../automationClientContext";
/** Class representing a AutomationAccountOperations. */
export class AutomationAccountOperations {
private readonly client: AutomationClientContext;
/**
* Create a AutomationAccountOperations.
* @param {AutomationClientContext} client Reference to the service client.
*/
constructor(client: AutomationClientContext) {
this.client = client;
}
/**
* Update an automation account.
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param parameters Parameters supplied to the update automation account.
* @param [options] The optional parameters
* @returns Promise<Models.AutomationAccountUpdateResponse>
*/
update(resourceGroupName: string, automationAccountName: string, parameters: Models.AutomationAccountUpdateParameters, options?: msRest.RequestOptionsBase): Promise<Models.AutomationAccountUpdateResponse>;
/**
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param parameters Parameters supplied to the update automation account.
* @param callback The callback
*/
update(resourceGroupName: string, automationAccountName: string, parameters: Models.AutomationAccountUpdateParameters, callback: msRest.ServiceCallback<Models.AutomationAccount>): void;
/**
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param parameters Parameters supplied to the update automation account.
* @param options The optional parameters
* @param callback The callback
*/
update(resourceGroupName: string, automationAccountName: string, parameters: Models.AutomationAccountUpdateParameters, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AutomationAccount>): void;
update(resourceGroupName: string, automationAccountName: string, parameters: Models.AutomationAccountUpdateParameters, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AutomationAccount>, callback?: msRest.ServiceCallback<Models.AutomationAccount>): Promise<Models.AutomationAccountUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
automationAccountName,
parameters,
options
},
updateOperationSpec,
callback) as Promise<Models.AutomationAccountUpdateResponse>;
}
/**
* Create or update automation account.
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param parameters Parameters supplied to the create or update automation account.
* @param [options] The optional parameters
* @returns Promise<Models.AutomationAccountCreateOrUpdateResponse>
*/
createOrUpdate(resourceGroupName: string, automationAccountName: string, parameters: Models.AutomationAccountCreateOrUpdateParameters, options?: msRest.RequestOptionsBase): Promise<Models.AutomationAccountCreateOrUpdateResponse>;
/**
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param parameters Parameters supplied to the create or update automation account.
* @param callback The callback
*/
createOrUpdate(resourceGroupName: string, automationAccountName: string, parameters: Models.AutomationAccountCreateOrUpdateParameters, callback: msRest.ServiceCallback<Models.AutomationAccount>): void;
/**
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param parameters Parameters supplied to the create or update automation account.
* @param options The optional parameters
* @param callback The callback
*/
createOrUpdate(resourceGroupName: string, automationAccountName: string, parameters: Models.AutomationAccountCreateOrUpdateParameters, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AutomationAccount>): void;
createOrUpdate(resourceGroupName: string, automationAccountName: string, parameters: Models.AutomationAccountCreateOrUpdateParameters, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AutomationAccount>, callback?: msRest.ServiceCallback<Models.AutomationAccount>): Promise<Models.AutomationAccountCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
automationAccountName,
parameters,
options
},
createOrUpdateOperationSpec,
callback) as Promise<Models.AutomationAccountCreateOrUpdateResponse>;
}
/**
* Delete an automation account.
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(resourceGroupName: string, automationAccountName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, automationAccountName: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param options The optional parameters
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, automationAccountName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, automationAccountName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
automationAccountName,
options
},
deleteMethodOperationSpec,
callback);
}
/**
* Get information about an Automation Account.
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param [options] The optional parameters
* @returns Promise<Models.AutomationAccountGetResponse>
*/
get(resourceGroupName: string, automationAccountName: string, options?: msRest.RequestOptionsBase): Promise<Models.AutomationAccountGetResponse>;
/**
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param callback The callback
*/
get(resourceGroupName: string, automationAccountName: string, callback: msRest.ServiceCallback<Models.AutomationAccount>): void;
/**
* @param resourceGroupName Name of an Azure Resource group.
* @param automationAccountName The name of the automation account.
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, automationAccountName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AutomationAccount>): void;
get(resourceGroupName: string, automationAccountName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AutomationAccount>, callback?: msRest.ServiceCallback<Models.AutomationAccount>): Promise<Models.AutomationAccountGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
automationAccountName,
options
},
getOperationSpec,
callback) as Promise<Models.AutomationAccountGetResponse>;
}
/**
* Retrieve a list of accounts within a given resource group.
* @param resourceGroupName Name of an Azure Resource group.
* @param [options] The optional parameters
* @returns Promise<Models.AutomationAccountListByResourceGroupResponse>
*/
listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.AutomationAccountListByResourceGroupResponse>;
/**
* @param resourceGroupName Name of an Azure Resource group.
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.AutomationAccountListResult>): void;
/**
* @param resourceGroupName Name of an Azure Resource group.
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AutomationAccountListResult>): void;
listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AutomationAccountListResult>, callback?: msRest.ServiceCallback<Models.AutomationAccountListResult>): Promise<Models.AutomationAccountListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
options
},
listByResourceGroupOperationSpec,
callback) as Promise<Models.AutomationAccountListByResourceGroupResponse>;
}
/**
* Retrieve a list of accounts within a given subscription.
* @summary Lists the Automation Accounts within an Azure subscription.
* @param [options] The optional parameters
* @returns Promise<Models.AutomationAccountListResponse>
*/
list(options?: msRest.RequestOptionsBase): Promise<Models.AutomationAccountListResponse>;
/**
* @param callback The callback
*/
list(callback: msRest.ServiceCallback<Models.AutomationAccountListResult>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
list(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AutomationAccountListResult>): void;
list(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AutomationAccountListResult>, callback?: msRest.ServiceCallback<Models.AutomationAccountListResult>): Promise<Models.AutomationAccountListResponse> {
return this.client.sendOperationRequest(
{
options
},
listOperationSpec,
callback) as Promise<Models.AutomationAccountListResponse>;
}
/**
* Retrieve a list of accounts within a given resource group.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.AutomationAccountListByResourceGroupNextResponse>
*/
listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.AutomationAccountListByResourceGroupNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.AutomationAccountListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AutomationAccountListResult>): void;
listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AutomationAccountListResult>, callback?: msRest.ServiceCallback<Models.AutomationAccountListResult>): Promise<Models.AutomationAccountListByResourceGroupNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByResourceGroupNextOperationSpec,
callback) as Promise<Models.AutomationAccountListByResourceGroupNextResponse>;
}
/**
* Retrieve a list of accounts within a given subscription.
* @summary Lists the Automation Accounts within an Azure subscription.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.AutomationAccountListNextResponse>
*/
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.AutomationAccountListNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.AutomationAccountListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AutomationAccountListResult>): void;
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AutomationAccountListResult>, callback?: msRest.ServiceCallback<Models.AutomationAccountListResult>): Promise<Models.AutomationAccountListNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listNextOperationSpec,
callback) as Promise<Models.AutomationAccountListNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const updateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.automationAccountName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.AutomationAccountUpdateParameters,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.AutomationAccount
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const createOrUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.automationAccountName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.AutomationAccountCreateOrUpdateParameters,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.AutomationAccount
},
201: {
bodyMapper: Mappers.AutomationAccount
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const deleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.automationAccountName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.automationAccountName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.AutomationAccount
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listByResourceGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts",
urlParameters: [
Parameters.resourceGroupName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.AutomationAccountListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.Automation/automationAccounts",
urlParameters: [
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.AutomationAccountListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listByResourceGroupNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.AutomationAccountListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.AutomationAccountListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
}; | the_stack |
import * as os from "os"
import { app, BrowserWindow, dialog, Menu } from "electron"
import { createWindow, IDelayedEvent } from "./main"
export const buildDockMenu = (mainWindow, loadInit) => {
const menu = []
menu.push({
label: "New Window",
click() {
createWindow([], process.cwd())
},
})
return Menu.buildFromTemplate(menu)
}
export const buildMenu = (mainWindow, loadInit) => {
const menu = []
// On Windows, both the forward slash `/` and the backward slash `\` are accepted as path delimiters.
// The node APIs only return the backward slash, ie: `C:\\oni\\README.md`, but this causes problems
// for VIM as it sees escape keys.
const executeMenuAction = (browserWindow: BrowserWindow, delayedEvent: IDelayedEvent) => {
if (browserWindow) {
return browserWindow.webContents.send(delayedEvent.evt, ...delayedEvent.cmd)
}
createWindow([], process.cwd(), delayedEvent)
}
const normalizePath = fileName => fileName.split("\\").join("/")
const executeVimCommand = (browserWindow: BrowserWindow, command: string) => {
executeMenuAction(browserWindow, {
evt: "execute-command",
cmd: ["editor.executeVimCommand", command],
})
}
const openMultipleFiles = (browserWindow: BrowserWindow, files: string[]) => {
executeMenuAction(browserWindow, { evt: "open-files", cmd: [files] })
}
const executeOniCommand = (browserWindow: BrowserWindow, command: string) => {
executeMenuAction(browserWindow, { evt: "execute-command", cmd: [command] })
}
const openUrl = (browserWindow: BrowserWindow, url: string) => {
executeMenuAction(browserWindow, { evt: "execute-command", cmd: ["browser.openUrl", url] })
}
const executeVimCommandForFiles = (browserWindow, command, files) => {
if (!files || !files.length) {
return
}
files.forEach(fileName =>
executeVimCommand(browserWindow, `${command} ${normalizePath(fileName)}`),
)
}
const isWindows = os.platform() === "win32"
const preferences = {
label: "Preferences",
submenu: [
{
label: "Edit Oni config",
accelerator: "CmdOrCtrl+,",
click(item, focusedWindow) {
executeOniCommand(focusedWindow, "oni.config.openConfigJs")
},
},
],
}
if (loadInit) {
preferences.submenu.push({
label: "Edit Neovim config",
accelerator: null,
click(item, focusedWindow) {
executeOniCommand(focusedWindow, "oni.config.openInitVim")
},
})
}
const reopenWithEncoding = {
label: "Reopen with Encoding",
submenu: [],
}
// TODO: Maybe better show normal encoding name in submenu?
// Encoding list from http://vimdoc.sourceforge.net/htmldoc/mbyte.html#encoding-values
const encodingList = [
"utf-8",
"utf-16le",
"utf-16be",
"utf-32le",
"utf-32be",
"latin1",
"koi8-r",
"koi8-u",
"macroman",
"cp437",
"cp737",
"cp775",
"cp850",
"cp852",
"cp855",
"cp857",
"cp860",
"cp861",
"cp862",
"cp863",
"cp865",
"cp866",
"cp869",
"cp874",
"cp1250",
"cp1251",
"cp1253",
"cp1254",
"cp1255",
"cp1256",
"cp1257",
"cp1258",
"cp932",
"euc-jp",
"sjis",
"cp949",
"euc-kr",
"cp936",
"euc-cn",
"cp950",
"big5",
"euc-tw",
].map(val => {
return {
label: val.toUpperCase(),
click(item, focusedWindow) {
executeVimCommand(focusedWindow, ":e! ++enc=" + val)
},
}
})
reopenWithEncoding.submenu.push(...encodingList)
menu.push({
label: isWindows ? "File" : "Oni",
submenu: [
{
label: "New File",
accelerator: "CmdOrCtrl+N",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, ":enew")
},
},
{
label: "Open File…",
accelerator: "CmdOrCtrl+O",
click(item, focusedWindow) {
dialog.showOpenDialog(
focusedWindow,
{ properties: ["openFile", "multiSelections"] },
files => openMultipleFiles(focusedWindow, files),
)
},
},
{
label: "Open Folder…",
click(item, focusedWindow) {
executeOniCommand(focusedWindow, "workspace.openFolder")
},
},
reopenWithEncoding,
{
label: "Split Open…",
click(item, focusedWindow) {
dialog.showOpenDialog(focusedWindow, { properties: ["openFile"] }, files =>
executeVimCommandForFiles(focusedWindow, ":sp", files),
)
},
},
{
type: "separator",
},
{
label: "New Window",
click() {
createWindow([], process.cwd())
},
},
{
label: "Hide Window",
click(item, focusedWindow) {
focusedWindow.hide()
},
},
{
type: "separator",
},
{
label: "Save",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, ":w")
},
},
{
label: "Save As…",
click(item, focusedWindow) {
dialog.showSaveDialog(focusedWindow, {}, name => {
if (name) {
executeVimCommand(focusedWindow, ":save " + normalizePath(name))
}
})
},
},
{
label: "Save All",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, ":wall")
},
},
{
type: "separator",
},
preferences,
{
type: "separator",
},
{
label: "Close File",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, ":close")
},
},
{
label: "Revert File",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, ":e!")
},
},
{
label: "Close All File",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, ":%bw")
},
},
{
type: "separator",
},
{
label: "Exit",
accelerator: "CmdOrCtrl+Q",
click(item, focusedWindow) {
app.quit()
},
},
],
})
// Edit menu
menu.push({
label: "Edit",
submenu: [
{
label: "Undo",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "u")
},
},
{
label: "Redo",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "\\<C-r>")
},
},
{
label: "Repeat",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, ".")
},
},
{
type: "separator",
},
{
label: "Copy",
click(item, focusedWindow) {
executeOniCommand(focusedWindow, "editor.clipboard.yank")
},
},
{
label: "Cut",
click(item, focusedWindow) {
executeOniCommand(focusedWindow, "editor.clipboard.cut")
},
},
{
label: "Paste",
click(item, focusedWindow) {
executeOniCommand(focusedWindow, "editor.clipboard.paste")
},
},
{
label: "Paste Line Before",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "[p")
},
},
{
label: "Paste Line After",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "]p")
},
},
{
label: "Copy File Path",
submenu: [
{
label: "Full Path",
click(item, focusedWindow) {
executeVimCommand(
focusedWindow,
":let @" + (isWindows ? "*" : "+") + "=expand('%:p')",
)
},
},
{
label: "Full Path with Line Number",
click(item, focusedWindow) {
executeVimCommand(
focusedWindow,
":let @" +
(isWindows ? "*" : "+") +
"=expand('%:p') . ':' . line('.')",
)
},
},
{
label: "Relative Path",
click(item, focusedWindow) {
executeVimCommand(
focusedWindow,
":let @" + (isWindows ? "*" : "+") + "=expand('%')",
)
},
},
{
label: "Relative Path with Line Number",
click(item, focusedWindow) {
executeVimCommand(
focusedWindow,
":let @" +
(isWindows ? "*" : "+") +
"=expand('%') . ':' . line('.')",
)
},
},
{
label: "File Name",
click(item, focusedWindow) {
executeVimCommand(
focusedWindow,
":let @" + (isWindows ? "*" : "+") + "=expand('%:t')",
)
},
},
{
label: "File Name with Line Number",
click(item, focusedWindow) {
executeVimCommand(
focusedWindow,
":let @" +
(isWindows ? "*" : "+") +
"=expand('%:t') . ':' . line('.')",
)
},
},
],
},
{
type: "separator",
},
{
label: "Line",
submenu: [
{
label: "Indent",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, ">")
},
},
{
label: "Unindent",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "<")
},
},
{
label: "Reindent",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "=i{")
},
},
{
type: "separator",
},
{
label: "Move Up",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "m+")
},
},
{
label: "Move Down",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "m--")
},
},
{
type: "separator",
},
{
label: "Duplicate",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "Yp")
},
},
{
label: "Copy",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "Y")
},
},
{
label: "Cut",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "Y^D")
},
},
{
label: "Delete",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "dd")
},
},
{
label: "Clear",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "^D")
},
},
{
label: "Join",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "J")
},
},
],
},
{
label: "Text",
submenu: [
{
label: "Upper Case",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "U")
},
},
{
label: "Lower Case",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "u")
},
},
{
label: "Swap Case",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "~")
},
},
{
type: "separator",
},
{
label: "Delete Inner Word",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "diw")
},
},
{
label: "Delete Previous Word",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "bbdw")
},
},
{
label: "Delete Next Word",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "nwdw")
},
},
{
label: "Strip First Character",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, ":%normal ^x")
},
},
{
label: "Strip Last Character",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, ":%normal $x")
},
},
{
label: "Strip Trailings Blanks",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, ":%s/^s+//")
executeVimCommand(focusedWindow, ":%s/s+$//")
},
},
{
label: "Delete Line",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "dd")
},
},
{
label: "Remove Blank Lines",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, ":g/^$/d")
},
},
],
},
{
label: "Comment",
submenu: [
{
label: "Toggle Comment",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, ":Commentary")
},
},
],
},
{
label: "Insert",
submenu: [
{
label: "Encoding Identifier",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, ":put =&fileencoding")
},
},
{
type: "separator",
},
{
label: "Date / Time (Short)",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, ":put =strftime('%c')")
},
},
{
label: "Date / Time (Long)",
click(item, focusedWindow) {
executeVimCommand(
focusedWindow,
":put =strftime('%a, %d %b %Y %H:%M:%S')",
)
},
},
{
type: "separator",
},
{
label: "Full Path",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, ":put =expand('%:p')")
},
},
{
label: "File Name",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, ":put =expand('%:t')")
},
},
{
label: "File Name with Line Number",
click(item, focusedWindow) {
executeVimCommand(
focusedWindow,
":put =expand('%:t') . ':' . line('.')",
)
},
},
],
},
{
type: "separator",
},
{
label: "Select All",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "ggVG")
},
},
],
})
// Window menu
menu.push({
label: "Split",
submenu: [
{
label: "New Horizontal Split",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "\\<C-w>n")
},
},
{
label: "Split File Horizontally",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "\\<C-w>s")
},
},
{
label: "Split File Vertically",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "\\<C-w>v")
},
},
{
type: "separator",
},
{
label: "Close",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "\\<C-w>c")
},
},
{
label: "Close Other Split(s)",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "\\<C-w>o")
},
},
{
type: "separator",
},
{
label: "Move To",
submenu: [
{
label: "Top",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "\\<C-w>K")
},
},
{
label: "Bottom",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "\\<C-w>J")
},
},
{
label: "Left Side",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "\\<C-w>H")
},
},
{
label: "Right Side",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "\\<C-w>L")
},
},
],
},
{
label: "Rotate Up",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "\\<C-w>R")
},
},
{
label: "Rotate Down",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "\\<C-w>r")
},
},
{
type: "separator",
},
{
label: "Equal Size",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "\\<C-w>=")
},
},
{
label: "Max Height",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "\\<C-w>_")
},
},
{
label: "Min Height",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "\\<C-w>1_")
},
},
{
label: "Max Width",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "\\<C-w>|")
},
},
{
label: "Min Width",
click(item, focusedWindow) {
executeVimCommand(focusedWindow, "\\<C-w>1|")
},
},
],
})
// Help menu
menu.push({
label: "Help",
submenu: [
{
label: "Learn more",
click(item, focusedWindow) {
openUrl(focusedWindow, "https://github.com/onivim/oni#introduction")
},
},
{
label: "Issues",
click(item, focusedWindow) {
openUrl(focusedWindow, "https://github.com/onivim/oni/issues")
},
},
{
label: "GitHub",
sublabel: "https://github.com/onivim/oni",
click(item, focusedWindow) {
openUrl(focusedWindow, "https://github.com/onivim/oni")
},
},
{
label: "Website",
sublabel: "https://www.onivim.io",
click(item, focusedWindow) {
openUrl(focusedWindow, "https://www.onivim.io")
},
},
{
type: "separator",
},
{
label: "About Oni",
click(item, focusedWindow) {
executeOniCommand(focusedWindow, "oni.about")
},
},
{
type: "separator",
},
{
label: "Developer Tools",
click(item, focusedWindow) {
executeOniCommand(focusedWindow, "oni.debug.openDevTools")
},
},
],
})
return Menu.buildFromTemplate(menu)
} | the_stack |
import { MouseEventDelegate } from "@/utils/EventHandler";
import ParamTypeServiceInstance from "../../sevices/ParamTypeService";
import CommonUtils from "../../utils/CommonUtils";
import HtmlUtils from "../../utils/HtmlUtils";
import ToolTipUtils from "../../utils/ToolTipUtils";
import { BlockParameterEditorRegData, BlockParameterEnumRegData, BlockParameterTypeRegData } from "../Define/BlockDef";
import { BlockParameterSetType } from "../Define/BlockParameterType";
import { BlockPort } from "../Define/Port";
import AllEditors from "../TypeEditors/AllEditors";
import { Vector2 } from "../Vector2";
import { BlockEditor } from "./BlockEditor";
export const BlockPortIcons = {
portBehaviorIcon: 'icon-sanjiaoxing',
portBehaviorIconActive: 'icon-zuo',
portParamIcon: 'icon-search2',
portParamIconActive: 'icon-yuan1',
portParamIconArray: 'icon-port-array',
portParamIconArrayActive: 'icon-port-array-full',
portParamIconSet: 'icon-port-set',
portParamIconDictionaryLeft: 'icon-port-dictionary-left',
portParamIconDictionaryRight: 'icon-port-dictionary-right',
portFailedIconActive: 'icon-close-',
portBehaviorAddIcon: 'icon-add-behavor-port',
portParamAddIcon: 'icon-pluss-1',
portPortDeleteIcon: 'icon-close-1',
}
/**
* 端口编辑器类
*/
export class BlockPortEditor extends BlockPort {
public constructor(block : BlockEditor) {
super(block);
this.isEditorPort = true;
this.fnonPortMouseUp = this.onPortMouseUp.bind(this);
this.fnonPortMouseMove = this.onPortMouseMove.bind(this);
}
public addPortElement(block : BlockEditor) {
this.editorData = new BlockPortEditorData();
this.editorData.parent = this;
this.editorData.block = block;
this.editorData.el = document.createElement('div');
this.editorData.el.classList.add("port");
this.editorData.elDot = document.createElement('i');
this.editorData.elDotIconLeft = document.createElement('i');
this.editorData.elDotIconRight = document.createElement('i');
this.editorData.elSpan = document.createElement('span');
this.editorData.elDeleteButton = document.createElement('a');
this.editorData.elDeleteButton.onclick = () => block.onUserDeletePort(this);
this.editorData.elDot.appendChild(this.editorData.elDotIconLeft);
this.editorData.elDot.appendChild(this.editorData.elDotIconRight);
this.editorData.elDotIconLeft.classList.add("iconfont", BlockPortIcons.portParamIconDictionaryLeft);
this.editorData.elDotIconRight.classList.add("iconfont", BlockPortIcons.portParamIconDictionaryRight);
this.editorData.elDeleteButton.classList.add("port-delete", "iconfont", BlockPortIcons.portPortDeleteIcon);
this.editorData.elDeleteButton.style.display = this.isDyamicAdd ? 'inline-block' : 'none';
this.editorData.elDeleteButton.setAttribute('data-title', '删除参数');
ToolTipUtils.registerElementTooltip(this.editorData.elDeleteButton);
this.editorData.elDot.style.color = 'rgb(253,253,253)';
this.editorData.elDot.classList.add("port-dot", "iconfont");
this.editorData.elSpan.innerText = this.name;
this.createOrRecreateParamPortEditor(true);
this.editorData.el.addEventListener('mousedown', (e) => this.onPortMouseDown(e));
this.editorData.el.addEventListener('mouseenter', (e) => this.onPortMouseEnter(e));
this.editorData.el.addEventListener('mouseleave', () => this.onPortMouseLeave());
this.editorData.el.addEventListener('contextmenu', this.onContextMenu.bind(this));
ToolTipUtils.registerElementTooltip(this.editorData.el);
//switch port and text's direction
if(this.direction === 'input') {
this.editorData.el.appendChild(this.editorData.elDot);
this.editorData.el.appendChild(this.editorData.elSpan);
if(this.editorData.elEditor != null) this.editorData.el.appendChild(this.editorData.elEditor);
this.editorData.el.appendChild(this.editorData.elDeleteButton);
}
else if(this.direction === 'output') {
this.editorData.el.appendChild(this.editorData.elDeleteButton);
if(this.editorData.elEditor != null) this.editorData.el.appendChild(this.editorData.elEditor);
this.editorData.el.appendChild(this.editorData.elSpan);
this.editorData.el.appendChild(this.editorData.elDot);
}
//add element node
if(this.paramType.isExecute())
this.editorData.elDot.classList.add(BlockPortIcons.portBehaviorIcon)
else
this.editorData.elDot.classList.add(BlockPortIcons.portParamIcon);
if(this.direction == 'input') (<BlockEditor>this.parent).els.elInputPorts.appendChild(this.editorData.el);
else if(this.direction === 'output') (<BlockEditor>this.parent).els.elOutputPorts.appendChild(this.editorData.el);
this.updatePortElement();
this.createOrReCreatePortCustomEditor();
}
public createOrReCreatePortCustomEditor() {
if(typeof (<BlockEditor>this.parent).onCreatePortCustomEditor === 'function') {
if(this.editorData.elCustomEditor != null) {
this.editorData.elCustomEditor.parentNode.removeChild(this.editorData.elCustomEditor);
this.editorData.elCustomEditor = null;
}
this.editorData.elCustomEditor = (<BlockEditor>this.parent).onCreatePortCustomEditor(this.editorData.el, (<BlockEditor>this.parent), this);
//添加元素
if(this.editorData.elCustomEditor!=null) {
this.editorData.elCustomEditor.classList.add('param-editor');
//switch port and text's direction
if(this.direction == 'input')
this.editorData.el.insertBefore(this.editorData.elCustomEditor, this.editorData.elDeleteButton);
else if(this.direction == 'output')
this.editorData.el.insertBefore(this.editorData.elCustomEditor, this.editorData.elSpan);
}
}
}
public createOrRecreateParamPortEditor(isAdd = false) {
if(this.paramType.isExecute()) {
this.editorData.el.setAttribute('data-title', this.name + (CommonUtils.isNullOrEmpty(this.description) ? '' : ('\n<small>' + this.description + '</small>')));
return;
}
if(this.paramType.equals(this.editorData.oldParamType)
&& this.paramDictionaryKeyType.equals(this.editorData.oldParamKeyType)
&& this.paramSetType == this.editorData.oldParamSetType) {
this.updatePortParamDisplayVal();
return;
}
if(this.editorData.elEditor != null) {
this.editorData.elEditor.parentNode.removeChild(this.editorData.elEditor);
this.editorData.elEditor = null;
}
let portParameter = this;
let customType : BlockParameterTypeRegData = null;
if((portParameter.paramType.isCustom()) && !CommonUtils.isNullOrEmpty(portParameter.paramType.customType))
customType = ParamTypeServiceInstance.getCustomType(portParameter.paramType.customType);
//获取类型编辑器
let editor : BlockParameterEditorRegData = null;
if(this.direction == 'input' || this.forceEditorControlOutput) {
if((portParameter.paramType.isCustom()) && customType != null){
editor = customType.editor;
if(editor == null && customType.prototypeName == 'enum')
editor = AllEditors.getDefaultEnumEditor(<BlockParameterEnumRegData>customType);
}
else editor = AllEditors.getBaseEditors(portParameter.paramType.baseType);
}
if(editor != null && editor.useInSetType.indexOf(portParameter.paramSetType) < 0) editor = null;
//类型说明
this.editorData.elEditor = null;
this.updatePortParamDisplayVal();
if(customType != null)
this.editorData.elDot.style.color = customType.color;
else
this.editorData.elDot.style.color = ParamTypeServiceInstance.getTypeColor(this.paramType.baseType);
//创建类型编辑器
if(!this.forceNoEditorControl && editor != null) {
//创建编辑器和更新回调
this.editorData.elEditor = editor.editorCreate(
<BlockEditor>this.parent,
this,
this.editorData.el, (v) => {
portParameter.paramUserSetValue = v;
let context = this.parent.currentRunningContext;
if(context) {
if(portParameter.direction == 'output')
portParameter.updateOnputValue(context, v);
else
portParameter.setValue(context, v);
}
return v;
}, portParameter.paramUserSetValue, portParameter.paramDefaultValue, customType);
//添加元素
if(this.editorData.elEditor!=null) {
this.editorData.elEditor.classList.add('param-editor');
if(!isAdd) {
//switch port and text's direction
if(this.direction == 'input')
this.editorData.el.insertBefore(this.editorData.elEditor, this.editorData.elDeleteButton);
else if(this.direction == 'output')
this.editorData.el.insertBefore(this.editorData.elEditor, this.editorData.elSpan);
}
}
}
this.editorData.editor = editor;
this.editorData.oldParamType = this.paramType.getType();
this.editorData.oldParamKeyType = this.paramDictionaryKeyType.getType();
this.editorData.oldParamSetType = this.paramSetType;
}
public updatePortParamDisplayVal() {
ToolTipUtils.updateElementTooltip(this.editorData.el, this.getPortParamValStr());
}
public updatePortElement() {
this.editorData.elSpan.innerText = this.name;
this.editorData.elDeleteButton.style.display = this.isDyamicAdd ? 'inline-block' : 'none';
if(this.paramType.isExecute()){
this.editorData.el.setAttribute('data-title', '<h5 class="text-secondary">' + (CommonUtils.isNullOrEmpty(this.name) ? (
this.direction == 'input' ? '入口' : '出口'
) : this.name) + '</h5>执行' +
(CommonUtils.isNullOrEmpty(this.description) ? '' : ('\n<small>' + this.description + '</small>')));
HtmlUtils.hideElement(this.editorData.elDotIconLeft);
HtmlUtils.hideElement(this.editorData.elDotIconRight);
this.editorData.elDot.classList.remove(BlockPortIcons.portParamIcon, BlockPortIcons.portParamIconActive,
BlockPortIcons.portParamIconArray, BlockPortIcons.portParamIconArrayActive, BlockPortIcons.portParamIconSet);
} else {
if(this.paramSetType != 'dictionary') {
HtmlUtils.hideElement(this.editorData.elDotIconLeft);
HtmlUtils.hideElement(this.editorData.elDotIconRight);
}
this.editorData.elDot.classList.remove(BlockPortIcons.portBehaviorIcon, BlockPortIcons.portBehaviorIconActive);
this.createOrRecreateParamPortEditor();
this.updatePortParamDisplayVal();
}
this.updatePortConnectStatusElement();
}
public removePortElement() {
this.editorData.el.parentNode.removeChild(this.editorData.el);
this.editorData = null;
}
public getPortParamValStr() {
let str = '<h5>' + (CommonUtils.isNullOrEmpty(this.name) ? (this.direction == 'input' ? '参数' : '返回值') : this.name)
+ '</h5><span class="text-secondary"><small>' + this.description
+ '</small></span><br/>类型:' + this.getTypeFriendlyString();
if(this.parent.currentRunner != null) {
str += '<br/>当前值:';
if(this.parent.currentRunningContext == null) str += CommonUtils.valueToStr(this.getUserSetValue())
else str += CommonUtils.valueToStr(
this.direction == 'input' ? this.rquestInputValue(this.parent.currentRunningContext) : this.rquestOutputValue(this.parent.currentRunningContext)
);
} else if(this.direction == 'input' && !this.forceNoEditorControl
&& this.editorData.editor != null && this.connectedFromPort.length == 0)
str += '<br/>设置值:' + CommonUtils.valueToStr(this.getUserSetValue());
return str;
}
public updatePortConnectStatusElement() {
//点的状态
if(this.editorData.forceDotErrorState){
this.editorData.elDot.classList.add("error", BlockPortIcons.portFailedIconActive);
this.editorData.elDot.classList.remove(BlockPortIcons.portBehaviorIcon, BlockPortIcons.portBehaviorIconActive,
BlockPortIcons.portParamIcon, BlockPortIcons.portParamIconActive);
HtmlUtils.hideElement(this.editorData.elDotIconLeft);
HtmlUtils.hideElement(this.editorData.elDotIconRight);
}else {
this.editorData.elDot.classList.remove("error", BlockPortIcons.portFailedIconActive);
if(this.paramType.isExecute())
CommonUtils.setClassWithSwitch(this.editorData.elDot, this.isConnected() || this.editorData.forceDotActiveState,
BlockPortIcons.portBehaviorIcon, BlockPortIcons.portBehaviorIconActive);
else {
this.editorData.elDot.classList.remove(BlockPortIcons.portParamIcon, BlockPortIcons.portParamIconActive, BlockPortIcons.portParamIconArray,
BlockPortIcons.portParamIconArrayActive, BlockPortIcons.portParamIconSet);
switch(this.paramSetType) {
case 'variable':
default: {
CommonUtils.setClassWithSwitch(this.editorData.elDot, this.isConnected() || this.editorData.forceDotActiveState,
BlockPortIcons.portParamIcon, BlockPortIcons.portParamIconActive);
break
}
case 'array': {
CommonUtils.setClassWithSwitch(this.editorData.elDot, this.isConnected() || this.editorData.forceDotActiveState,
BlockPortIcons.portParamIconArray, BlockPortIcons.portParamIconArrayActive);
break
}
case 'dictionary': {
this.editorData.elDotIconLeft.setAttribute('style', 'width: 8px;display: inline-block;margin-left: -5px;');
this.editorData.elDotIconRight.setAttribute('style', 'margin-left: -2px;');
this.editorData.elDotIconRight.style.color = ParamTypeServiceInstance.getTypeColor(this.paramType.getType(), 'rgb(129,122,122)');
this.editorData.elDotIconLeft.style.color = ParamTypeServiceInstance.getTypeColor(this.paramDictionaryKeyType.getType(), 'rgb(129,122,122)');
break
}
case 'set': {
this.editorData.elDot.classList.add(BlockPortIcons.portParamIconSet);
this.editorData.elDot.style.color = ParamTypeServiceInstance.getTypeColor(this.paramType.getType(), 'rgb(129,122,122)');
break
}
}
}
}
//数值编辑器状态
if(!this.paramType.isExecute()) {
if(this.editorData.elEditor != null) {
this.editorData.elEditor.style.display = this.isConnected() ? 'none' : 'inline-block';
}
}
}
public unconnectAllConnector() {
(<BlockEditor>this.parent).unConnectPort(this);
}
/**
* 端口的编辑器数据
*/
public editorData : BlockPortEditorData = null;
//#region 鼠标事件
public mouseEnter = false;
public mouseDownInPort = false;
public mouseConnectingPort = false;
private onPortMouseEnter(e : MouseEvent) {
if(!this.mouseEnter) {
this.mouseEnter = true;
(<BlockEditor>this.parent).editor.updateCurrentHoverPort(this);
if(!this.paramType.isExecute())
ToolTipUtils.updateElementTooltip(this.editorData.el, this.getPortParamValStr());
}
}
private onPortMouseLeave() {
if(this.mouseEnter) {
this.mouseEnter = false;
(<BlockEditor>this.parent).editor.updateCurrentHoverPortLeave(this);
}
}
private onPortMouseMove(e : MouseEvent) {
if(e.button == 0) {
this.mouseConnectingPort = true;
(<BlockEditor>this.parent).mouseConnectingPort = true;
(<BlockEditor>this.parent).editor.updateConnectEnd(new Vector2(e.x, e.y));
}
return true;
}
private onPortMouseDown(e : MouseEvent) {
if(!this.testIsDownInControl(e)) {
this.mouseDownInPort = true;
(<BlockEditor>this.parent).mouseDownInPort = true;
this.mouseConnectingPort = false;
(<BlockEditor>this.parent).mouseConnectingPort = false;
if(e.button == 0) {
(<BlockEditor>this.parent).editor.startConnect(this);
(<BlockEditor>this.parent).editor.updateConnectEnd(new Vector2(e.x, e.y));
}
document.addEventListener('mouseup', this.fnonPortMouseUp);
document.addEventListener('mousemove', this.fnonPortMouseMove);
e.stopPropagation();
}
}
private onPortMouseUp() {
this.mouseDownInPort = false;
this.mouseConnectingPort = false;
(<BlockEditor>this.parent).mouseDownInPort = false;
(<BlockEditor>this.parent).mouseConnectingPort = false;
(<BlockEditor>this.parent).editor.endConnect(this);
document.removeEventListener('mouseup', this.fnonPortMouseUp);
document.removeEventListener('mousemove', this.fnonPortMouseMove);
}
private onContextMenu(e : MouseEvent) {
e.stopPropagation();
e.preventDefault();
(<BlockEditor>this.parent).editor.showPortRightMenu(this, new Vector2(e.x, e.y));
return false;
}
//#endregion
private fnonPortMouseMove : MouseEventDelegate = null;
private fnonPortMouseUp : MouseEventDelegate = null;
private testIsDownInControl(e : MouseEvent){
let target = (<HTMLElement>e.target);
return (HtmlUtils.isEventInControl(e)
|| target.classList.contains('flow-block-no-move')
|| target.classList.contains('param-editor')
|| target.classList.contains('port-delete')
|| target.classList.contains('port')
|| target.classList.contains('custom-editor'));
}
//#region 编辑器获取信息
public getBlockFastInfo() {
return this.parent.regData.baseInfo.name;
}
public getParentBlock() {
return <BlockEditor>this.parent;
}
//#endregion
}
/**
* 编辑器使用数据
*/
export class BlockPortEditorData {
public el : HTMLDivElement = null;
public elDot : HTMLElement = null;
public elDotIconLeft : HTMLElement = null;
public elDotIconRight : HTMLElement = null;
public elSpan : HTMLSpanElement = null;
public elEditor : HTMLElement = null;
public elCustomEditor : HTMLElement = null;
public elDeleteButton : HTMLElement = null;
public forceDotErrorState = false;
public forceDotActiveState = false;
public block : BlockEditor = null;
public parent : BlockPort = null;
public editor : BlockParameterEditorRegData = null;
public oldParamType : string = null;
public oldParamKeyType : string = null;
public oldParamSetType : BlockParameterSetType = null;
private pos = new Vector2();
public getPosition() {
this.pos.Set(this.block.position.x + this.elDot.offsetLeft + this.elDot.offsetWidth / 2,
this.block.position.y + this.elDot.offsetTop + this.elDot.offsetHeight / 2 + 4);
return this.pos;
}
public updatePortConnectStatusElement() {
this.block.updatePortConnectStatusElement(this.parent);
}
}
export class BlockPortEditorDataFake extends BlockPortEditorData {
public constructor() {
super();
}
private posFake = new Vector2();
public setPosition(p : Vector2) {
this.posFake.Set(p);
}
public getPosition() {
return this.posFake;
}
} | the_stack |
import { Emitter, Event } from 'vs/base/common/event';
import { IModelDecorationOptions, IModelDecorationsChangeAccessor, IModelDeltaDecoration, ITextModel } from 'vs/editor/common/model';
import { FoldingRegion, FoldingRegions, ILineRange } from './foldingRanges';
export interface IDecorationProvider {
getDecorationOption(isCollapsed: boolean, isHidden: boolean): IModelDecorationOptions;
deltaDecorations(oldDecorations: string[], newDecorations: IModelDeltaDecoration[]): string[];
changeDecorations<T>(callback: (changeAccessor: IModelDecorationsChangeAccessor) => T): T | null;
}
export interface FoldingModelChangeEvent {
model: FoldingModel;
collapseStateChanged?: FoldingRegion[];
}
export type CollapseMemento = ILineRange[];
export class FoldingModel {
private readonly _textModel: ITextModel;
private readonly _decorationProvider: IDecorationProvider;
private _regions: FoldingRegions;
private _editorDecorationIds: string[];
private _isInitialized: boolean;
private readonly _updateEventEmitter = new Emitter<FoldingModelChangeEvent>();
public readonly onDidChange: Event<FoldingModelChangeEvent> = this._updateEventEmitter.event;
public get regions(): FoldingRegions { return this._regions; }
public get textModel() { return this._textModel; }
public get isInitialized() { return this._isInitialized; }
public get decorationProvider() { return this._decorationProvider; }
constructor(textModel: ITextModel, decorationProvider: IDecorationProvider) {
this._textModel = textModel;
this._decorationProvider = decorationProvider;
this._regions = new FoldingRegions(new Uint32Array(0), new Uint32Array(0));
this._editorDecorationIds = [];
this._isInitialized = false;
}
public toggleCollapseState(toggledRegions: FoldingRegion[]) {
if (!toggledRegions.length) {
return;
}
toggledRegions = toggledRegions.sort((r1, r2) => r1.regionIndex - r2.regionIndex);
const processed: { [key: string]: boolean | undefined } = {};
this._decorationProvider.changeDecorations(accessor => {
let k = 0; // index from [0 ... this.regions.length]
let dirtyRegionEndLine = -1; // end of the range where decorations need to be updated
let lastHiddenLine = -1; // the end of the last hidden lines
const updateDecorationsUntil = (index: number) => {
while (k < index) {
const endLineNumber = this._regions.getEndLineNumber(k);
const isCollapsed = this._regions.isCollapsed(k);
if (endLineNumber <= dirtyRegionEndLine) {
accessor.changeDecorationOptions(this._editorDecorationIds[k], this._decorationProvider.getDecorationOption(isCollapsed, endLineNumber <= lastHiddenLine));
}
if (isCollapsed && endLineNumber > lastHiddenLine) {
lastHiddenLine = endLineNumber;
}
k++;
}
};
for (let region of toggledRegions) {
let index = region.regionIndex;
let editorDecorationId = this._editorDecorationIds[index];
if (editorDecorationId && !processed[editorDecorationId]) {
processed[editorDecorationId] = true;
updateDecorationsUntil(index); // update all decorations up to current index using the old dirtyRegionEndLine
let newCollapseState = !this._regions.isCollapsed(index);
this._regions.setCollapsed(index, newCollapseState);
dirtyRegionEndLine = Math.max(dirtyRegionEndLine, this._regions.getEndLineNumber(index));
}
}
updateDecorationsUntil(this._regions.length);
});
this._updateEventEmitter.fire({ model: this, collapseStateChanged: toggledRegions });
}
public update(newRegions: FoldingRegions, blockedLineNumers: number[] = []): void {
let newEditorDecorations: IModelDeltaDecoration[] = [];
let isBlocked = (startLineNumber: number, endLineNumber: number) => {
for (let blockedLineNumber of blockedLineNumers) {
if (startLineNumber < blockedLineNumber && blockedLineNumber <= endLineNumber) { // first line is visible
return true;
}
}
return false;
};
let lastHiddenLine = -1;
let initRange = (index: number, isCollapsed: boolean) => {
const startLineNumber = newRegions.getStartLineNumber(index);
const endLineNumber = newRegions.getEndLineNumber(index);
if (!isCollapsed) {
isCollapsed = newRegions.isCollapsed(index);
}
if (isCollapsed && isBlocked(startLineNumber, endLineNumber)) {
isCollapsed = false;
}
newRegions.setCollapsed(index, isCollapsed);
const maxColumn = this._textModel.getLineMaxColumn(startLineNumber);
const decorationRange = {
startLineNumber: startLineNumber,
startColumn: Math.max(maxColumn - 1, 1), // make it length == 1 to detect deletions
endLineNumber: startLineNumber,
endColumn: maxColumn
};
newEditorDecorations.push({ range: decorationRange, options: this._decorationProvider.getDecorationOption(isCollapsed, endLineNumber <= lastHiddenLine) });
if (isCollapsed && endLineNumber > lastHiddenLine) {
lastHiddenLine = endLineNumber;
}
};
let i = 0;
let nextCollapsed = () => {
while (i < this._regions.length) {
let isCollapsed = this._regions.isCollapsed(i);
i++;
if (isCollapsed) {
return i - 1;
}
}
return -1;
};
let k = 0;
let collapsedIndex = nextCollapsed();
while (collapsedIndex !== -1 && k < newRegions.length) {
// get the latest range
let decRange = this._textModel.getDecorationRange(this._editorDecorationIds[collapsedIndex]);
if (decRange) {
let collapsedStartLineNumber = decRange.startLineNumber;
if (decRange.startColumn === Math.max(decRange.endColumn - 1, 1) && this._textModel.getLineMaxColumn(collapsedStartLineNumber) === decRange.endColumn) { // test that the decoration is still covering the full line else it got deleted
while (k < newRegions.length) {
let startLineNumber = newRegions.getStartLineNumber(k);
if (collapsedStartLineNumber >= startLineNumber) {
initRange(k, collapsedStartLineNumber === startLineNumber);
k++;
} else {
break;
}
}
}
}
collapsedIndex = nextCollapsed();
}
while (k < newRegions.length) {
initRange(k, false);
k++;
}
this._editorDecorationIds = this._decorationProvider.deltaDecorations(this._editorDecorationIds, newEditorDecorations);
this._regions = newRegions;
this._isInitialized = true;
this._updateEventEmitter.fire({ model: this });
}
/**
* Collapse state memento, for persistence only
*/
public getMemento(): CollapseMemento | undefined {
let collapsedRanges: ILineRange[] = [];
for (let i = 0; i < this._regions.length; i++) {
if (this._regions.isCollapsed(i)) {
let range = this._textModel.getDecorationRange(this._editorDecorationIds[i]);
if (range) {
let startLineNumber = range.startLineNumber;
let endLineNumber = range.endLineNumber + this._regions.getEndLineNumber(i) - this._regions.getStartLineNumber(i);
collapsedRanges.push({ startLineNumber, endLineNumber });
}
}
}
if (collapsedRanges.length > 0) {
return collapsedRanges;
}
return undefined;
}
/**
* Apply persisted state, for persistence only
*/
public applyMemento(state: CollapseMemento) {
if (!Array.isArray(state)) {
return;
}
let toToogle: FoldingRegion[] = [];
for (let range of state) {
let region = this.getRegionAtLine(range.startLineNumber);
if (region && !region.isCollapsed) {
toToogle.push(region);
}
}
this.toggleCollapseState(toToogle);
}
public dispose() {
this._decorationProvider.deltaDecorations(this._editorDecorationIds, []);
}
getAllRegionsAtLine(lineNumber: number, filter?: (r: FoldingRegion, level: number) => boolean): FoldingRegion[] {
let result: FoldingRegion[] = [];
if (this._regions) {
let index = this._regions.findRange(lineNumber);
let level = 1;
while (index >= 0) {
let current = this._regions.toRegion(index);
if (!filter || filter(current, level)) {
result.push(current);
}
level++;
index = current.parentIndex;
}
}
return result;
}
getRegionAtLine(lineNumber: number): FoldingRegion | null {
if (this._regions) {
let index = this._regions.findRange(lineNumber);
if (index >= 0) {
return this._regions.toRegion(index);
}
}
return null;
}
getRegionsInside(region: FoldingRegion | null, filter?: RegionFilter | RegionFilterWithLevel): FoldingRegion[] {
let result: FoldingRegion[] = [];
let index = region ? region.regionIndex + 1 : 0;
let endLineNumber = region ? region.endLineNumber : Number.MAX_VALUE;
if (filter && filter.length === 2) {
const levelStack: FoldingRegion[] = [];
for (let i = index, len = this._regions.length; i < len; i++) {
let current = this._regions.toRegion(i);
if (this._regions.getStartLineNumber(i) < endLineNumber) {
while (levelStack.length > 0 && !current.containedBy(levelStack[levelStack.length - 1])) {
levelStack.pop();
}
levelStack.push(current);
if (filter(current, levelStack.length)) {
result.push(current);
}
} else {
break;
}
}
} else {
for (let i = index, len = this._regions.length; i < len; i++) {
let current = this._regions.toRegion(i);
if (this._regions.getStartLineNumber(i) < endLineNumber) {
if (!filter || (filter as RegionFilter)(current)) {
result.push(current);
}
} else {
break;
}
}
}
return result;
}
}
type RegionFilter = (r: FoldingRegion) => boolean;
type RegionFilterWithLevel = (r: FoldingRegion, level: number) => boolean;
/**
* Collapse or expand the regions at the given locations
* @param levels The number of levels. Use 1 to only impact the regions at the location, use Number.MAX_VALUE for all levels.
* @param lineNumbers the location of the regions to collapse or expand, or if not set, all regions in the model.
*/
export function toggleCollapseState(foldingModel: FoldingModel, levels: number, lineNumbers: number[]) {
let toToggle: FoldingRegion[] = [];
for (let lineNumber of lineNumbers) {
let region = foldingModel.getRegionAtLine(lineNumber);
if (region) {
const doCollapse = !region.isCollapsed;
toToggle.push(region);
if (levels > 1) {
let regionsInside = foldingModel.getRegionsInside(region, (r, level: number) => r.isCollapsed !== doCollapse && level < levels);
toToggle.push(...regionsInside);
}
}
}
foldingModel.toggleCollapseState(toToggle);
}
/**
* Collapse or expand the regions at the given locations including all children.
* @param doCollapse Whether to collapse or expand
* @param levels The number of levels. Use 1 to only impact the regions at the location, use Number.MAX_VALUE for all levels.
* @param lineNumbers the location of the regions to collapse or expand, or if not set, all regions in the model.
*/
export function setCollapseStateLevelsDown(foldingModel: FoldingModel, doCollapse: boolean, levels = Number.MAX_VALUE, lineNumbers?: number[]): void {
let toToggle: FoldingRegion[] = [];
if (lineNumbers && lineNumbers.length > 0) {
for (let lineNumber of lineNumbers) {
let region = foldingModel.getRegionAtLine(lineNumber);
if (region) {
if (region.isCollapsed !== doCollapse) {
toToggle.push(region);
}
if (levels > 1) {
let regionsInside = foldingModel.getRegionsInside(region, (r, level: number) => r.isCollapsed !== doCollapse && level < levels);
toToggle.push(...regionsInside);
}
}
}
} else {
let regionsInside = foldingModel.getRegionsInside(null, (r, level: number) => r.isCollapsed !== doCollapse && level < levels);
toToggle.push(...regionsInside);
}
foldingModel.toggleCollapseState(toToggle);
}
/**
* Collapse or expand the regions at the given locations including all parents.
* @param doCollapse Whether to collapse or expand
* @param levels The number of levels. Use 1 to only impact the regions at the location, use Number.MAX_VALUE for all levels.
* @param lineNumbers the location of the regions to collapse or expand.
*/
export function setCollapseStateLevelsUp(foldingModel: FoldingModel, doCollapse: boolean, levels: number, lineNumbers: number[]): void {
let toToggle: FoldingRegion[] = [];
for (let lineNumber of lineNumbers) {
let regions = foldingModel.getAllRegionsAtLine(lineNumber, (region, level) => region.isCollapsed !== doCollapse && level <= levels);
toToggle.push(...regions);
}
foldingModel.toggleCollapseState(toToggle);
}
/**
* Collapse or expand a region at the given locations. If the inner most region is already collapsed/expanded, uses the first parent instead.
* @param doCollapse Whether to collapse or expand
* @param lineNumbers the location of the regions to collapse or expand.
*/
export function setCollapseStateUp(foldingModel: FoldingModel, doCollapse: boolean, lineNumbers: number[]): void {
let toToggle: FoldingRegion[] = [];
for (let lineNumber of lineNumbers) {
let regions = foldingModel.getAllRegionsAtLine(lineNumber, (region,) => region.isCollapsed !== doCollapse);
if (regions.length > 0) {
toToggle.push(regions[0]);
}
}
foldingModel.toggleCollapseState(toToggle);
}
/**
* Folds or unfolds all regions that have a given level, except if they contain one of the blocked lines.
* @param foldLevel level. Level == 1 is the top level
* @param doCollapse Whether to collapse or expand
*/
export function setCollapseStateAtLevel(foldingModel: FoldingModel, foldLevel: number, doCollapse: boolean, blockedLineNumbers: number[]): void {
let filter = (region: FoldingRegion, level: number) => level === foldLevel && region.isCollapsed !== doCollapse && !blockedLineNumbers.some(line => region.containsLine(line));
let toToggle = foldingModel.getRegionsInside(null, filter);
foldingModel.toggleCollapseState(toToggle);
}
/**
* Folds or unfolds all regions, except if they contain or are contained by a region of one of the blocked lines.
* @param doCollapse Whether to collapse or expand
* @param blockedLineNumbers the location of regions to not collapse or expand
*/
export function setCollapseStateForRest(foldingModel: FoldingModel, doCollapse: boolean, blockedLineNumbers: number[]): void {
let filteredRegions: FoldingRegion[] = [];
for (let lineNumber of blockedLineNumbers) {
const regions = foldingModel.getAllRegionsAtLine(lineNumber, undefined);
if (regions.length > 0) {
filteredRegions.push(regions[0]);
}
}
let filter = (region: FoldingRegion) => filteredRegions.every((filteredRegion) => !filteredRegion.containedBy(region) && !region.containedBy(filteredRegion)) && region.isCollapsed !== doCollapse;
let toToggle = foldingModel.getRegionsInside(null, filter);
foldingModel.toggleCollapseState(toToggle);
}
/**
* Folds all regions for which the lines start with a given regex
* @param foldingModel the folding model
*/
export function setCollapseStateForMatchingLines(foldingModel: FoldingModel, regExp: RegExp, doCollapse: boolean): void {
let editorModel = foldingModel.textModel;
let regions = foldingModel.regions;
let toToggle: FoldingRegion[] = [];
for (let i = regions.length - 1; i >= 0; i--) {
if (doCollapse !== regions.isCollapsed(i)) {
let startLineNumber = regions.getStartLineNumber(i);
if (regExp.test(editorModel.getLineContent(startLineNumber))) {
toToggle.push(regions.toRegion(i));
}
}
}
foldingModel.toggleCollapseState(toToggle);
}
/**
* Folds all regions of the given type
* @param foldingModel the folding model
*/
export function setCollapseStateForType(foldingModel: FoldingModel, type: string, doCollapse: boolean): void {
let regions = foldingModel.regions;
let toToggle: FoldingRegion[] = [];
for (let i = regions.length - 1; i >= 0; i--) {
if (doCollapse !== regions.isCollapsed(i) && type === regions.getType(i)) {
toToggle.push(regions.toRegion(i));
}
}
foldingModel.toggleCollapseState(toToggle);
}
/**
* Get line to go to for parent fold of current line
* @param lineNumber the current line number
* @param foldingModel the folding model
*
* @return Parent fold start line
*/
export function getParentFoldLine(lineNumber: number, foldingModel: FoldingModel): number | null {
let startLineNumber: number | null = null;
let foldingRegion = foldingModel.getRegionAtLine(lineNumber);
if (foldingRegion !== null) {
startLineNumber = foldingRegion.startLineNumber;
// If current line is not the start of the current fold, go to top line of current fold. If not, go to parent fold
if (lineNumber === startLineNumber) {
let parentFoldingIdx = foldingRegion.parentIndex;
if (parentFoldingIdx !== -1) {
startLineNumber = foldingModel.regions.getStartLineNumber(parentFoldingIdx);
} else {
startLineNumber = null;
}
}
}
return startLineNumber;
}
/**
* Get line to go to for previous fold at the same level of current line
* @param lineNumber the current line number
* @param foldingModel the folding model
*
* @return Previous fold start line
*/
export function getPreviousFoldLine(lineNumber: number, foldingModel: FoldingModel): number | null {
let foldingRegion = foldingModel.getRegionAtLine(lineNumber);
// If on the folding range start line, go to previous sibling.
if (foldingRegion !== null && foldingRegion.startLineNumber === lineNumber) {
// If current line is not the start of the current fold, go to top line of current fold. If not, go to previous fold.
if (lineNumber !== foldingRegion.startLineNumber) {
return foldingRegion.startLineNumber;
} else {
// Find min line number to stay within parent.
let expectedParentIndex = foldingRegion.parentIndex;
let minLineNumber = 0;
if (expectedParentIndex !== -1) {
minLineNumber = foldingModel.regions.getStartLineNumber(foldingRegion.parentIndex);
}
// Find fold at same level.
while (foldingRegion !== null) {
if (foldingRegion.regionIndex > 0) {
foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex - 1);
// Keep at same level.
if (foldingRegion.startLineNumber <= minLineNumber) {
return null;
} else if (foldingRegion.parentIndex === expectedParentIndex) {
return foldingRegion.startLineNumber;
}
} else {
return null;
}
}
}
} else {
// Go to last fold that's before the current line.
if (foldingModel.regions.length > 0) {
foldingRegion = foldingModel.regions.toRegion(foldingModel.regions.length - 1);
while (foldingRegion !== null) {
// Found fold before current line.
if (foldingRegion.startLineNumber < lineNumber) {
return foldingRegion.startLineNumber;
}
if (foldingRegion.regionIndex > 0) {
foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex - 1);
} else {
foldingRegion = null;
}
}
}
}
return null;
}
/**
* Get line to go to next fold at the same level of current line
* @param lineNumber the current line number
* @param foldingModel the folding model
*
* @return Next fold start line
*/
export function getNextFoldLine(lineNumber: number, foldingModel: FoldingModel): number | null {
let foldingRegion = foldingModel.getRegionAtLine(lineNumber);
// If on the folding range start line, go to next sibling.
if (foldingRegion !== null && foldingRegion.startLineNumber === lineNumber) {
// Find max line number to stay within parent.
let expectedParentIndex = foldingRegion.parentIndex;
let maxLineNumber = 0;
if (expectedParentIndex !== -1) {
maxLineNumber = foldingModel.regions.getEndLineNumber(foldingRegion.parentIndex);
} else if (foldingModel.regions.length === 0) {
return null;
} else {
maxLineNumber = foldingModel.regions.getEndLineNumber(foldingModel.regions.length - 1);
}
// Find fold at same level.
while (foldingRegion !== null) {
if (foldingRegion.regionIndex < foldingModel.regions.length) {
foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex + 1);
// Keep at same level.
if (foldingRegion.startLineNumber >= maxLineNumber) {
return null;
} else if (foldingRegion.parentIndex === expectedParentIndex) {
return foldingRegion.startLineNumber;
}
} else {
return null;
}
}
} else {
// Go to first fold that's after the current line.
if (foldingModel.regions.length > 0) {
foldingRegion = foldingModel.regions.toRegion(0);
while (foldingRegion !== null) {
// Found fold after current line.
if (foldingRegion.startLineNumber > lineNumber) {
return foldingRegion.startLineNumber;
}
if (foldingRegion.regionIndex < foldingModel.regions.length) {
foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex + 1);
} else {
foldingRegion = null;
}
}
}
}
return null;
} | the_stack |
import * as fs from 'fs';
import * as path from 'path';
import { EOL } from 'os';
import {
CdmArgumentDefinition,
CdmCollection,
CdmConstantEntityDefinition,
CdmCorpusDefinition,
CdmE2ERelationship,
CdmEntityDefinition,
CdmEntityReference,
CdmFolderDefinition,
CdmManifestDefinition,
CdmTraitReferenceBase,
CdmTraitReference
} from '../../../internal';
import { testHelper } from '../../testHelper';
import { projectionTestUtils } from '../../Utilities/projectionTestUtils';
import { AttributeContextUtil } from '../Projection/AttributeContextUtil';
/**
* Test to validate calculateEntityGraphAsync function
*/
describe('Cdm/Relationship/CalculateRelationshipTest', () => {
/**
* Platform-specific line separator
*/
const endOfLine: string = EOL;
/**
* The path between TestDataPath and TestName.
*/
const testsSubpath: string = 'Cdm/Relationship/TestCalculateRelationship';
/**
* Non projection scenario with the referenced entity having a primary key
*/
it('TestSimpleWithId', async () => {
const testName: string = 'TestSimpleWithId';
const entityName: string = 'Sales';
await testRun(testName, entityName, false);
});
/**
* Projection scenario with the referenced entity not having any primary key
*/
it('TestWithoutIdProj', async () => {
const testName: string = 'TestWithoutIdProj';
const entityName: string = 'Sales';
await testRun(testName, entityName, true);
});
/**
*
*/
it('TestDiffRefLocation', async () => {
const testName: string = 'TestDiffRefLocation';
const entityName: string = 'Sales';
await testRun(testName, entityName, true);
});
/**
* Projection with composite keys
*/
it('TestCompositeProj', async () => {
const testName: string = 'TestCompositeProj';
const entityName: string = 'Sales';
await testRun(testName, entityName, true);
});
/**
* Projection with nested composite keys
*/
it('TestNestedCompositeProj', async () => {
const testName: string = 'TestNestedCompositeProj';
const entityName: string = 'Sales';
await testRun(testName, entityName, true);
});
/**
* Non projection scenario with selectsSubAttribute set to one
*/
it('TestPolymorphicWithoutProj', async () => {
const testName: string = 'TestPolymorphicWithoutProj';
const entityName: string = 'CustomPerson';
await testRun(testName, entityName, false);
});
/**
* Projection with IsPolymorphicSource property set to true
*/
it('TestPolymorphicProj', async () => {
const testName: string = 'TestPolymorphicProj';
const entityName: string = 'Person';
await testRun(testName, entityName, true);
});
/**
* Test a composite key relationship with a polymorphic entity
*/
it('TestCompositeKeyPolymorphicRelationship', async () => {
const testName: string = 'TestCompositeKeyPolymorphicRelationship';
const entityName: string = 'Person';
await testRun(testName, entityName, true);
});
/**
* Test a composite key relationship with multiple entity attribute but not polymorphic
*/
it('TestCompositeKeyNonPolymorphicRelationship', async () => {
const testName: string = 'TestCompositeKeyNonPolymorphicRelationship';
const entityName: string = 'Person';
await testRun(testName, entityName, true);
});
/**
* Common test code for these test cases
*/
async function testRun(testName: string, entityName: string, isEntitySet: boolean, updateExpectedOutput: boolean = false): Promise<void> {
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
const inputFolder: string = testHelper.getInputFolderPath(testsSubpath, testName);
const expectedOutputFolder: string = testHelper.getExpectedOutputFolderPath(testsSubpath, testName);
const actualOutputFolder: string = testHelper.getActualOutputFolderPath(testsSubpath, testName);
if (!fs.existsSync(actualOutputFolder)) {
fs.mkdirSync(actualOutputFolder, { recursive: true });
}
const manifest: CdmManifestDefinition = await corpus.fetchObjectAsync<CdmManifestDefinition>('local:/default.manifest.cdm.json');
expect(manifest)
.toBeTruthy();
const entity: CdmEntityDefinition = await corpus.fetchObjectAsync<CdmEntityDefinition>(`local:/${entityName}.cdm.json/${entityName}`, manifest);
expect(entity)
.toBeTruthy();
const resolvedEntity: CdmEntityDefinition = await projectionTestUtils.getResolvedEntity(corpus, entity, ['referenceOnly']);
assertEntityShapeInReslovedEntity(resolvedEntity, isEntitySet);
await AttributeContextUtil.validateAttributeContext(expectedOutputFolder, entityName, resolvedEntity, updateExpectedOutput);
await corpus.calculateEntityGraphAsync(manifest);
await manifest.populateManifestRelationshipsAsync();
const actualRelationshipsString: string = listRelationships(corpus, entity, actualOutputFolder, entityName);
const relationshipsFilename: string = `REL_${entityName}.txt`;
fs.writeFileSync(path.join(actualOutputFolder, relationshipsFilename), actualRelationshipsString);
const expectedRelationshipsStringFilePath: string = path.resolve(path.join(expectedOutputFolder, relationshipsFilename));
const expectedRelationshipsString: string = fs.readFileSync(expectedRelationshipsStringFilePath).toString();
expect(actualRelationshipsString)
.toEqual(expectedRelationshipsString);
const outputFolder: CdmFolderDefinition = corpus.storage.fetchRootFolder('output');
outputFolder.documents.push(manifest);
const manifestFileName: string = 'saved.manifest.cdm.json';
await manifest.saveAsAsync(manifestFileName, true);
const actualManifestPath: string = `${actualOutputFolder}/${manifestFileName}`;
if (!fs.existsSync(actualManifestPath)) {
fail('Unable to save manifest with relationship');
} else {
const savedManifest: CdmManifestDefinition = await corpus.fetchObjectAsync<CdmManifestDefinition>(`output:/${manifestFileName}`);
const actualSavedManifestRel: string = getRelationshipStrings(savedManifest.relationships);
const manifestRelationshipsFilename: string = `MANIFEST_REL_${entityName}.txt`;
fs.writeFileSync(path.join(actualOutputFolder, manifestRelationshipsFilename), actualSavedManifestRel);
const expectedSavedManifestRel: string = fs.readFileSync(path.join(expectedOutputFolder, manifestRelationshipsFilename)).toString();
expect(actualSavedManifestRel)
.toEqual(expectedSavedManifestRel);
}
}
/**
* Check if the entity shape is correct in entity reference.
*/
function assertEntityShapeInReslovedEntity(resolvedEntity: CdmEntityDefinition, isEntitySet: boolean): void {
for (const att of resolvedEntity.attributes) {
if (att && att.appliedTraits) {
for (const traitRef of att.appliedTraits) {
if (traitRef.namedReference === 'is.linkedEntity.identifier' && (traitRef as CdmTraitReference).arguments.length > 0) {
const constEnt: CdmConstantEntityDefinition = ((traitRef as CdmTraitReference).arguments.allItems[0].value as CdmEntityReference).fetchObjectDefinition<CdmConstantEntityDefinition>();
if (constEnt) {
if (isEntitySet) {
expect('entitySet')
.toEqual(constEnt.entityShape.namedReference)
} else {
expect('entityGroupSet')
.toEqual(constEnt.entityShape.namedReference)
}
return;
}
}
}
}
}
fail('Unable to find entity shape from resolved model.');
}
/**
* Get a string version of the relationship collection
*/
function getRelationshipStrings(relationships: CdmCollection<CdmE2ERelationship>): string {
let bldr: string = '';
for (const rel of relationships.allItems) {
bldr += `${rel.name ? rel.name : ''}|${rel.toEntity}|${rel.toEntityAttribute}|${rel.fromEntity}|${rel.fromEntityAttribute}`;
bldr += endOfLine;
}
return bldr;
}
/**
* Get a string version of one relationship
*/
function getRelationshipString(rel: CdmE2ERelationship): string {
let nameAndPipe: string = '';
if (rel.name) {
nameAndPipe = `${rel.name}|`
}
return `${nameAndPipe}${rel.toEntity}|${rel.toEntityAttribute}|${rel.fromEntity}|${rel.fromEntityAttribute}`;
}
/**
* List the incoming and outgoing relationships
*/
function listRelationships(corpus: CdmCorpusDefinition, entity: CdmEntityDefinition, actualOutputFolder: string, entityName: string): string {
let bldr: string = '';
const relCache: Set<string> = new Set<string>();
bldr += `Incoming Relationships For: ${entity.entityName}:` + endOfLine;
// Loop through all the relationships where other entities point to this entity.
for (const relationship of corpus.fetchIncomingRelationships(entity)) {
const cacheKey: string = getRelationshipString(relationship);
if (!relCache.has(cacheKey))
{
bldr += printRelationship(relationship) + endOfLine;
relCache.add(cacheKey);
}
}
console.log(`Outgoing Relationships For: ${entity.entityName}:`);
// Now loop through all the relationships where this entity points to other entities.
for (const relationship of corpus.fetchOutgoingRelationships(entity)) {
const cacheKey: string = getRelationshipString(relationship);
if (!relCache.has(cacheKey))
{
bldr += printRelationship(relationship) + endOfLine;
relCache.add(cacheKey);
}
}
return bldr;
}
/**
* Print the relationship
*/
function printRelationship(relationship: CdmE2ERelationship): string {
let bldr: string = '';
if (relationship.name) {
bldr += ` Name: ${relationship.name}` + endOfLine;
}
bldr += ` FromEntity: ${relationship.fromEntity}` + endOfLine;
bldr += ` FromEntityAttribute: ${relationship.fromEntityAttribute}` + endOfLine;
bldr += ` ToEntity: ${relationship.toEntity}` + endOfLine;
bldr += ` ToEntityAttribute: ${relationship.toEntityAttribute}` + endOfLine;
if (relationship.exhibitsTraits != null && relationship.exhibitsTraits.length != 0) {
bldr += ' ExhibitsTraits:' + endOfLine;
var orderedAppliedTraits = relationship.exhibitsTraits.allItems.sort((a, b) => a.namedReference?.localeCompare(b.namedReference));
orderedAppliedTraits.forEach((trait : CdmTraitReferenceBase) => {
bldr += ` ${trait.namedReference}` + endOfLine;
if (trait instanceof CdmTraitReference) {
(trait as CdmTraitReference).arguments.allItems.forEach((args : CdmArgumentDefinition) => {
var attrCtxUtil = new AttributeContextUtil();
bldr += ` ${attrCtxUtil.getArgumentValuesAsString(args)}` + endOfLine;
});
}
});
}
bldr += endOfLine;
console.log(bldr);
return bldr;
}
/**
* Check the attribute context for these test scenarios
*/
function getAttributeContextString(resolvedEntity: CdmEntityDefinition, entityName: string, actualOutputFolder: string): string {
return (new AttributeContextUtil()).getAttributeContextStrings(resolvedEntity);
}
}); | the_stack |
namespace ts {
const enum ClassPropertySubstitutionFlags {
/**
* Enables substitutions for class expressions with static fields
* which have initializers that reference the class name.
*/
ClassAliases = 1 << 0,
/**
* Enables substitutions for class expressions with static fields
* which have initializers that reference the 'this' or 'super'.
*/
ClassStaticThisOrSuperReference = 1 << 1,
}
export const enum PrivateIdentifierKind {
Field = "f",
Method = "m",
Accessor = "a"
}
interface PrivateIdentifierInfoBase {
/**
* brandCheckIdentifier can contain:
* - For instance field: The WeakMap that will be the storage for the field.
* - For instance methods or accessors: The WeakSet that will be used for brand checking.
* - For static members: The constructor that will be used for brand checking.
*/
brandCheckIdentifier: Identifier;
/**
* Stores if the identifier is static or not
*/
isStatic: boolean;
/**
* Stores if the identifier declaration is valid or not. Reserved names (e.g. #constructor)
* or duplicate identifiers are considered invalid.
*/
isValid: boolean;
}
interface PrivateIdentifierAccessorInfo extends PrivateIdentifierInfoBase {
kind: PrivateIdentifierKind.Accessor;
/**
* Identifier for a variable that will contain the private get accessor implementation, if any.
*/
getterName?: Identifier;
/**
* Identifier for a variable that will contain the private set accessor implementation, if any.
*/
setterName?: Identifier;
}
interface PrivateIdentifierMethodInfo extends PrivateIdentifierInfoBase {
kind: PrivateIdentifierKind.Method;
/**
* Identifier for a variable that will contain the private method implementation.
*/
methodName: Identifier;
}
interface PrivateIdentifierInstanceFieldInfo extends PrivateIdentifierInfoBase {
kind: PrivateIdentifierKind.Field;
isStatic: false;
/**
* Defined for ease of access when in a union with PrivateIdentifierStaticFieldInfo.
*/
variableName: undefined;
}
interface PrivateIdentifierStaticFieldInfo extends PrivateIdentifierInfoBase {
kind: PrivateIdentifierKind.Field;
isStatic: true;
/**
* Contains the variable that will server as the storage for the field.
*/
variableName: Identifier;
}
type PrivateIdentifierInfo =
| PrivateIdentifierMethodInfo
| PrivateIdentifierInstanceFieldInfo
| PrivateIdentifierStaticFieldInfo
| PrivateIdentifierAccessorInfo;
interface PrivateIdentifierEnvironment {
/**
* Used for prefixing generated variable names.
*/
className: string;
/**
* Used for brand check on private methods.
*/
weakSetName?: Identifier;
/**
* A mapping of private names to information needed for transformation.
*/
identifiers: UnderscoreEscapedMap<PrivateIdentifierInfo>
}
interface ClassLexicalEnvironment {
facts: ClassFacts;
/**
* Used for brand checks on static members, and `this` references in static initializers
*/
classConstructor: Identifier | undefined;
/**
* Used for `super` references in static initializers.
*/
superClassReference: Identifier | undefined;
privateIdentifierEnvironment: PrivateIdentifierEnvironment | undefined;
}
const enum ClassFacts {
None = 0,
ClassWasDecorated = 1 << 0,
NeedsClassConstructorReference = 1 << 1,
NeedsClassSuperReference = 1 << 2,
NeedsSubstitutionForThisInClassStaticField = 1 << 3,
}
/**
* Transforms ECMAScript Class Syntax.
* TypeScript parameter property syntax is transformed in the TypeScript transformer.
* For now, this transforms public field declarations using TypeScript class semantics,
* where declarations are elided and initializers are transformed as assignments in the constructor.
* When --useDefineForClassFields is on, this transforms to ECMAScript semantics, with Object.defineProperty.
*/
export function transformClassFields(context: TransformationContext) {
const {
factory,
hoistVariableDeclaration,
endLexicalEnvironment,
startLexicalEnvironment,
resumeLexicalEnvironment,
addBlockScopedVariable
} = context;
const resolver = context.getEmitResolver();
const compilerOptions = context.getCompilerOptions();
const languageVersion = getEmitScriptTarget(compilerOptions);
const useDefineForClassFields = getUseDefineForClassFields(compilerOptions);
const shouldTransformPrivateElementsOrClassStaticBlocks = languageVersion < ScriptTarget.ES2022;
// We don't need to transform `super` property access when targeting ES5, ES3 because
// the es2015 transformation handles those.
const shouldTransformSuperInStaticInitializers = (languageVersion <= ScriptTarget.ES2021 || !useDefineForClassFields) && languageVersion >= ScriptTarget.ES2015;
const shouldTransformThisInStaticInitializers = languageVersion <= ScriptTarget.ES2021 || !useDefineForClassFields;
const previousOnSubstituteNode = context.onSubstituteNode;
context.onSubstituteNode = onSubstituteNode;
const previousOnEmitNode = context.onEmitNode;
context.onEmitNode = onEmitNode;
let enabledSubstitutions: ClassPropertySubstitutionFlags;
let classAliases: Identifier[];
/**
* Tracks what computed name expressions originating from elided names must be inlined
* at the next execution site, in document order
*/
let pendingExpressions: Expression[] | undefined;
/**
* Tracks what computed name expression statements and static property initializers must be
* emitted at the next execution site, in document order (for decorated classes).
*/
let pendingStatements: Statement[] | undefined;
const classLexicalEnvironmentStack: (ClassLexicalEnvironment | undefined)[] = [];
const classLexicalEnvironmentMap = new Map<number, ClassLexicalEnvironment>();
let currentClassLexicalEnvironment: ClassLexicalEnvironment | undefined;
let currentComputedPropertyNameClassLexicalEnvironment: ClassLexicalEnvironment | undefined;
let currentStaticPropertyDeclarationOrStaticBlock: PropertyDeclaration | ClassStaticBlockDeclaration | undefined;
return chainBundle(context, transformSourceFile);
function transformSourceFile(node: SourceFile) {
const options = context.getCompilerOptions();
if (node.isDeclarationFile
|| useDefineForClassFields && getEmitScriptTarget(options) >= ScriptTarget.ES2022) {
return node;
}
const visited = visitEachChild(node, visitor, context);
addEmitHelpers(visited, context.readEmitHelpers());
return visited;
}
function visitorWorker(node: Node, valueIsDiscarded: boolean): VisitResult<Node> {
if (node.transformFlags & TransformFlags.ContainsClassFields) {
switch (node.kind) {
case SyntaxKind.ClassExpression:
case SyntaxKind.ClassDeclaration:
return visitClassLike(node as ClassLikeDeclaration);
case SyntaxKind.PropertyDeclaration:
return visitPropertyDeclaration(node as PropertyDeclaration);
case SyntaxKind.VariableStatement:
return visitVariableStatement(node as VariableStatement);
case SyntaxKind.PrivateIdentifier:
return visitPrivateIdentifier(node as PrivateIdentifier);
case SyntaxKind.ClassStaticBlockDeclaration:
return visitClassStaticBlockDeclaration(node as ClassStaticBlockDeclaration);
}
}
if (node.transformFlags & TransformFlags.ContainsClassFields ||
node.transformFlags & TransformFlags.ContainsLexicalSuper &&
shouldTransformSuperInStaticInitializers &&
currentStaticPropertyDeclarationOrStaticBlock &&
currentClassLexicalEnvironment) {
switch (node.kind) {
case SyntaxKind.PrefixUnaryExpression:
case SyntaxKind.PostfixUnaryExpression:
return visitPreOrPostfixUnaryExpression(node as PrefixUnaryExpression | PostfixUnaryExpression, valueIsDiscarded);
case SyntaxKind.BinaryExpression:
return visitBinaryExpression(node as BinaryExpression, valueIsDiscarded);
case SyntaxKind.CallExpression:
return visitCallExpression(node as CallExpression);
case SyntaxKind.TaggedTemplateExpression:
return visitTaggedTemplateExpression(node as TaggedTemplateExpression);
case SyntaxKind.PropertyAccessExpression:
return visitPropertyAccessExpression(node as PropertyAccessExpression);
case SyntaxKind.ElementAccessExpression:
return visitElementAccessExpression(node as ElementAccessExpression);
case SyntaxKind.ExpressionStatement:
return visitExpressionStatement(node as ExpressionStatement);
case SyntaxKind.ForStatement:
return visitForStatement(node as ForStatement);
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
case SyntaxKind.Constructor:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor: {
const savedCurrentStaticPropertyDeclarationOrStaticBlock = currentStaticPropertyDeclarationOrStaticBlock;
currentStaticPropertyDeclarationOrStaticBlock = undefined;
const result = visitEachChild(node, visitor, context);
currentStaticPropertyDeclarationOrStaticBlock = savedCurrentStaticPropertyDeclarationOrStaticBlock;
return result;
}
}
}
return visitEachChild(node, visitor, context);
}
function discardedValueVisitor(node: Node): VisitResult<Node> {
return visitorWorker(node, /*valueIsDiscarded*/ true);
}
function visitor(node: Node): VisitResult<Node> {
return visitorWorker(node, /*valueIsDiscarded*/ false);
}
function heritageClauseVisitor(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.HeritageClause:
return visitEachChild(node, heritageClauseVisitor, context);
case SyntaxKind.ExpressionWithTypeArguments:
return visitExpressionWithTypeArguments(node as ExpressionWithTypeArguments);
}
return visitor(node);
}
function visitorDestructuringTarget(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.ObjectLiteralExpression:
case SyntaxKind.ArrayLiteralExpression:
return visitAssignmentPattern(node as AssignmentPattern);
default:
return visitor(node);
}
}
/**
* If we visit a private name, this means it is an undeclared private name.
* Replace it with an empty identifier to indicate a problem with the code,
* unless we are in a statement position - otherwise this will not trigger
* a SyntaxError.
*/
function visitPrivateIdentifier(node: PrivateIdentifier) {
if (!shouldTransformPrivateElementsOrClassStaticBlocks) {
return node;
}
if (isStatement(node.parent)) {
return node;
}
return setOriginalNode(factory.createIdentifier(""), node);
}
/**
* Visits `#id in expr`
*/
function visitPrivateIdentifierInInExpression(node: BinaryExpression) {
if (!shouldTransformPrivateElementsOrClassStaticBlocks) {
return node;
}
const privId = node.left;
Debug.assertNode(privId, isPrivateIdentifier);
Debug.assert(node.operatorToken.kind === SyntaxKind.InKeyword);
const info = accessPrivateIdentifier(privId);
if (info) {
const receiver = visitNode(node.right, visitor, isExpression);
return setOriginalNode(
context.getEmitHelperFactory().createClassPrivateFieldInHelper(info.brandCheckIdentifier, receiver),
node
);
}
// Private name has not been declared. Subsequent transformers will handle this error
return visitEachChild(node, visitor, context);
}
/**
* Visits the members of a class that has fields.
*
* @param node The node to visit.
*/
function classElementVisitor(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.Constructor:
// Constructors for classes using class fields are transformed in
// `visitClassDeclaration` or `visitClassExpression`.
return undefined;
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.MethodDeclaration:
return visitMethodOrAccessorDeclaration(node as MethodDeclaration | AccessorDeclaration);
case SyntaxKind.PropertyDeclaration:
return visitPropertyDeclaration(node as PropertyDeclaration);
case SyntaxKind.ComputedPropertyName:
return visitComputedPropertyName(node as ComputedPropertyName);
case SyntaxKind.SemicolonClassElement:
return node;
default:
return visitor(node);
}
}
function visitVariableStatement(node: VariableStatement) {
const savedPendingStatements = pendingStatements;
pendingStatements = [];
const visitedNode = visitEachChild(node, visitor, context);
const statement = some(pendingStatements) ?
[visitedNode, ...pendingStatements] :
visitedNode;
pendingStatements = savedPendingStatements;
return statement;
}
function visitComputedPropertyName(name: ComputedPropertyName) {
let node = visitEachChild(name, visitor, context);
if (some(pendingExpressions)) {
const expressions = pendingExpressions;
expressions.push(node.expression);
pendingExpressions = [];
node = factory.updateComputedPropertyName(
node,
factory.inlineExpressions(expressions)
);
}
return node;
}
function visitMethodOrAccessorDeclaration(node: MethodDeclaration | AccessorDeclaration) {
Debug.assert(!some(node.decorators));
if (!shouldTransformPrivateElementsOrClassStaticBlocks || !isPrivateIdentifier(node.name)) {
return visitEachChild(node, classElementVisitor, context);
}
// leave invalid code untransformed
const info = accessPrivateIdentifier(node.name);
Debug.assert(info, "Undeclared private name for property declaration.");
if (!info.isValid) {
return node;
}
const functionName = getHoistedFunctionName(node);
if (functionName) {
getPendingExpressions().push(
factory.createAssignment(
functionName,
factory.createFunctionExpression(
filter(node.modifiers, m => !isStaticModifier(m)),
node.asteriskToken,
functionName,
/* typeParameters */ undefined,
visitParameterList(node.parameters, classElementVisitor, context),
/* type */ undefined,
visitFunctionBody(node.body!, classElementVisitor, context)
)
)
);
}
// remove method declaration from class
return undefined;
}
function getHoistedFunctionName(node: MethodDeclaration | AccessorDeclaration) {
Debug.assert(isPrivateIdentifier(node.name));
const info = accessPrivateIdentifier(node.name);
Debug.assert(info, "Undeclared private name for property declaration.");
if (info.kind === PrivateIdentifierKind.Method) {
return info.methodName;
}
if (info.kind === PrivateIdentifierKind.Accessor) {
if (isGetAccessor(node)) {
return info.getterName;
}
if (isSetAccessor(node)) {
return info.setterName;
}
}
}
function visitPropertyDeclaration(node: PropertyDeclaration) {
Debug.assert(!some(node.decorators));
if (isPrivateIdentifier(node.name)) {
if (!shouldTransformPrivateElementsOrClassStaticBlocks) {
// Initializer is elided as the field is initialized in transformConstructor.
return factory.updatePropertyDeclaration(
node,
/*decorators*/ undefined,
visitNodes(node.modifiers, visitor, isModifier),
node.name,
/*questionOrExclamationToken*/ undefined,
/*type*/ undefined,
/*initializer*/ undefined
);
}
// leave invalid code untransformed
const info = accessPrivateIdentifier(node.name);
Debug.assert(info, "Undeclared private name for property declaration.");
if (!info.isValid) {
return node;
}
}
// Create a temporary variable to store a computed property name (if necessary).
// If it's not inlineable, then we emit an expression after the class which assigns
// the property name to the temporary variable.
const expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || useDefineForClassFields);
if (expr && !isSimpleInlineableExpression(expr)) {
getPendingExpressions().push(expr);
}
return undefined;
}
function createPrivateIdentifierAccess(info: PrivateIdentifierInfo, receiver: Expression): Expression {
return createPrivateIdentifierAccessHelper(info, visitNode(receiver, visitor, isExpression));
}
function createPrivateIdentifierAccessHelper(info: PrivateIdentifierInfo, receiver: Expression): Expression {
setCommentRange(receiver, moveRangePos(receiver, -1));
switch(info.kind) {
case PrivateIdentifierKind.Accessor:
return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(
receiver,
info.brandCheckIdentifier,
info.kind,
info.getterName
);
case PrivateIdentifierKind.Method:
return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(
receiver,
info.brandCheckIdentifier,
info.kind,
info.methodName
);
case PrivateIdentifierKind.Field:
return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(
receiver,
info.brandCheckIdentifier,
info.kind,
info.variableName
);
default:
Debug.assertNever(info, "Unknown private element type");
}
}
function visitPropertyAccessExpression(node: PropertyAccessExpression) {
if (shouldTransformPrivateElementsOrClassStaticBlocks && isPrivateIdentifier(node.name)) {
const privateIdentifierInfo = accessPrivateIdentifier(node.name);
if (privateIdentifierInfo) {
return setTextRange(
setOriginalNode(
createPrivateIdentifierAccess(privateIdentifierInfo, node.expression),
node
),
node
);
}
}
if (shouldTransformSuperInStaticInitializers &&
isSuperProperty(node) &&
isIdentifier(node.name) &&
currentStaticPropertyDeclarationOrStaticBlock &&
currentClassLexicalEnvironment) {
const { classConstructor, superClassReference, facts } = currentClassLexicalEnvironment;
if (facts & ClassFacts.ClassWasDecorated) {
return visitInvalidSuperProperty(node);
}
if (classConstructor && superClassReference) {
// converts `super.x` into `Reflect.get(_baseTemp, "x", _classTemp)`
const superProperty = factory.createReflectGetCall(
superClassReference,
factory.createStringLiteralFromNode(node.name),
classConstructor
);
setOriginalNode(superProperty, node.expression);
setTextRange(superProperty, node.expression);
return superProperty;
}
}
return visitEachChild(node, visitor, context);
}
function visitElementAccessExpression(node: ElementAccessExpression) {
if (shouldTransformSuperInStaticInitializers &&
isSuperProperty(node) &&
currentStaticPropertyDeclarationOrStaticBlock &&
currentClassLexicalEnvironment) {
const { classConstructor, superClassReference, facts } = currentClassLexicalEnvironment;
if (facts & ClassFacts.ClassWasDecorated) {
return visitInvalidSuperProperty(node);
}
if (classConstructor && superClassReference) {
// converts `super[x]` into `Reflect.get(_baseTemp, x, _classTemp)`
const superProperty = factory.createReflectGetCall(
superClassReference,
visitNode(node.argumentExpression, visitor, isExpression),
classConstructor
);
setOriginalNode(superProperty, node.expression);
setTextRange(superProperty, node.expression);
return superProperty;
}
}
return visitEachChild(node, visitor, context);
}
function visitPreOrPostfixUnaryExpression(node: PrefixUnaryExpression | PostfixUnaryExpression, valueIsDiscarded: boolean) {
if (node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken) {
if (shouldTransformPrivateElementsOrClassStaticBlocks && isPrivateIdentifierPropertyAccessExpression(node.operand)) {
let info: PrivateIdentifierInfo | undefined;
if (info = accessPrivateIdentifier(node.operand.name)) {
const receiver = visitNode(node.operand.expression, visitor, isExpression);
const { readExpression, initializeExpression } = createCopiableReceiverExpr(receiver);
let expression: Expression = createPrivateIdentifierAccess(info, readExpression);
const temp = isPrefixUnaryExpression(node) || valueIsDiscarded ? undefined : factory.createTempVariable(hoistVariableDeclaration);
expression = expandPreOrPostfixIncrementOrDecrementExpression(factory, node, expression, hoistVariableDeclaration, temp);
expression = createPrivateIdentifierAssignment(
info,
initializeExpression || readExpression,
expression,
SyntaxKind.EqualsToken
);
setOriginalNode(expression, node);
setTextRange(expression, node);
if (temp) {
expression = factory.createComma(expression, temp);
setTextRange(expression, node);
}
return expression;
}
}
else if (shouldTransformSuperInStaticInitializers &&
isSuperProperty(node.operand) &&
currentStaticPropertyDeclarationOrStaticBlock &&
currentClassLexicalEnvironment) {
// converts `++super.a` into `(Reflect.set(_baseTemp, "a", (_a = Reflect.get(_baseTemp, "a", _classTemp), _b = ++_a), _classTemp), _b)`
// converts `++super[f()]` into `(Reflect.set(_baseTemp, _a = f(), (_b = Reflect.get(_baseTemp, _a, _classTemp), _c = ++_b), _classTemp), _c)`
// converts `--super.a` into `(Reflect.set(_baseTemp, "a", (_a = Reflect.get(_baseTemp, "a", _classTemp), _b = --_a), _classTemp), _b)`
// converts `--super[f()]` into `(Reflect.set(_baseTemp, _a = f(), (_b = Reflect.get(_baseTemp, _a, _classTemp), _c = --_b), _classTemp), _c)`
// converts `super.a++` into `(Reflect.set(_baseTemp, "a", (_a = Reflect.get(_baseTemp, "a", _classTemp), _b = _a++), _classTemp), _b)`
// converts `super[f()]++` into `(Reflect.set(_baseTemp, _a = f(), (_b = Reflect.get(_baseTemp, _a, _classTemp), _c = _b++), _classTemp), _c)`
// converts `super.a--` into `(Reflect.set(_baseTemp, "a", (_a = Reflect.get(_baseTemp, "a", _classTemp), _b = _a--), _classTemp), _b)`
// converts `super[f()]--` into `(Reflect.set(_baseTemp, _a = f(), (_b = Reflect.get(_baseTemp, _a, _classTemp), _c = _b--), _classTemp), _c)`
const { classConstructor, superClassReference, facts } = currentClassLexicalEnvironment;
if (facts & ClassFacts.ClassWasDecorated) {
const operand = visitInvalidSuperProperty(node.operand);
return isPrefixUnaryExpression(node) ?
factory.updatePrefixUnaryExpression(node, operand) :
factory.updatePostfixUnaryExpression(node, operand);
}
if (classConstructor && superClassReference) {
let setterName: Expression | undefined;
let getterName: Expression | undefined;
if (isPropertyAccessExpression(node.operand)) {
if (isIdentifier(node.operand.name)) {
getterName = setterName = factory.createStringLiteralFromNode(node.operand.name);
}
}
else {
if (isSimpleInlineableExpression(node.operand.argumentExpression)) {
getterName = setterName = node.operand.argumentExpression;
}
else {
getterName = factory.createTempVariable(hoistVariableDeclaration);
setterName = factory.createAssignment(getterName, visitNode(node.operand.argumentExpression, visitor, isExpression));
}
}
if (setterName && getterName) {
let expression: Expression = factory.createReflectGetCall(superClassReference, getterName, classConstructor);
setTextRange(expression, node.operand);
const temp = valueIsDiscarded ? undefined : factory.createTempVariable(hoistVariableDeclaration);
expression = expandPreOrPostfixIncrementOrDecrementExpression(factory, node, expression, hoistVariableDeclaration, temp);
expression = factory.createReflectSetCall(superClassReference, setterName, expression, classConstructor);
setOriginalNode(expression, node);
setTextRange(expression, node);
if (temp) {
expression = factory.createComma(expression, temp);
setTextRange(expression, node);
}
return expression;
}
}
}
}
return visitEachChild(node, visitor, context);
}
function visitForStatement(node: ForStatement) {
return factory.updateForStatement(
node,
visitNode(node.initializer, discardedValueVisitor, isForInitializer),
visitNode(node.condition, visitor, isExpression),
visitNode(node.incrementor, discardedValueVisitor, isExpression),
visitIterationBody(node.statement, visitor, context)
);
}
function visitExpressionStatement(node: ExpressionStatement) {
return factory.updateExpressionStatement(
node,
visitNode(node.expression, discardedValueVisitor, isExpression)
);
}
function createCopiableReceiverExpr(receiver: Expression): { readExpression: Expression; initializeExpression: Expression | undefined } {
const clone = nodeIsSynthesized(receiver) ? receiver : factory.cloneNode(receiver);
if (isSimpleInlineableExpression(receiver)) {
return { readExpression: clone, initializeExpression: undefined };
}
const readExpression = factory.createTempVariable(hoistVariableDeclaration);
const initializeExpression = factory.createAssignment(readExpression, clone);
return { readExpression, initializeExpression };
}
function visitCallExpression(node: CallExpression) {
if (shouldTransformPrivateElementsOrClassStaticBlocks && isPrivateIdentifierPropertyAccessExpression(node.expression)) {
// Transform call expressions of private names to properly bind the `this` parameter.
const { thisArg, target } = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion);
if (isCallChain(node)) {
return factory.updateCallChain(
node,
factory.createPropertyAccessChain(visitNode(target, visitor), node.questionDotToken, "call"),
/*questionDotToken*/ undefined,
/*typeArguments*/ undefined,
[visitNode(thisArg, visitor, isExpression), ...visitNodes(node.arguments, visitor, isExpression)]
);
}
return factory.updateCallExpression(
node,
factory.createPropertyAccessExpression(visitNode(target, visitor), "call"),
/*typeArguments*/ undefined,
[visitNode(thisArg, visitor, isExpression), ...visitNodes(node.arguments, visitor, isExpression)]
);
}
if (shouldTransformSuperInStaticInitializers &&
isSuperProperty(node.expression) &&
currentStaticPropertyDeclarationOrStaticBlock &&
currentClassLexicalEnvironment?.classConstructor) {
// converts `super.f(...)` into `Reflect.get(_baseTemp, "f", _classTemp).call(_classTemp, ...)`
const invocation = factory.createFunctionCallCall(
visitNode(node.expression, visitor, isExpression),
currentClassLexicalEnvironment.classConstructor,
visitNodes(node.arguments, visitor, isExpression)
);
setOriginalNode(invocation, node);
setTextRange(invocation, node);
return invocation;
}
return visitEachChild(node, visitor, context);
}
function visitTaggedTemplateExpression(node: TaggedTemplateExpression) {
if (shouldTransformPrivateElementsOrClassStaticBlocks && isPrivateIdentifierPropertyAccessExpression(node.tag)) {
// Bind the `this` correctly for tagged template literals when the tag is a private identifier property access.
const { thisArg, target } = factory.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion);
return factory.updateTaggedTemplateExpression(
node,
factory.createCallExpression(
factory.createPropertyAccessExpression(visitNode(target, visitor), "bind"),
/*typeArguments*/ undefined,
[visitNode(thisArg, visitor, isExpression)]
),
/*typeArguments*/ undefined,
visitNode(node.template, visitor, isTemplateLiteral)
);
}
if (shouldTransformSuperInStaticInitializers &&
isSuperProperty(node.tag) &&
currentStaticPropertyDeclarationOrStaticBlock &&
currentClassLexicalEnvironment?.classConstructor) {
// converts `` super.f`x` `` into `` Reflect.get(_baseTemp, "f", _classTemp).bind(_classTemp)`x` ``
const invocation = factory.createFunctionBindCall(
visitNode(node.tag, visitor, isExpression),
currentClassLexicalEnvironment.classConstructor,
[]
);
setOriginalNode(invocation, node);
setTextRange(invocation, node);
return factory.updateTaggedTemplateExpression(
node,
invocation,
/*typeArguments*/ undefined,
visitNode(node.template, visitor, isTemplateLiteral)
);
}
return visitEachChild(node, visitor, context);
}
function transformClassStaticBlockDeclaration(node: ClassStaticBlockDeclaration) {
if (shouldTransformPrivateElementsOrClassStaticBlocks) {
if (currentClassLexicalEnvironment) {
classLexicalEnvironmentMap.set(getOriginalNodeId(node), currentClassLexicalEnvironment);
}
startLexicalEnvironment();
const savedCurrentStaticPropertyDeclarationOrStaticBlock = currentStaticPropertyDeclarationOrStaticBlock;
currentStaticPropertyDeclarationOrStaticBlock = node;
let statements = visitNodes(node.body.statements, visitor, isStatement);
statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment());
currentStaticPropertyDeclarationOrStaticBlock = savedCurrentStaticPropertyDeclarationOrStaticBlock;
const iife = factory.createImmediatelyInvokedArrowFunction(statements);
setOriginalNode(iife, node);
setTextRange(iife, node);
addEmitFlags(iife, EmitFlags.AdviseOnEmitNode);
return iife;
}
}
function visitBinaryExpression(node: BinaryExpression, valueIsDiscarded: boolean) {
if (isDestructuringAssignment(node)) {
const savedPendingExpressions = pendingExpressions;
pendingExpressions = undefined;
node = factory.updateBinaryExpression(
node,
visitNode(node.left, visitorDestructuringTarget),
node.operatorToken,
visitNode(node.right, visitor)
);
const expr = some(pendingExpressions) ?
factory.inlineExpressions(compact([...pendingExpressions, node])) :
node;
pendingExpressions = savedPendingExpressions;
return expr;
}
if (isAssignmentExpression(node)) {
if (shouldTransformPrivateElementsOrClassStaticBlocks && isPrivateIdentifierPropertyAccessExpression(node.left)) {
const info = accessPrivateIdentifier(node.left.name);
if (info) {
return setTextRange(
setOriginalNode(
createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind),
node
),
node
);
}
}
else if (shouldTransformSuperInStaticInitializers &&
isSuperProperty(node.left) &&
currentStaticPropertyDeclarationOrStaticBlock &&
currentClassLexicalEnvironment) {
const { classConstructor, superClassReference, facts } = currentClassLexicalEnvironment;
if (facts & ClassFacts.ClassWasDecorated) {
return factory.updateBinaryExpression(
node,
visitInvalidSuperProperty(node.left),
node.operatorToken,
visitNode(node.right, visitor, isExpression));
}
if (classConstructor && superClassReference) {
let setterName =
isElementAccessExpression(node.left) ? visitNode(node.left.argumentExpression, visitor, isExpression) :
isIdentifier(node.left.name) ? factory.createStringLiteralFromNode(node.left.name) :
undefined;
if (setterName) {
// converts `super.x = 1` into `(Reflect.set(_baseTemp, "x", _a = 1, _classTemp), _a)`
// converts `super[f()] = 1` into `(Reflect.set(_baseTemp, f(), _a = 1, _classTemp), _a)`
// converts `super.x += 1` into `(Reflect.set(_baseTemp, "x", _a = Reflect.get(_baseTemp, "x", _classtemp) + 1, _classTemp), _a)`
// converts `super[f()] += 1` into `(Reflect.set(_baseTemp, _a = f(), _b = Reflect.get(_baseTemp, _a, _classtemp) + 1, _classTemp), _b)`
let expression = visitNode(node.right, visitor, isExpression);
if (isCompoundAssignment(node.operatorToken.kind)) {
let getterName = setterName;
if (!isSimpleInlineableExpression(setterName)) {
getterName = factory.createTempVariable(hoistVariableDeclaration);
setterName = factory.createAssignment(getterName, setterName);
}
const superPropertyGet = factory.createReflectGetCall(
superClassReference,
getterName,
classConstructor
);
setOriginalNode(superPropertyGet, node.left);
setTextRange(superPropertyGet, node.left);
expression = factory.createBinaryExpression(
superPropertyGet,
getNonAssignmentOperatorForCompoundAssignment(node.operatorToken.kind),
expression
);
setTextRange(expression, node);
}
const temp = valueIsDiscarded ? undefined : factory.createTempVariable(hoistVariableDeclaration);
if (temp) {
expression = factory.createAssignment(temp, expression);
setTextRange(temp, node);
}
expression = factory.createReflectSetCall(
superClassReference,
setterName,
expression,
classConstructor
);
setOriginalNode(expression, node);
setTextRange(expression, node);
if (temp) {
expression = factory.createComma(expression, temp);
setTextRange(expression, node);
}
return expression;
}
}
}
}
if (node.operatorToken.kind === SyntaxKind.InKeyword && isPrivateIdentifier(node.left)) {
return visitPrivateIdentifierInInExpression(node);
}
return visitEachChild(node, visitor, context);
}
function createPrivateIdentifierAssignment(info: PrivateIdentifierInfo, receiver: Expression, right: Expression, operator: AssignmentOperator): Expression {
receiver = visitNode(receiver, visitor, isExpression);
right = visitNode(right, visitor, isExpression);
if (isCompoundAssignment(operator)) {
const { readExpression, initializeExpression } = createCopiableReceiverExpr(receiver);
receiver = initializeExpression || readExpression;
right = factory.createBinaryExpression(
createPrivateIdentifierAccessHelper(info, readExpression),
getNonAssignmentOperatorForCompoundAssignment(operator),
right
);
}
setCommentRange(receiver, moveRangePos(receiver, -1));
switch(info.kind) {
case PrivateIdentifierKind.Accessor:
return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(
receiver,
info.brandCheckIdentifier,
right,
info.kind,
info.setterName
);
case PrivateIdentifierKind.Method:
return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(
receiver,
info.brandCheckIdentifier,
right,
info.kind,
/* f */ undefined
);
case PrivateIdentifierKind.Field:
return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(
receiver,
info.brandCheckIdentifier,
right,
info.kind,
info.variableName
);
default:
Debug.assertNever(info, "Unknown private element type");
}
}
/**
* Set up the environment for a class.
*/
function visitClassLike(node: ClassLikeDeclaration) {
if (!forEach(node.members, doesClassElementNeedTransform)) {
return visitEachChild(node, visitor, context);
}
const savedPendingExpressions = pendingExpressions;
pendingExpressions = undefined;
startClassLexicalEnvironment();
if (shouldTransformPrivateElementsOrClassStaticBlocks) {
const name = getNameOfDeclaration(node);
if (name && isIdentifier(name)) {
getPrivateIdentifierEnvironment().className = idText(name);
}
const privateInstanceMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node);
if (some(privateInstanceMethodsAndAccessors)) {
getPrivateIdentifierEnvironment().weakSetName = createHoistedVariableForClass(
"instances",
privateInstanceMethodsAndAccessors[0].name
);
}
}
const result = isClassDeclaration(node) ?
visitClassDeclaration(node) :
visitClassExpression(node);
endClassLexicalEnvironment();
pendingExpressions = savedPendingExpressions;
return result;
}
function doesClassElementNeedTransform(node: ClassElement) {
return isPropertyDeclaration(node) || isClassStaticBlockDeclaration(node) || (shouldTransformPrivateElementsOrClassStaticBlocks && node.name && isPrivateIdentifier(node.name));
}
function getPrivateInstanceMethodsAndAccessors(node: ClassLikeDeclaration) {
return filter(node.members, isNonStaticMethodOrAccessorWithPrivateName);
}
function getClassFacts(node: ClassLikeDeclaration) {
let facts = ClassFacts.None;
const original = getOriginalNode(node);
if (isClassDeclaration(original) && classOrConstructorParameterIsDecorated(original)) {
facts |= ClassFacts.ClassWasDecorated;
}
for (const member of node.members) {
if (!isStatic(member)) continue;
if (member.name && isPrivateIdentifier(member.name) && shouldTransformPrivateElementsOrClassStaticBlocks) {
facts |= ClassFacts.NeedsClassConstructorReference;
}
if (isPropertyDeclaration(member) || isClassStaticBlockDeclaration(member)) {
if (shouldTransformThisInStaticInitializers && member.transformFlags & TransformFlags.ContainsLexicalThis) {
facts |= ClassFacts.NeedsSubstitutionForThisInClassStaticField;
if (!(facts & ClassFacts.ClassWasDecorated)) {
facts |= ClassFacts.NeedsClassConstructorReference;
}
}
if (shouldTransformSuperInStaticInitializers && member.transformFlags & TransformFlags.ContainsLexicalSuper) {
if (!(facts & ClassFacts.ClassWasDecorated)) {
facts |= ClassFacts.NeedsClassConstructorReference | ClassFacts.NeedsClassSuperReference;
}
}
}
}
return facts;
}
function visitExpressionWithTypeArguments(node: ExpressionWithTypeArguments) {
const facts = currentClassLexicalEnvironment?.facts || ClassFacts.None;
if (facts & ClassFacts.NeedsClassSuperReference) {
const temp = factory.createTempVariable(hoistVariableDeclaration, /*reserveInNestedScopes*/ true);
getClassLexicalEnvironment().superClassReference = temp;
return factory.updateExpressionWithTypeArguments(
node,
factory.createAssignment(
temp,
visitNode(node.expression, visitor, isExpression)
),
/*typeArguments*/ undefined
);
}
return visitEachChild(node, visitor, context);
}
function visitClassDeclaration(node: ClassDeclaration) {
const facts = getClassFacts(node);
if (facts) {
getClassLexicalEnvironment().facts = facts;
}
if (facts & ClassFacts.NeedsSubstitutionForThisInClassStaticField) {
enableSubstitutionForClassStaticThisOrSuperReference();
}
const staticProperties = getStaticPropertiesAndClassStaticBlock(node);
// If a class has private static fields, or a static field has a `this` or `super` reference,
// then we need to allocate a temp variable to hold on to that reference.
let pendingClassReferenceAssignment: BinaryExpression | undefined;
if (facts & ClassFacts.NeedsClassConstructorReference) {
const temp = factory.createTempVariable(hoistVariableDeclaration, /*reservedInNestedScopes*/ true);
getClassLexicalEnvironment().classConstructor = factory.cloneNode(temp);
pendingClassReferenceAssignment = factory.createAssignment(temp, factory.getInternalName(node));
}
const extendsClauseElement = getEffectiveBaseTypeNode(node);
const isDerivedClass = !!(extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== SyntaxKind.NullKeyword);
const statements: Statement[] = [
factory.updateClassDeclaration(
node,
/*decorators*/ undefined,
node.modifiers,
node.name,
/*typeParameters*/ undefined,
visitNodes(node.heritageClauses, heritageClauseVisitor, isHeritageClause),
transformClassMembers(node, isDerivedClass)
)
];
if (pendingClassReferenceAssignment) {
getPendingExpressions().unshift(pendingClassReferenceAssignment);
}
// Write any pending expressions from elided or moved computed property names
if (some(pendingExpressions)) {
statements.push(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)));
}
// Emit static property assignment. Because classDeclaration is lexically evaluated,
// it is safe to emit static property assignment after classDeclaration
// From ES6 specification:
// HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using
// a lexical declaration such as a LexicalDeclaration or a ClassDeclaration.
if (some(staticProperties)) {
addPropertyOrClassStaticBlockStatements(statements, staticProperties, factory.getInternalName(node));
}
return statements;
}
function visitClassExpression(node: ClassExpression): Expression {
const facts = getClassFacts(node);
if (facts) {
getClassLexicalEnvironment().facts = facts;
}
if (facts & ClassFacts.NeedsSubstitutionForThisInClassStaticField) {
enableSubstitutionForClassStaticThisOrSuperReference();
}
// If this class expression is a transformation of a decorated class declaration,
// then we want to output the pendingExpressions as statements, not as inlined
// expressions with the class statement.
//
// In this case, we use pendingStatements to produce the same output as the
// class declaration transformation. The VariableStatement visitor will insert
// these statements after the class expression variable statement.
const isDecoratedClassDeclaration = !!(facts & ClassFacts.ClassWasDecorated);
const staticPropertiesOrClassStaticBlocks = getStaticPropertiesAndClassStaticBlock(node);
const extendsClauseElement = getEffectiveBaseTypeNode(node);
const isDerivedClass = !!(extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== SyntaxKind.NullKeyword);
const isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & NodeCheckFlags.ClassWithConstructorReference;
let temp: Identifier | undefined;
function createClassTempVar() {
const classCheckFlags = resolver.getNodeCheckFlags(node);
const isClassWithConstructorReference = classCheckFlags & NodeCheckFlags.ClassWithConstructorReference;
const requiresBlockScopedVar = classCheckFlags & NodeCheckFlags.BlockScopedBindingInLoop;
return factory.createTempVariable(requiresBlockScopedVar ? addBlockScopedVariable : hoistVariableDeclaration, !!isClassWithConstructorReference);
}
if (facts & ClassFacts.NeedsClassConstructorReference) {
temp = createClassTempVar();
getClassLexicalEnvironment().classConstructor = factory.cloneNode(temp);
}
const classExpression = factory.updateClassExpression(
node,
visitNodes(node.decorators, visitor, isDecorator),
node.modifiers,
node.name,
/*typeParameters*/ undefined,
visitNodes(node.heritageClauses, heritageClauseVisitor, isHeritageClause),
transformClassMembers(node, isDerivedClass)
);
const hasTransformableStatics = some(staticPropertiesOrClassStaticBlocks, p => isClassStaticBlockDeclaration(p) || !!p.initializer || (shouldTransformPrivateElementsOrClassStaticBlocks && isPrivateIdentifier(p.name)));
if (hasTransformableStatics || some(pendingExpressions)) {
if (isDecoratedClassDeclaration) {
Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration.");
// Write any pending expressions from elided or moved computed property names
if (pendingStatements && pendingExpressions && some(pendingExpressions)) {
pendingStatements.push(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)));
}
if (pendingStatements && some(staticPropertiesOrClassStaticBlocks)) {
addPropertyOrClassStaticBlockStatements(pendingStatements, staticPropertiesOrClassStaticBlocks, factory.getInternalName(node));
}
if (temp) {
return factory.inlineExpressions([factory.createAssignment(temp, classExpression), temp]);
}
return classExpression;
}
else {
const expressions: Expression[] = [];
temp ||= createClassTempVar();
if (isClassWithConstructorReference) {
// record an alias as the class name is not in scope for statics.
enableSubstitutionForClassAliases();
const alias = factory.cloneNode(temp) as GeneratedIdentifier;
alias.autoGenerateFlags &= ~GeneratedIdentifierFlags.ReservedInNestedScopes;
classAliases[getOriginalNodeId(node)] = alias;
}
// To preserve the behavior of the old emitter, we explicitly indent
// the body of a class with static initializers.
setEmitFlags(classExpression, EmitFlags.Indented | getEmitFlags(classExpression));
expressions.push(startOnNewLine(factory.createAssignment(temp, classExpression)));
// Add any pending expressions leftover from elided or relocated computed property names
addRange(expressions, map(pendingExpressions, startOnNewLine));
addRange(expressions, generateInitializedPropertyExpressionsOrClassStaticBlock(staticPropertiesOrClassStaticBlocks, temp));
expressions.push(startOnNewLine(temp));
return factory.inlineExpressions(expressions);
}
}
return classExpression;
}
function visitClassStaticBlockDeclaration(node: ClassStaticBlockDeclaration) {
if (!shouldTransformPrivateElementsOrClassStaticBlocks) {
return visitEachChild(node, classElementVisitor, context);
}
// ClassStaticBlockDeclaration for classes are transformed in `visitClassDeclaration` or `visitClassExpression`.
return undefined;
}
function transformClassMembers(node: ClassDeclaration | ClassExpression, isDerivedClass: boolean) {
if (shouldTransformPrivateElementsOrClassStaticBlocks) {
// Declare private names.
for (const member of node.members) {
if (isPrivateIdentifierClassElementDeclaration(member)) {
addPrivateIdentifierToEnvironment(member);
}
}
if (some(getPrivateInstanceMethodsAndAccessors(node))) {
createBrandCheckWeakSetForPrivateMethods();
}
}
const members: ClassElement[] = [];
const constructor = transformConstructor(node, isDerivedClass);
if (constructor) {
members.push(constructor);
}
addRange(members, visitNodes(node.members, classElementVisitor, isClassElement));
return setTextRange(factory.createNodeArray(members), /*location*/ node.members);
}
function createBrandCheckWeakSetForPrivateMethods() {
const { weakSetName } = getPrivateIdentifierEnvironment();
Debug.assert(weakSetName, "weakSetName should be set in private identifier environment");
getPendingExpressions().push(
factory.createAssignment(
weakSetName,
factory.createNewExpression(
factory.createIdentifier("WeakSet"),
/*typeArguments*/ undefined,
[]
)
)
);
}
function isClassElementThatRequiresConstructorStatement(member: ClassElement) {
if (isStatic(member) || hasSyntacticModifier(getOriginalNode(member), ModifierFlags.Abstract)) {
return false;
}
if (useDefineForClassFields) {
// If we are using define semantics and targeting ESNext or higher,
// then we don't need to transform any class properties.
return languageVersion < ScriptTarget.ES2022;
}
return isInitializedProperty(member) || shouldTransformPrivateElementsOrClassStaticBlocks && isPrivateIdentifierClassElementDeclaration(member);
}
function transformConstructor(node: ClassDeclaration | ClassExpression, isDerivedClass: boolean) {
const constructor = visitNode(getFirstConstructorWithBody(node), visitor, isConstructorDeclaration);
const elements = node.members.filter(isClassElementThatRequiresConstructorStatement);
if (!some(elements)) {
return constructor;
}
const parameters = visitParameterList(constructor ? constructor.parameters : undefined, visitor, context);
const body = transformConstructorBody(node, constructor, isDerivedClass);
if (!body) {
return undefined;
}
return startOnNewLine(
setOriginalNode(
setTextRange(
factory.createConstructorDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
parameters ?? [],
body
),
constructor || node
),
constructor
)
);
}
function transformConstructorBody(node: ClassDeclaration | ClassExpression, constructor: ConstructorDeclaration | undefined, isDerivedClass: boolean) {
let properties = getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false);
if (!useDefineForClassFields) {
properties = filter(properties, property => !!property.initializer || isPrivateIdentifier(property.name));
}
const privateMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node);
const needsConstructorBody = some(properties) || some(privateMethodsAndAccessors);
// Only generate synthetic constructor when there are property initializers to move.
if (!constructor && !needsConstructorBody) {
return visitFunctionBody(/*node*/ undefined, visitor, context);
}
resumeLexicalEnvironment();
let indexOfFirstStatement = 0;
let statements: Statement[] = [];
if (!constructor && isDerivedClass) {
// Add a synthetic `super` call:
//
// super(...arguments);
//
statements.push(
factory.createExpressionStatement(
factory.createCallExpression(
factory.createSuper(),
/*typeArguments*/ undefined,
[factory.createSpreadElement(factory.createIdentifier("arguments"))]
)
)
);
}
if (constructor) {
indexOfFirstStatement = addPrologueDirectivesAndInitialSuperCall(factory, constructor, statements, visitor);
}
// Add the property initializers. Transforms this:
//
// public x = 1;
//
// Into this:
//
// constructor() {
// this.x = 1;
// }
//
if (constructor?.body) {
let afterParameterProperties = findIndex(constructor.body.statements, s => !isParameterPropertyDeclaration(getOriginalNode(s), constructor), indexOfFirstStatement);
if (afterParameterProperties === -1) {
afterParameterProperties = constructor.body.statements.length;
}
if (afterParameterProperties > indexOfFirstStatement) {
if (!useDefineForClassFields) {
addRange(statements, visitNodes(constructor.body.statements, visitor, isStatement, indexOfFirstStatement, afterParameterProperties - indexOfFirstStatement));
}
indexOfFirstStatement = afterParameterProperties;
}
}
const receiver = factory.createThis();
// private methods can be called in property initializers, they should execute first.
addMethodStatements(statements, privateMethodsAndAccessors, receiver);
addPropertyOrClassStaticBlockStatements(statements, properties, receiver);
// Add existing statements, skipping the initial super call.
if (constructor) {
addRange(statements, visitNodes(constructor.body!.statements, visitor, isStatement, indexOfFirstStatement));
}
statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment());
return setTextRange(
factory.createBlock(
setTextRange(
factory.createNodeArray(statements),
/*location*/ constructor ? constructor.body!.statements : node.members
),
/*multiLine*/ true
),
/*location*/ constructor ? constructor.body : undefined
);
}
/**
* Generates assignment statements for property initializers.
*
* @param properties An array of property declarations to transform.
* @param receiver The receiver on which each property should be assigned.
*/
function addPropertyOrClassStaticBlockStatements(statements: Statement[], properties: readonly (PropertyDeclaration | ClassStaticBlockDeclaration)[], receiver: LeftHandSideExpression) {
for (const property of properties) {
const expression = isClassStaticBlockDeclaration(property) ?
transformClassStaticBlockDeclaration(property) :
transformProperty(property, receiver);
if (!expression) {
continue;
}
const statement = factory.createExpressionStatement(expression);
setSourceMapRange(statement, moveRangePastModifiers(property));
setCommentRange(statement, property);
setOriginalNode(statement, property);
statements.push(statement);
}
}
/**
* Generates assignment expressions for property initializers.
*
* @param propertiesOrClassStaticBlocks An array of property declarations to transform.
* @param receiver The receiver on which each property should be assigned.
*/
function generateInitializedPropertyExpressionsOrClassStaticBlock(propertiesOrClassStaticBlocks: readonly (PropertyDeclaration | ClassStaticBlockDeclaration)[], receiver: LeftHandSideExpression) {
const expressions: Expression[] = [];
for (const property of propertiesOrClassStaticBlocks) {
const expression = isClassStaticBlockDeclaration(property) ? transformClassStaticBlockDeclaration(property) : transformProperty(property, receiver);
if (!expression) {
continue;
}
startOnNewLine(expression);
setSourceMapRange(expression, moveRangePastModifiers(property));
setCommentRange(expression, property);
setOriginalNode(expression, property);
expressions.push(expression);
}
return expressions;
}
/**
* Transforms a property initializer into an assignment statement.
*
* @param property The property declaration.
* @param receiver The object receiving the property assignment.
*/
function transformProperty(property: PropertyDeclaration, receiver: LeftHandSideExpression) {
const savedCurrentStaticPropertyDeclarationOrStaticBlock = currentStaticPropertyDeclarationOrStaticBlock;
const transformed = transformPropertyWorker(property, receiver);
if (transformed && hasStaticModifier(property) && currentClassLexicalEnvironment?.facts) {
// capture the lexical environment for the member
setOriginalNode(transformed, property);
addEmitFlags(transformed, EmitFlags.AdviseOnEmitNode);
classLexicalEnvironmentMap.set(getOriginalNodeId(transformed), currentClassLexicalEnvironment);
}
currentStaticPropertyDeclarationOrStaticBlock = savedCurrentStaticPropertyDeclarationOrStaticBlock;
return transformed;
}
function transformPropertyWorker(property: PropertyDeclaration, receiver: LeftHandSideExpression) {
// We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name)
const emitAssignment = !useDefineForClassFields;
const propertyName = isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression)
? factory.updateComputedPropertyName(property.name, factory.getGeneratedNameForNode(property.name))
: property.name;
if (hasStaticModifier(property)) {
currentStaticPropertyDeclarationOrStaticBlock = property;
}
if (shouldTransformPrivateElementsOrClassStaticBlocks && isPrivateIdentifier(propertyName)) {
const privateIdentifierInfo = accessPrivateIdentifier(propertyName);
if (privateIdentifierInfo) {
if (privateIdentifierInfo.kind === PrivateIdentifierKind.Field) {
if (!privateIdentifierInfo.isStatic) {
return createPrivateInstanceFieldInitializer(
receiver,
visitNode(property.initializer, visitor, isExpression),
privateIdentifierInfo.brandCheckIdentifier
);
}
else {
return createPrivateStaticFieldInitializer(
privateIdentifierInfo.variableName,
visitNode(property.initializer, visitor, isExpression)
);
}
}
else {
return undefined;
}
}
else {
Debug.fail("Undeclared private name for property declaration.");
}
}
if ((isPrivateIdentifier(propertyName) || hasStaticModifier(property)) && !property.initializer) {
return undefined;
}
const propertyOriginalNode = getOriginalNode(property);
if (hasSyntacticModifier(propertyOriginalNode, ModifierFlags.Abstract)) {
return undefined;
}
const initializer = property.initializer || emitAssignment ? visitNode(property.initializer, visitor, isExpression) ?? factory.createVoidZero()
: isParameterPropertyDeclaration(propertyOriginalNode, propertyOriginalNode.parent) && isIdentifier(propertyName) ? propertyName
: factory.createVoidZero();
if (emitAssignment || isPrivateIdentifier(propertyName)) {
const memberAccess = createMemberAccessForPropertyName(factory, receiver, propertyName, /*location*/ propertyName);
return factory.createAssignment(memberAccess, initializer);
}
else {
const name = isComputedPropertyName(propertyName) ? propertyName.expression
: isIdentifier(propertyName) ? factory.createStringLiteral(unescapeLeadingUnderscores(propertyName.escapedText))
: propertyName;
const descriptor = factory.createPropertyDescriptor({ value: initializer, configurable: true, writable: true, enumerable: true });
return factory.createObjectDefinePropertyCall(receiver, name, descriptor);
}
}
function enableSubstitutionForClassAliases() {
if ((enabledSubstitutions & ClassPropertySubstitutionFlags.ClassAliases) === 0) {
enabledSubstitutions |= ClassPropertySubstitutionFlags.ClassAliases;
// We need to enable substitutions for identifiers. This allows us to
// substitute class names inside of a class declaration.
context.enableSubstitution(SyntaxKind.Identifier);
// Keep track of class aliases.
classAliases = [];
}
}
function enableSubstitutionForClassStaticThisOrSuperReference() {
if ((enabledSubstitutions & ClassPropertySubstitutionFlags.ClassStaticThisOrSuperReference) === 0) {
enabledSubstitutions |= ClassPropertySubstitutionFlags.ClassStaticThisOrSuperReference;
// substitute `this` in a static field initializer
context.enableSubstitution(SyntaxKind.ThisKeyword);
// these push a new lexical environment that is not the class lexical environment
context.enableEmitNotification(SyntaxKind.FunctionDeclaration);
context.enableEmitNotification(SyntaxKind.FunctionExpression);
context.enableEmitNotification(SyntaxKind.Constructor);
// these push a new lexical environment that is not the class lexical environment, except
// when they have a computed property name
context.enableEmitNotification(SyntaxKind.GetAccessor);
context.enableEmitNotification(SyntaxKind.SetAccessor);
context.enableEmitNotification(SyntaxKind.MethodDeclaration);
context.enableEmitNotification(SyntaxKind.PropertyDeclaration);
// class lexical environments are restored when entering a computed property name
context.enableEmitNotification(SyntaxKind.ComputedPropertyName);
}
}
/**
* Generates brand-check initializer for private methods.
*
* @param statements Statement list that should be used to append new statements.
* @param methods An array of method declarations.
* @param receiver The receiver on which each method should be assigned.
*/
function addMethodStatements(statements: Statement[], methods: readonly (MethodDeclaration | AccessorDeclaration)[], receiver: LeftHandSideExpression) {
if (!shouldTransformPrivateElementsOrClassStaticBlocks || !some(methods)) {
return;
}
const { weakSetName } = getPrivateIdentifierEnvironment();
Debug.assert(weakSetName, "weakSetName should be set in private identifier environment");
statements.push(
factory.createExpressionStatement(
createPrivateInstanceMethodInitializer(receiver, weakSetName)
)
);
}
function visitInvalidSuperProperty(node: SuperProperty) {
return isPropertyAccessExpression(node) ?
factory.updatePropertyAccessExpression(
node,
factory.createVoidZero(),
node.name) :
factory.updateElementAccessExpression(
node,
factory.createVoidZero(),
visitNode(node.argumentExpression, visitor, isExpression));
}
function onEmitNode(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void) {
const original = getOriginalNode(node);
if (original.id) {
const classLexicalEnvironment = classLexicalEnvironmentMap.get(original.id);
if (classLexicalEnvironment) {
const savedClassLexicalEnvironment = currentClassLexicalEnvironment;
const savedCurrentComputedPropertyNameClassLexicalEnvironment = currentComputedPropertyNameClassLexicalEnvironment;
currentClassLexicalEnvironment = classLexicalEnvironment;
currentComputedPropertyNameClassLexicalEnvironment = classLexicalEnvironment;
previousOnEmitNode(hint, node, emitCallback);
currentClassLexicalEnvironment = savedClassLexicalEnvironment;
currentComputedPropertyNameClassLexicalEnvironment = savedCurrentComputedPropertyNameClassLexicalEnvironment;
return;
}
}
switch (node.kind) {
case SyntaxKind.FunctionExpression:
if (isArrowFunction(original) || getEmitFlags(node) & EmitFlags.AsyncFunctionBody) {
break;
}
// falls through
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.Constructor: {
const savedClassLexicalEnvironment = currentClassLexicalEnvironment;
const savedCurrentComputedPropertyNameClassLexicalEnvironment = currentComputedPropertyNameClassLexicalEnvironment;
currentClassLexicalEnvironment = undefined;
currentComputedPropertyNameClassLexicalEnvironment = undefined;
previousOnEmitNode(hint, node, emitCallback);
currentClassLexicalEnvironment = savedClassLexicalEnvironment;
currentComputedPropertyNameClassLexicalEnvironment = savedCurrentComputedPropertyNameClassLexicalEnvironment;
return;
}
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.PropertyDeclaration: {
const savedClassLexicalEnvironment = currentClassLexicalEnvironment;
const savedCurrentComputedPropertyNameClassLexicalEnvironment = currentComputedPropertyNameClassLexicalEnvironment;
currentComputedPropertyNameClassLexicalEnvironment = currentClassLexicalEnvironment;
currentClassLexicalEnvironment = undefined;
previousOnEmitNode(hint, node, emitCallback);
currentClassLexicalEnvironment = savedClassLexicalEnvironment;
currentComputedPropertyNameClassLexicalEnvironment = savedCurrentComputedPropertyNameClassLexicalEnvironment;
return;
}
case SyntaxKind.ComputedPropertyName: {
const savedClassLexicalEnvironment = currentClassLexicalEnvironment;
const savedCurrentComputedPropertyNameClassLexicalEnvironment = currentComputedPropertyNameClassLexicalEnvironment;
currentClassLexicalEnvironment = currentComputedPropertyNameClassLexicalEnvironment;
currentComputedPropertyNameClassLexicalEnvironment = undefined;
previousOnEmitNode(hint, node, emitCallback);
currentClassLexicalEnvironment = savedClassLexicalEnvironment;
currentComputedPropertyNameClassLexicalEnvironment = savedCurrentComputedPropertyNameClassLexicalEnvironment;
return;
}
}
previousOnEmitNode(hint, node, emitCallback);
}
/**
* Hooks node substitutions.
*
* @param hint The context for the emitter.
* @param node The node to substitute.
*/
function onSubstituteNode(hint: EmitHint, node: Node) {
node = previousOnSubstituteNode(hint, node);
if (hint === EmitHint.Expression) {
return substituteExpression(node as Expression);
}
return node;
}
function substituteExpression(node: Expression) {
switch (node.kind) {
case SyntaxKind.Identifier:
return substituteExpressionIdentifier(node as Identifier);
case SyntaxKind.ThisKeyword:
return substituteThisExpression(node as ThisExpression);
}
return node;
}
function substituteThisExpression(node: ThisExpression) {
if (enabledSubstitutions & ClassPropertySubstitutionFlags.ClassStaticThisOrSuperReference && currentClassLexicalEnvironment) {
const { facts, classConstructor } = currentClassLexicalEnvironment;
if (facts & ClassFacts.ClassWasDecorated) {
return factory.createParenthesizedExpression(factory.createVoidZero());
}
if (classConstructor) {
return setTextRange(
setOriginalNode(
factory.cloneNode(classConstructor),
node,
),
node
);
}
}
return node;
}
function substituteExpressionIdentifier(node: Identifier): Expression {
return trySubstituteClassAlias(node) || node;
}
function trySubstituteClassAlias(node: Identifier): Expression | undefined {
if (enabledSubstitutions & ClassPropertySubstitutionFlags.ClassAliases) {
if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.ConstructorReferenceInClass) {
// Due to the emit for class decorators, any reference to the class from inside of the class body
// must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
// behavior of class names in ES6.
// Also, when emitting statics for class expressions, we must substitute a class alias for
// constructor references in static property initializers.
const declaration = resolver.getReferencedValueDeclaration(node);
if (declaration) {
const classAlias = classAliases[declaration.id!]; // TODO: GH#18217
if (classAlias) {
const clone = factory.cloneNode(classAlias);
setSourceMapRange(clone, node);
setCommentRange(clone, node);
return clone;
}
}
}
}
return undefined;
}
/**
* If the name is a computed property, this function transforms it, then either returns an expression which caches the
* value of the result or the expression itself if the value is either unused or safe to inline into multiple locations
* @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator)
*/
function getPropertyNameExpressionIfNeeded(name: PropertyName, shouldHoist: boolean): Expression | undefined {
if (isComputedPropertyName(name)) {
const expression = visitNode(name.expression, visitor, isExpression);
const innerExpression = skipPartiallyEmittedExpressions(expression);
const inlinable = isSimpleInlineableExpression(innerExpression);
const alreadyTransformed = isAssignmentExpression(innerExpression) && isGeneratedIdentifier(innerExpression.left);
if (!alreadyTransformed && !inlinable && shouldHoist) {
const generatedName = factory.getGeneratedNameForNode(name);
if (resolver.getNodeCheckFlags(name) & NodeCheckFlags.BlockScopedBindingInLoop) {
addBlockScopedVariable(generatedName);
}
else {
hoistVariableDeclaration(generatedName);
}
return factory.createAssignment(generatedName, expression);
}
return (inlinable || isIdentifier(innerExpression)) ? undefined : expression;
}
}
function startClassLexicalEnvironment() {
classLexicalEnvironmentStack.push(currentClassLexicalEnvironment);
currentClassLexicalEnvironment = undefined;
}
function endClassLexicalEnvironment() {
currentClassLexicalEnvironment = classLexicalEnvironmentStack.pop();
}
function getClassLexicalEnvironment() {
return currentClassLexicalEnvironment ||= {
facts: ClassFacts.None,
classConstructor: undefined,
superClassReference: undefined,
privateIdentifierEnvironment: undefined,
};
}
function getPrivateIdentifierEnvironment() {
const lex = getClassLexicalEnvironment();
lex.privateIdentifierEnvironment ||= {
className: "",
identifiers: new Map()
};
return lex.privateIdentifierEnvironment;
}
function getPendingExpressions() {
return pendingExpressions || (pendingExpressions = []);
}
function addPrivateIdentifierToEnvironment(node: PrivateClassElementDeclaration) {
const text = getTextOfPropertyName(node.name) as string;
const lex = getClassLexicalEnvironment();
const { classConstructor } = lex;
const privateEnv = getPrivateIdentifierEnvironment();
const { weakSetName } = privateEnv;
const assignmentExpressions: Expression[] = [];
const privateName = node.name.escapedText;
const previousInfo = privateEnv.identifiers.get(privateName);
const isValid = !isReservedPrivateName(node.name) && previousInfo === undefined;
if (hasStaticModifier(node)) {
Debug.assert(classConstructor, "weakSetName should be set in private identifier environment");
if (isPropertyDeclaration(node)) {
const variableName = createHoistedVariableForPrivateName(text, node);
privateEnv.identifiers.set(privateName, {
kind: PrivateIdentifierKind.Field,
variableName,
brandCheckIdentifier: classConstructor,
isStatic: true,
isValid,
});
}
else if (isMethodDeclaration(node)) {
const functionName = createHoistedVariableForPrivateName(text, node);
privateEnv.identifiers.set(privateName, {
kind: PrivateIdentifierKind.Method,
methodName: functionName,
brandCheckIdentifier: classConstructor,
isStatic: true,
isValid,
});
}
else if (isGetAccessorDeclaration(node)) {
const getterName = createHoistedVariableForPrivateName(text + "_get", node);
if (previousInfo?.kind === PrivateIdentifierKind.Accessor && previousInfo.isStatic && !previousInfo.getterName) {
previousInfo.getterName = getterName;
}
else {
privateEnv.identifiers.set(privateName, {
kind: PrivateIdentifierKind.Accessor,
getterName,
setterName: undefined,
brandCheckIdentifier: classConstructor,
isStatic: true,
isValid,
});
}
}
else if (isSetAccessorDeclaration(node)) {
const setterName = createHoistedVariableForPrivateName(text + "_set", node);
if (previousInfo?.kind === PrivateIdentifierKind.Accessor && previousInfo.isStatic && !previousInfo.setterName) {
previousInfo.setterName = setterName;
}
else {
privateEnv.identifiers.set(privateName, {
kind: PrivateIdentifierKind.Accessor,
getterName: undefined,
setterName,
brandCheckIdentifier: classConstructor,
isStatic: true,
isValid,
});
}
}
else {
Debug.assertNever(node, "Unknown class element type.");
}
}
else if (isPropertyDeclaration(node)) {
const weakMapName = createHoistedVariableForPrivateName(text, node);
privateEnv.identifiers.set(privateName, {
kind: PrivateIdentifierKind.Field,
brandCheckIdentifier: weakMapName,
isStatic: false,
variableName: undefined,
isValid,
});
assignmentExpressions.push(factory.createAssignment(
weakMapName,
factory.createNewExpression(
factory.createIdentifier("WeakMap"),
/*typeArguments*/ undefined,
[]
)
));
}
else if (isMethodDeclaration(node)) {
Debug.assert(weakSetName, "weakSetName should be set in private identifier environment");
privateEnv.identifiers.set(privateName, {
kind: PrivateIdentifierKind.Method,
methodName: createHoistedVariableForPrivateName(text, node),
brandCheckIdentifier: weakSetName,
isStatic: false,
isValid,
});
}
else if (isAccessor(node)) {
Debug.assert(weakSetName, "weakSetName should be set in private identifier environment");
if (isGetAccessor(node)) {
const getterName = createHoistedVariableForPrivateName(text + "_get", node);
if (previousInfo?.kind === PrivateIdentifierKind.Accessor && !previousInfo.isStatic && !previousInfo.getterName) {
previousInfo.getterName = getterName;
}
else {
privateEnv.identifiers.set(privateName, {
kind: PrivateIdentifierKind.Accessor,
getterName,
setterName: undefined,
brandCheckIdentifier: weakSetName,
isStatic: false,
isValid,
});
}
}
else {
const setterName = createHoistedVariableForPrivateName(text + "_set", node);
if (previousInfo?.kind === PrivateIdentifierKind.Accessor && !previousInfo.isStatic && !previousInfo.setterName) {
previousInfo.setterName = setterName;
}
else {
privateEnv.identifiers.set(privateName, {
kind: PrivateIdentifierKind.Accessor,
getterName: undefined,
setterName,
brandCheckIdentifier: weakSetName,
isStatic: false,
isValid,
});
}
}
}
else {
Debug.assertNever(node, "Unknown class element type.");
}
getPendingExpressions().push(...assignmentExpressions);
}
function createHoistedVariableForClass(name: string, node: PrivateIdentifier | ClassStaticBlockDeclaration): Identifier {
const { className } = getPrivateIdentifierEnvironment();
const prefix = className ? `_${className}` : "";
const identifier = factory.createUniqueName(`${prefix}_${name}`, GeneratedIdentifierFlags.Optimistic);
if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.BlockScopedBindingInLoop) {
addBlockScopedVariable(identifier);
}
else {
hoistVariableDeclaration(identifier);
}
return identifier;
}
function createHoistedVariableForPrivateName(privateName: string, node: PrivateClassElementDeclaration): Identifier {
return createHoistedVariableForClass(privateName.substring(1), node.name);
}
function accessPrivateIdentifier(name: PrivateIdentifier) {
if (currentClassLexicalEnvironment?.privateIdentifierEnvironment) {
const info = currentClassLexicalEnvironment.privateIdentifierEnvironment.identifiers.get(name.escapedText);
if (info) {
return info;
}
}
for (let i = classLexicalEnvironmentStack.length - 1; i >= 0; --i) {
const env = classLexicalEnvironmentStack[i];
if (!env) {
continue;
}
const info = env.privateIdentifierEnvironment?.identifiers.get(name.escapedText);
if (info) {
return info;
}
}
return undefined;
}
function wrapPrivateIdentifierForDestructuringTarget(node: PrivateIdentifierPropertyAccessExpression) {
const parameter = factory.getGeneratedNameForNode(node);
const info = accessPrivateIdentifier(node.name);
if (!info) {
return visitEachChild(node, visitor, context);
}
let receiver = node.expression;
// We cannot copy `this` or `super` into the function because they will be bound
// differently inside the function.
if (isThisProperty(node) || isSuperProperty(node) || !isSimpleCopiableExpression(node.expression)) {
receiver = factory.createTempVariable(hoistVariableDeclaration, /*reservedInNestedScopes*/ true);
getPendingExpressions().push(factory.createBinaryExpression(receiver, SyntaxKind.EqualsToken, visitNode(node.expression, visitor, isExpression)));
}
return factory.createAssignmentTargetWrapper(
parameter,
createPrivateIdentifierAssignment(
info,
receiver,
parameter,
SyntaxKind.EqualsToken
)
);
}
function visitArrayAssignmentTarget(node: BindingOrAssignmentElement) {
const target = getTargetOfBindingOrAssignmentElement(node);
if (target) {
let wrapped: LeftHandSideExpression | undefined;
if (isPrivateIdentifierPropertyAccessExpression(target)) {
wrapped = wrapPrivateIdentifierForDestructuringTarget(target);
}
else if (shouldTransformSuperInStaticInitializers &&
isSuperProperty(target) &&
currentStaticPropertyDeclarationOrStaticBlock &&
currentClassLexicalEnvironment) {
const { classConstructor, superClassReference, facts } = currentClassLexicalEnvironment;
if (facts & ClassFacts.ClassWasDecorated) {
wrapped = visitInvalidSuperProperty(target);
}
else if (classConstructor && superClassReference) {
const name =
isElementAccessExpression(target) ? visitNode(target.argumentExpression, visitor, isExpression) :
isIdentifier(target.name) ? factory.createStringLiteralFromNode(target.name) :
undefined;
if (name) {
const temp = factory.createTempVariable(/*recordTempVariable*/ undefined);
wrapped = factory.createAssignmentTargetWrapper(
temp,
factory.createReflectSetCall(
superClassReference,
name,
temp,
classConstructor,
)
);
}
}
}
if (wrapped) {
if (isAssignmentExpression(node)) {
return factory.updateBinaryExpression(
node,
wrapped,
node.operatorToken,
visitNode(node.right, visitor, isExpression)
);
}
else if (isSpreadElement(node)) {
return factory.updateSpreadElement(node, wrapped);
}
else {
return wrapped;
}
}
}
return visitNode(node, visitorDestructuringTarget);
}
function visitObjectAssignmentTarget(node: ObjectLiteralElementLike) {
if (isObjectBindingOrAssignmentElement(node) && !isShorthandPropertyAssignment(node)) {
const target = getTargetOfBindingOrAssignmentElement(node);
let wrapped: LeftHandSideExpression | undefined;
if (target) {
if (isPrivateIdentifierPropertyAccessExpression(target)) {
wrapped = wrapPrivateIdentifierForDestructuringTarget(target);
}
else if (shouldTransformSuperInStaticInitializers &&
isSuperProperty(target) &&
currentStaticPropertyDeclarationOrStaticBlock &&
currentClassLexicalEnvironment) {
const { classConstructor, superClassReference, facts } = currentClassLexicalEnvironment;
if (facts & ClassFacts.ClassWasDecorated) {
wrapped = visitInvalidSuperProperty(target);
}
else if (classConstructor && superClassReference) {
const name =
isElementAccessExpression(target) ? visitNode(target.argumentExpression, visitor, isExpression) :
isIdentifier(target.name) ? factory.createStringLiteralFromNode(target.name) :
undefined;
if (name) {
const temp = factory.createTempVariable(/*recordTempVariable*/ undefined);
wrapped = factory.createAssignmentTargetWrapper(
temp,
factory.createReflectSetCall(
superClassReference,
name,
temp,
classConstructor,
)
);
}
}
}
}
if (isPropertyAssignment(node)) {
const initializer = getInitializerOfBindingOrAssignmentElement(node);
return factory.updatePropertyAssignment(
node,
visitNode(node.name, visitor, isPropertyName),
wrapped ?
initializer ? factory.createAssignment(wrapped, visitNode(initializer, visitor)) : wrapped :
visitNode(node.initializer, visitorDestructuringTarget, isExpression)
);
}
if (isSpreadAssignment(node)) {
return factory.updateSpreadAssignment(
node,
wrapped || visitNode(node.expression, visitorDestructuringTarget, isExpression)
);
}
Debug.assert(wrapped === undefined, "Should not have generated a wrapped target");
}
return visitNode(node, visitor);
}
function visitAssignmentPattern(node: AssignmentPattern) {
if (isArrayLiteralExpression(node)) {
// Transforms private names in destructuring assignment array bindings.
// Transforms SuperProperty assignments in destructuring assignment array bindings in static initializers.
//
// Source:
// ([ this.#myProp ] = [ "hello" ]);
//
// Transformation:
// [ { set value(x) { this.#myProp = x; } }.value ] = [ "hello" ];
return factory.updateArrayLiteralExpression(
node,
visitNodes(node.elements, visitArrayAssignmentTarget, isExpression)
);
}
else {
// Transforms private names in destructuring assignment object bindings.
// Transforms SuperProperty assignments in destructuring assignment object bindings in static initializers.
//
// Source:
// ({ stringProperty: this.#myProp } = { stringProperty: "hello" });
//
// Transformation:
// ({ stringProperty: { set value(x) { this.#myProp = x; } }.value }) = { stringProperty: "hello" };
return factory.updateObjectLiteralExpression(
node,
visitNodes(node.properties, visitObjectAssignmentTarget, isObjectLiteralElementLike)
);
}
}
}
function createPrivateStaticFieldInitializer(variableName: Identifier, initializer: Expression | undefined) {
return factory.createAssignment(
variableName,
factory.createObjectLiteralExpression([
factory.createPropertyAssignment("value", initializer || factory.createVoidZero())
])
);
}
function createPrivateInstanceFieldInitializer(receiver: LeftHandSideExpression, initializer: Expression | undefined, weakMapName: Identifier) {
return factory.createCallExpression(
factory.createPropertyAccessExpression(weakMapName, "set"),
/*typeArguments*/ undefined,
[receiver, initializer || factory.createVoidZero()]
);
}
function createPrivateInstanceMethodInitializer(receiver: LeftHandSideExpression, weakSetName: Identifier) {
return factory.createCallExpression(
factory.createPropertyAccessExpression(weakSetName, "add"),
/*typeArguments*/ undefined,
[receiver]
);
}
function isReservedPrivateName(node: PrivateIdentifier) {
return node.escapedText === "#constructor";
}
} | the_stack |
import {
bytes16,
bytes24,
bytes32,
bytesF32,
bytesF64,
} from "@thi.ng/binary/bytes";
import { unsupported } from "@thi.ng/errors/unsupported";
import type { Reducer, Transducer } from "@thi.ng/transducers";
import { iterator } from "@thi.ng/transducers/iterator";
import { mapcat } from "@thi.ng/transducers/mapcat";
import { reduce } from "@thi.ng/transducers/reduce";
import type { BinStructItem } from "./api.js";
import { utf8Encode } from "./utf8.js";
export const i8 = (x: number): BinStructItem => ["i8", x];
export const i8array = (x: ArrayLike<number>): BinStructItem => ["i8a", x];
export const u8 = (x: number): BinStructItem => ["u8", x];
export const u8array = (x: ArrayLike<number>): BinStructItem => ["u8a", x];
export const i16 = (x: number, le = false): BinStructItem => ["i16", x, le];
export const i16array = (x: ArrayLike<number>, le = false): BinStructItem => [
"i16a",
x,
le,
];
export const u16 = (x: number, le = false): BinStructItem => ["u16", x, le];
export const u16array = (x: ArrayLike<number>, le = false): BinStructItem => [
"u16a",
x,
le,
];
export const i24 = (x: number, le = false): BinStructItem => ["i24", x, le];
export const i24array = (x: ArrayLike<number>, le = false): BinStructItem => [
"i24a",
x,
le,
];
export const u24 = (x: number, le = false): BinStructItem => ["u24", x, le];
export const u24array = (x: ArrayLike<number>, le = false): BinStructItem => [
"u24a",
x,
le,
];
export const i32 = (x: number, le = false): BinStructItem => ["i32", x, le];
export const i32array = (x: ArrayLike<number>, le = false): BinStructItem => [
"i32a",
x,
le,
];
export const u32 = (x: number, le = false): BinStructItem => ["u32", x, le];
export const u32array = (x: ArrayLike<number>, le = false): BinStructItem => [
"u32a",
x,
le,
];
export const f32 = (x: number, le = false): BinStructItem => ["f32", x, le];
export const f32array = (x: ArrayLike<number>, le = false): BinStructItem => [
"f32a",
x,
le,
];
export const f64 = (x: number, le = false): BinStructItem => ["f64", x, le];
export const f64array = (x: ArrayLike<number>, le = false): BinStructItem => [
"f64a",
x,
le,
];
export const str = (x: string): BinStructItem => ["str", x];
/**
* Transducer which converts {@link BinStructItem} inputs to bytes. If
* `src` iterable is given, yields an iterator of unsigned bytes (e.g.
* for streaming purposes).
*
* @example
* ```ts
* hexDumpString({}, asBytes([
* str("hello!"),
* u32(0xdecafbad),
* i16(-1),
* f32(Math.PI)
* ]))
* // 00000000 | 68 65 6c 6c 6f 21 de ca fb ad ff ff 40 49 0f db | hello!......@I..
* ```
*/
export function asBytes(): Transducer<BinStructItem, number>;
export function asBytes(src: Iterable<BinStructItem>): Iterable<number>;
export function asBytes(src?: Iterable<BinStructItem>): any {
return src
? iterator(asBytes(), src)
: mapcat((x: BinStructItem) => {
const val = <number>x[1];
const le = x[2];
switch (x[0]) {
case "i8":
case "u8":
return [val];
case "i8a":
case "u8a":
return <number[]>x[1];
case "i16":
case "u16":
return bytes16(val, le);
case "i16a":
case "u16a":
return mapcat((x) => bytes16(x, le), <number[]>x[1]);
case "i24":
case "u24":
return bytes24(val, le);
case "i24a":
case "u24a":
return mapcat((x) => bytes24(x, le), <number[]>x[1]);
case "i32":
case "u32":
return bytes32(val, le);
case "i32a":
case "u32a":
return mapcat((x) => bytes32(x, le), <number[]>x[1]);
case "f32":
return bytesF32(val, le);
case "f32a":
return mapcat((x) => bytesF32(x, le), <number[]>x[1]);
case "f64":
return bytesF64(val, le);
case "f64a":
return mapcat((x) => bytesF64(x, le), <number[]>x[1]);
case "str":
return utf8Encode(<string>x[1]);
default:
unsupported(`invalid struct item: ${x[0]}`);
}
});
}
export function bytes(cap?: number): Reducer<Uint8Array, BinStructItem>;
export function bytes(cap: number, src: Iterable<BinStructItem>): Uint8Array;
export function bytes(cap = 1024, src?: Iterable<BinStructItem>) {
let view: DataView;
let pos = 0;
const ensure = (acc: Uint8Array, size: number) => {
if (pos + size <= cap) return acc;
cap *= 2;
const buf = new Uint8Array(cap);
buf.set(acc);
view = new DataView(buf.buffer);
return buf;
};
const setArray = (
fn: string,
stride: number,
acc: Uint8Array,
x: any,
le: boolean
) => {
const n = x.length;
acc = ensure(acc, stride * n);
for (let i = 0; i < n; i++, pos += stride) {
(<any>view)[fn](pos, x[i], le);
}
return acc;
};
return src
? reduce(bytes(cap), src)
: <Reducer<Uint8Array, BinStructItem>>[
() => new Uint8Array(cap),
(acc) => acc.subarray(0, pos),
(acc, [type, x, le = false]) => {
if (!view || view.buffer !== acc.buffer) {
cap = acc.byteLength;
view = new DataView(acc.buffer, acc.byteOffset);
}
switch (type) {
case "i8":
acc = ensure(acc, 1);
view.setInt8(pos, <number>x);
pos++;
break;
case "i8a": {
const n = (<ArrayLike<number>>x).length;
acc = ensure(acc, n);
new Int8Array(acc.buffer, acc.byteOffset).set(
<ArrayLike<number>>x,
pos
);
pos += n;
break;
}
case "u8":
acc = ensure(acc, 1);
view.setUint8(pos, <number>x);
pos++;
break;
case "u8a": {
const n = (<ArrayLike<number>>x).length;
acc = ensure(acc, n);
acc.set(<ArrayLike<number>>x, pos);
pos += n;
break;
}
case "i16":
acc = ensure(acc, 2);
view.setInt16(pos, <number>x, le);
pos += 2;
break;
case "i16a":
acc = setArray("setInt16", 2, acc, x, le);
break;
case "u16":
acc = ensure(acc, 2);
view.setUint16(pos, <number>x, le);
pos += 2;
break;
case "u16a":
acc = setArray("setUint16", 2, acc, x, le);
break;
case "i24":
acc = ensure(acc, 4);
view.setInt32(pos, <number>x, le);
pos += 3;
break;
case "i24a":
acc = setArray("setInt32", 3, acc, x, le);
break;
case "u24":
acc = ensure(acc, 4);
view.setUint32(pos, <number>x, le);
pos += 3;
break;
case "u24a":
acc = setArray("setUint32", 3, acc, x, le);
break;
case "i32":
acc = ensure(acc, 4);
view.setInt32(pos, <number>x, le);
pos += 4;
break;
case "i32a":
acc = setArray("setInt32", 4, acc, x, le);
break;
case "u32":
acc = ensure(acc, 4);
view.setUint32(pos, <number>x, le);
pos += 4;
break;
case "u32a":
acc = setArray("setUint32", 4, acc, x, le);
break;
case "f32":
acc = ensure(acc, 4);
view.setFloat32(pos, <number>x, le);
pos += 4;
break;
case "f32a":
acc = setArray("setFloat32", 4, acc, x, le);
break;
case "f64":
acc = ensure(acc, 8);
view.setFloat64(pos, <number>x, le);
pos += 8;
break;
case "f64a":
acc = setArray("setFloat64", 8, acc, x, le);
break;
case "str": {
let utf = utf8Encode(<string>x);
acc = ensure(acc, utf.length);
acc.set(utf, pos);
pos += utf.length;
break;
}
default:
}
return acc;
},
];
} | the_stack |
import { Component, Input, OnInit, OnDestroy, ViewChild, NgZone } from '@angular/core';
import { FormGroup, FormBuilder, Validators, NgForm } from '@angular/forms';
import { DeviceService } from '../../service/device.service';
import { Router, ActivatedRoute } from '@angular/router';
import { SwalComponent } from '@toverux/ngx-sweetalert2';
import { ProfileInfo } from '../../model/profileInfo';
import { Device } from '../../model/device';
import { DeviceType } from '../../model/deviceType';
import { AsyncLocalStorage } from 'angular-async-local-storage';
import { LoggerService } from '../../service/logger.service';
import { Subscription } from 'rxjs/Subscription';
import { Message } from '../../model/message';
import { MQTTService } from '../../service/mqtt.service';
import { StatsService } from '../../service/stats.service';
import { environment } from '../../../environments/environment';
import { BlockUI, NgBlockUI } from 'ng-block-ui';
import * as moment from 'moment';
import * as _ from 'underscore';
declare var jquery: any;
declare var $: any;
declare var swal: any;
declare var mapboxgl: any;
declare var Gauge: any;
@Component({
selector: 'app-ratchet',
templateUrl: './vehicle.component.html'
})
export class VehicleComponent implements OnInit, OnDestroy { // implements LoggedInCallback {
public title: string = 'Vehicle Details';
public deviceStats: any = {};
private profile: ProfileInfo;
public vehicleId: string;
private sub: Subscription;
public device: Device = new Device();
public deviceType: DeviceType = new DeviceType();
public messages: Message[] = [];
private throttle_gauge: any;
private speed_gauge: any;
private rpm_gauge: any;
private oil_gauge: any;
private map: any;
public invalidMapboxToken: boolean = false;
private pollerInterval: any = null;
public telematics: any = {
throttle: 0,
speed: 0,
engine_speed: 0,
oil_temp: 0,
transmission_torque: 0,
odometer: 0,
fuel_level: 0,
gear: 0,
latitude: 38.955796,
longitude: -77.395869
};
@BlockUI() blockUI: NgBlockUI;
constructor(public router: Router,
public route: ActivatedRoute,
private deviceService: DeviceService,
protected localStorage: AsyncLocalStorage,
private logger: LoggerService,
private mqttService: MQTTService,
private statsService: StatsService,
private _ngZone: NgZone) {
}
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.vehicleId = params['vehicleId'];
});
this.device.metadata = {
vin: ''
};
this.blockUI.start('Loading vehicle...');
const _self = this;
this.statsService.statObservable$.subscribe(message => {
this.deviceStats = message;
this._ngZone.run(() => { });
});
this.statsService.refresh();
this.localStorage.getItem<ProfileInfo>('profile').subscribe((profile) => {
_self.profile = new ProfileInfo(profile);
_self.loadDevice();
this.createMap();
this.createGuages();
this.pollerInterval = setInterval(function() {
_self.loadDevice();
}, environment.refreshInterval);
});
}
ngOnDestroy() {
this.logger.info('destroying vehicle page, attempting to remove poller.');
clearInterval(this.pollerInterval);
}
loadDevice() {
const _self = this;
this.deviceService.getDevice(this.vehicleId).then((d: Device) => {
this.device = d;
if (this.deviceType.typeId === '') {
_self.deviceService.getDeviceType(_self.device.typeId).then((type: DeviceType) => {
_self.blockUI.stop();
_self.deviceType = new DeviceType(type);
this.mqttService.subscribe(`${_self.deviceType.spec.dataTopic}/${_self.device.metadata.vin}`);
// * listen to the MQTT stream
_self.mqttService.messageObservable$.subscribe(message => {
if (message.topic.startsWith(`${_self.deviceType.spec.dataTopic}/${_self.device.metadata.vin}`)) {
if (_self.messages.length > 100) {
_self.messages.pop();
}
_self.messages.unshift(message);
_self.updateGauges(message);
_self._ngZone.run(() => { });
}
});
}).catch((err) => {
this.blockUI.stop();
this.logger.error('error occurred calling getDeviceType api, show message');
this.logger.error(err);
});
} else {
this.blockUI.stop();
}
}).catch((err) => {
this.blockUI.stop();
swal(
'Oops...',
'Something went wrong! Unable to retrieve the vehicle.',
'error');
this.logger.error('error occurred calling getDevice api, show message');
this.logger.error(err);
});
}
startDevice() {
this.blockUI.start('Starting vehicle...');
const _self = this;
if (this.device.stage === 'sleeping') {
this.device.operation = 'hydrate';
this.deviceService.updateDevice(this.device).then((resp: any) => {
_self.loadDevice();
}).catch((err) => {
this.blockUI.stop();
swal(
'Oops...',
'Something went wrong! Unable to start the vehicle.',
'error');
this.logger.error('error occurred calling updateDevice api, show message');
this.logger.error(err);
this.loadDevice();
});
}
}
stopDevice() {
this.blockUI.start('Stopping vehicle...');
const _self = this;
if (this.device.stage === 'hydrated') {
this.device.operation = 'stop';
this.deviceService.updateDevice(this.device).then((resp: any) => {
_self.loadDevice();
}).catch((err) => {
this.blockUI.stop();
swal(
'Oops...',
'Something went wrong! Unable to stop the vehicle.',
'error');
this.logger.error('error occurred calling updateDevice api, show message');
this.logger.error(err);
this.loadDevice();
});
} else {
this.blockUI.stop();
}
}
deleteDevice() {
const _self = this;
swal({
title: 'Are you sure you want to delete this vehicle?',
text: 'You won\'t be able to revert this!',
type: 'question',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.value) {
_self.blockUI.start('Deleting vehicle...');
_self.deviceService.deleteDevice(_self.device.id).then((resp: any) => {
this.router.navigate(['/securehome/automotive']);
}).catch((err) => {
_self.blockUI.stop();
swal(
'Oops...',
'Something went wrong! Unable to delete the vehicle.',
'error');
_self.logger.error('error occurred calling deleteDevice api, show message');
_self.logger.error(err);
_self.loadDevice();
});
}
});
}
refreshData() {
this.blockUI.start('Loading vehicle...');
this.loadDevice();
}
formatDate(dt: string) {
if (dt) {
return moment(dt).format('MMM Do YYYY HH:mm');
} else {
return '';
}
}
strinifyContent(m: any) {
return JSON.stringify(m, undefined, 2);
}
clearMessages() {
this.messages.length = 0;
}
updateGauges(message: any) {
if (message.content.name === 'torque_at_transmission') {
this.telematics.transmission_torque = message.content.value;
$('#torque').css('width', [Math.ceil((this.telematics.transmission_torque / 500.0) * 100), '%'].join(''));
} else if (message.content.name === 'fuel_level') {
this.telematics.fuel_level = message.content.value;
$('#fuel').css('width', [this.telematics.fuel_level, '%'].join(''));
} else if (message.content.name === 'accelerator_pedal_position') {
this.telematics.throttle = message.content.value;
this.throttle_gauge.set(this.telematics.throttle);
} else if (message.content.name === 'vehicle_speed') {
this.telematics.speed = message.content.value;
this.speed_gauge.set(this.telematics.speed);
} else if (message.content.name === 'oil_temp') {
this.telematics.oil_temp = message.content.value;
this.oil_gauge.set(this.telematics.oil_temp);
} else if (message.content.name === 'engine_speed') {
this.telematics.engine_speed = message.content.value;
this.rpm_gauge.set(this.telematics.engine_speed);
} else if (message.content.name === 'transmission_gear_position') {
this.telematics.gear = message.content.value;
} else if (message.content.name === 'odometer') {
this.telematics.odometer = message.content.value;
} else if (message.content.name === 'location') {
this.telematics.latitude = message.content.latitude;
this.telematics.longitude = message.content.longitude;
if (!this.invalidMapboxToken) {
this.updateMap();
}
}
}
createGuages() {
this.createThrottleGauge();
this.createSpeedGuage();
this.createRpmGuage();
this.createOilGuage();
$('#torque').css('width', [Math.ceil((this.telematics.transmission_torque / 500.0) * 100), '%'].join(''));
$('#fuel').css('width', [this.telematics.fuel_level, '%'].join(''));
}
createMap() {
if (this.profile.mapboxToken === '') {
this.invalidMapboxToken = true;
return;
}
const _self = this;
mapboxgl.accessToken = this.profile.mapboxToken; // 'pk.eyJ1IjoiYW16bnNiIiwiYSI6ImNqMDN2ZGlveDBjcXoyd3AzNjM0YmpqeDQifQ.LGPO_wlElLvOJax3TO5aLQ';
this.map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/bright-v9', // stylesheet location
center: [this.telematics.longitude, this.telematics.latitude], // starting position [lng, lat]
zoom: 14 // starting zoom
});
this.map.on('error', function(err: any) {
_self.logger.error('mapbox gl error');
_self.logger.error(err);
_self.invalidMapboxToken = true;
return;
});
this.map.on('load', function() {
_self.map.addSource('sourceTest', {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: [{
type: 'Feature',
properties: {},
geometry: {
type: 'Point',
coordinates: [_self.telematics.longitude, _self.telematics.latitude]
}
}]
}
});
_self.map.addLayer({
id: 'layerTest',
source: 'sourceTest',
type: 'circle',
paint: {
'circle-radius': 10,
'circle-color': '#1de9b6',
'circle-opacity': 0.7,
'circle-stroke-width': 2,
'circle-stroke-color': '#00897b'
}
});
});
}
updateMap() {
this.map.setCenter([this.telematics.longitude, this.telematics.latitude]);
this.map.getSource('sourceTest').setData({
type: 'FeatureCollection',
features: [{
type: 'Feature',
properties: {},
geometry: {
type: 'Point',
coordinates: [this.telematics.longitude, this.telematics.latitude]
}
}]
});
}
createThrottleGauge() {
// ==============================================================
// Speed Gaugue
// ==============================================================
const throttle_opts = {
angle: 0, // The span of the gauge arc
lineWidth: 0.42, // The line thickness
radiusScale: 1, // Relative radius
pointer: {
length: 0.64, // // Relative to gauge radius
strokeWidth: 0.04, // The thickness
color: '#000000' // Fill color
},
limitMax: false, // If false, the max value of the gauge will be updated if value surpass max
limitMin: false, // If true, the min value of the gauge will be fixed unless you set it manually
colorStart: '#26c6da', // Colors
colorStop: '#26c6da', // just experiment with them
strokeColor: '#E0E0E0', // to see which ones work best for you
generateGradient: true,
highDpiSupport: true // High resolution support
};
const throttle_target = document.getElementById('throttle'); // your canvas element
this.throttle_gauge = new Gauge(throttle_target).setOptions(throttle_opts); // create sexy gauge!
this.throttle_gauge.maxValue = 100; // set max gauge value
this.throttle_gauge.setMinValue(0); // Prefer setter over gauge.minValue = 0
this.throttle_gauge.animationSpeed = 45; // set animation speed (32 is default value)
this.throttle_gauge.set(this.telematics.throttle); // set actual value
}
createSpeedGuage() {
// ==============================================================
// Speed Gaugue
// ==============================================================
const speed_opts = {
angle: 0, // The span of the gauge arc
lineWidth: 0.42, // The line thickness
radiusScale: 1, // Relative radius
pointer: {
length: 0.64, // // Relative to gauge radius
strokeWidth: 0.04, // The thickness
color: '#000000' // Fill color
},
limitMax: false, // If false, the max value of the gauge will be updated if value surpass max
limitMin: false, // If true, the min value of the gauge will be fixed unless you set it manually
colorStart: '#009efb', // Colors
colorStop: '#009efb', // just experiment with them
strokeColor: '#E0E0E0', // to see which ones work best for you
generateGradient: true,
highDpiSupport: true // High resolution support
};
const speed_target = document.getElementById('speed'); // your canvas element
this.speed_gauge = new Gauge(speed_target).setOptions(speed_opts); // create sexy gauge!
this.speed_gauge.maxValue = 160; // set max gauge value
this.speed_gauge.setMinValue(0); // Prefer setter over gauge.minValue = 0
this.speed_gauge.animationSpeed = 45; // set animation speed (32 is default value)
this.speed_gauge.set(this.telematics.speed); // set actual value
}
createRpmGuage() {
// ==============================================================
// RPM Gaugue
// ==============================================================
const rpm_opts = {
angle: 0, // The span of the gauge arc
lineWidth: 0.42, // The line thickness
radiusScale: 1, // Relative radius
pointer: {
length: 0.64, // // Relative to gauge radius
strokeWidth: 0.04, // The thickness
color: '#000000' // Fill color
},
limitMax: false, // If false, the max value of the gauge will be updated if value surpass max
limitMin: false, // If true, the min value of the gauge will be fixed unless you set it manually
colorStart: '#7460ee', // Colors
colorStop: '#7460ee', // just experiment with them
strokeColor: '#E0E0E0', // to see which ones work best for you
generateGradient: true,
highDpiSupport: true // High resolution support
};
const rpm_target = document.getElementById('rpm'); // your canvas element
this.rpm_gauge = new Gauge(rpm_target).setOptions(rpm_opts); // create sexy gauge!
this.rpm_gauge.maxValue = 8000; // set max gauge value
this.rpm_gauge.setMinValue(0); // Prefer setter over gauge.minValue = 0
this.rpm_gauge.animationSpeed = 45; // set animation speed (32 is default value)
this.rpm_gauge.set(this.telematics.engine_speed); // set actual value
}
createOilGuage() {
// ==============================================================
// Oil Gaugue
// ==============================================================
const oil_opts = {
angle: 0, // The span of the gauge arc
lineWidth: 0.42, // The line thickness
radiusScale: 1, // Relative radius
pointer: {
length: 0.64, // // Relative to gauge radius
strokeWidth: 0.04, // The thickness
color: '#000000' // Fill color
},
limitMax: false, // If false, the max value of the gauge will be updated if value surpass max
limitMin: false, // If true, the min value of the gauge will be fixed unless you set it manually
colorStart: '#f62d51', // Colors
colorStop: '#f62d51', // just experiment with them
strokeColor: '#E0E0E0', // to see which ones work best for you
generateGradient: true,
highDpiSupport: true // High resolution support
};
const oil_target = document.getElementById('oil'); // your canvas element
this.oil_gauge = new Gauge(oil_target).setOptions(oil_opts); // create sexy gauge!
this.oil_gauge.maxValue = 300; // set max gauge value
this.oil_gauge.setMinValue(0); // Prefer setter over gauge.minValue = 0
this.oil_gauge.animationSpeed = 45; // set animation speed (32 is default value)
this.oil_gauge.set(this.telematics.oil_temp); // set actual value
}
} | the_stack |
import { SwiperOptions } from './swiper-options';
import Swiper from './swiper-class';
import { A11yEvents } from './modules/a11y';
import { AutoplayEvents } from './modules/autoplay';
import { ControllerEvents } from './modules/controller';
import { CoverflowEffectEvents } from './modules/effect-coverflow';
import { CubeEffectEvents } from './modules/effect-cube';
import { FadeEffectEvents } from './modules/effect-fade';
import { FlipEffectEvents } from './modules/effect-flip';
import { CreativeEffectEvents } from './modules/effect-creative';
import { CardsEffectEvents } from './modules/effect-cards';
import { HashNavigationEvents } from './modules/hash-navigation';
import { HistoryEvents } from './modules/history';
import { KeyboardEvents } from './modules/keyboard';
import { LazyEvents } from './modules/lazy';
import { MousewheelEvents } from './modules/mousewheel';
import { NavigationEvents } from './modules/navigation';
import { PaginationEvents } from './modules/pagination';
import { ParallaxEvents } from './modules/parallax';
import { ScrollbarEvents } from './modules/scrollbar';
import { ThumbsEvents } from './modules/thumbs';
import { VirtualEvents } from './modules/virtual';
import { ZoomEvents } from './modules/zoom';
import { FreeModeEvents } from './modules/free-mode';
export interface SwiperEvents {
// CORE_EVENTS_START
/**
* Fired right after Swiper initialization.
* @note Note that with `swiper.on('init')` syntax it will
* work only in case you set `init: false` parameter.
*
* @example
* ```js
* const swiper = new Swiper('.swiper', {
* init: false,
* // other parameters
* });
* swiper.on('init', function() {
* // do something
* });
* // init Swiper
* swiper.init();
* ```
*
* @example
* ```js
* // Otherwise use it as the parameter:
* const swiper = new Swiper('.swiper', {
* // other parameters
* on: {
* init: function () {
* // do something
* },
* }
* });
* ```
*/
init: (swiper: Swiper) => any;
/**
* Event will be fired right before Swiper destroyed
*/
beforeDestroy: (swiper: Swiper) => void;
/**
* Event will be fired when currently active slide is changed
*/
slideChange: (swiper: Swiper) => void;
/**
* Event will be fired in the beginning of animation to other slide (next or previous).
*/
slideChangeTransitionStart: (swiper: Swiper) => void;
/**
* Event will be fired after animation to other slide (next or previous).
*/
slideChangeTransitionEnd: (swiper: Swiper) => void;
/**
* Same as "slideChangeTransitionStart" but for "forward" direction only
*/
slideNextTransitionStart: (swiper: Swiper) => void;
/**
* Same as "slideChangeTransitionEnd" but for "forward" direction only
*/
slideNextTransitionEnd: (swiper: Swiper) => void;
/**
* Same as "slideChangeTransitionStart" but for "backward" direction only
*/
slidePrevTransitionStart: (swiper: Swiper) => void;
/**
* Same as "slideChangeTransitionEnd" but for "backward" direction only
*/
slidePrevTransitionEnd: (swiper: Swiper) => void;
/**
* Event will be fired in the beginning of transition.
*/
transitionStart: (swiper: Swiper) => void;
/**
* Event will be fired after transition.
*/
transitionEnd: (swiper: Swiper) => void;
/**
* Event will be fired when user touch Swiper. Receives `touchstart` event as an arguments.
*/
touchStart: (swiper: Swiper, event: MouseEvent | TouchEvent | PointerEvent) => void;
/**
* Event will be fired when user touch and move finger over Swiper. Receives `touchmove` event as an arguments.
*/
touchMove: (swiper: Swiper, event: MouseEvent | TouchEvent | PointerEvent) => void;
/**
* Event will be fired when user touch and move finger over Swiper in direction opposite to direction parameter. Receives `touchmove` event as an arguments.
*/
touchMoveOpposite: (swiper: Swiper, event: MouseEvent | TouchEvent | PointerEvent) => void;
/**
* Event will be fired when user touch and move finger over Swiper and move it. Receives `touchmove` event as an arguments.
*/
sliderMove: (swiper: Swiper, event: MouseEvent | TouchEvent | PointerEvent) => void;
/**
* Event will be fired when user release Swiper. Receives `touchend` event as an arguments.
*/
touchEnd: (swiper: Swiper, event: MouseEvent | TouchEvent | PointerEvent) => void;
/**
* Event will be fired when user click/tap on Swiper. Receives `touchend` event as an arguments.
*/
click: (swiper: Swiper, event: MouseEvent | TouchEvent | PointerEvent) => void;
/**
* Event will be fired when user click/tap on Swiper. Receives `touchend` event as an arguments.
*/
tap: (swiper: Swiper, event: MouseEvent | TouchEvent | PointerEvent) => void;
/**
* Event will be fired when user double tap on Swiper's container. Receives `touchend` event as an arguments
*/
doubleTap: (swiper: Swiper, event: MouseEvent | TouchEvent | PointerEvent) => void;
/**
* Event will be fired right after all inner images are loaded. updateOnImagesReady should be also enabled
*/
imagesReady: (swiper: Swiper) => void;
/**
* Event will be fired when Swiper progress is changed, as an arguments it receives progress that is always from 0 to 1
*/
progress: (swiper: Swiper, progress: number) => void;
/**
* Event will be fired when Swiper reach its beginning (initial position)
*/
reachBeginning: (swiper: Swiper) => void;
/**
* Event will be fired when Swiper reach last slide
*/
reachEnd: (swiper: Swiper) => void;
/**
* Event will be fired when Swiper goes to beginning or end position
*/
toEdge: (swiper: Swiper) => void;
/**
* Event will be fired when Swiper goes from beginning or end position
*/
fromEdge: (swiper: Swiper) => void;
/**
* Event will be fired when swiper's wrapper change its position. Receives current translate value as an arguments
*/
setTranslate: (swiper: Swiper, translate: number) => void;
/**
* Event will be fired everytime when swiper starts animation. Receives current transition duration (in ms) as an arguments
*/
setTransition: (swiper: Swiper, transition: number) => void;
/**
* Event will be fired on window resize right before swiper's onresize manipulation
*/
resize: (swiper: Swiper) => void;
/**
* Event will be fired if observer is enabled and it detects DOM mutations
*/
observerUpdate: (swiper: Swiper) => void;
/**
* Event will be fired right before "loop fix"
*/
beforeLoopFix: (swiper: Swiper) => void;
/**
* Event will be fired after "loop fix"
*/
loopFix: (swiper: Swiper) => void;
/**
* Event will be fired on breakpoint change
*/
breakpoint: (swiper: Swiper, breakpointParams: SwiperOptions) => void;
/**
* !INTERNAL: Event will fired right before breakpoint change
*/
_beforeBreakpoint?: (swiper: Swiper, breakpointParams: SwiperOptions) => void;
/**
* !INTERNAL: Event will fired after setting CSS classes on swiper container element
*/
_containerClasses?: (swiper: Swiper, classNames: string) => void;
/**
* !INTERNAL: Event will fired after setting CSS classes on swiper slide element
*/
_slideClass?: (swiper: Swiper, slideEl: HTMLElement, classNames: string) => void;
/**
* !INTERNAL: Event will fired after setting CSS classes on all swiper slides
*/
_slideClasses?: (
swiper: Swiper,
slides: { slideEl: HTMLElement; classNames: string; index: number }[],
) => void;
/**
* !INTERNAL: Event will fired as soon as swiper instance available (before init)
*/
_swiper?: (swiper: Swiper) => void;
/**
* !INTERNAL: Event will be fired on free mode touch end (release) and there will no be momentum
*/
_freeModeNoMomentumRelease?: (swiper: Swiper) => void;
/**
* Event will fired on active index change
*/
activeIndexChange: (swiper: Swiper) => void;
/**
* Event will fired on snap index change
*/
snapIndexChange: (swiper: Swiper) => void;
/**
* Event will fired on real index change
*/
realIndexChange: (swiper: Swiper) => void;
/**
* Event will fired right after initialization
*/
afterInit: (swiper: Swiper) => void;
/**
* Event will fired right before initialization
*/
beforeInit: (swiper: Swiper) => void;
/**
* Event will fired before resize handler
*/
beforeResize: (swiper: Swiper) => void;
/**
* Event will fired before slide change transition start
*/
beforeSlideChangeStart: (swiper: Swiper) => void;
/**
* Event will fired before transition start
*/
beforeTransitionStart: (swiper: Swiper, speed: number, internal: any) => void; // what is internal?
/**
* Event will fired on direction change
*/
changeDirection: (swiper: Swiper) => void;
/**
* Event will be fired when user double click/tap on Swiper
*/
doubleClick: (swiper: Swiper, event: MouseEvent | TouchEvent | PointerEvent) => void;
/**
* Event will be fired on swiper destroy
*/
destroy: (swiper: Swiper) => void;
/**
* Event will be fired on momentum bounce
*/
momentumBounce: (swiper: Swiper) => void;
/**
* Event will be fired on orientation change (e.g. landscape -> portrait)
*/
orientationchange: (swiper: Swiper) => void;
/**
* Event will be fired in the beginning of animation of resetting slide to current one
*/
slideResetTransitionStart: (swiper: Swiper) => void;
/**
* Event will be fired in the end of animation of resetting slide to current one
*/
slideResetTransitionEnd: (swiper: Swiper) => void;
/**
* Event will be fired with first touch/drag move
*/
sliderFirstMove: (swiper: Swiper, event: TouchEvent) => void;
/**
* Event will be fired when number of slides has changed
*/
slidesLengthChange: (swiper: Swiper) => void;
/**
* Event will be fired when slides grid has changed
*/
slidesGridLengthChange: (swiper: Swiper) => void;
/**
* Event will be fired when snap grid has changed
*/
snapGridLengthChange: (swiper: Swiper) => void;
/**
* Event will be fired after swiper.update() call
*/
update: (swiper: Swiper) => void;
/**
* Event will be fired when swiper is locked (when `watchOverflow` enabled)
*/
lock: (swiper: Swiper) => void;
/**
* Event will be fired when swiper is unlocked (when `watchOverflow` enabled)
*/
unlock: (swiper: Swiper) => void;
// CORE_EVENTS_END
}
interface SwiperEvents extends A11yEvents {}
interface SwiperEvents extends AutoplayEvents {}
interface SwiperEvents extends ControllerEvents {}
interface SwiperEvents extends CoverflowEffectEvents {}
interface SwiperEvents extends CubeEffectEvents {}
interface SwiperEvents extends FadeEffectEvents {}
interface SwiperEvents extends FlipEffectEvents {}
interface SwiperEvents extends CreativeEffectEvents {}
interface SwiperEvents extends CardsEffectEvents {}
interface SwiperEvents extends HashNavigationEvents {}
interface SwiperEvents extends HistoryEvents {}
interface SwiperEvents extends KeyboardEvents {}
interface SwiperEvents extends LazyEvents {}
interface SwiperEvents extends MousewheelEvents {}
interface SwiperEvents extends NavigationEvents {}
interface SwiperEvents extends PaginationEvents {}
interface SwiperEvents extends ParallaxEvents {}
interface SwiperEvents extends ScrollbarEvents {}
interface SwiperEvents extends ThumbsEvents {}
interface SwiperEvents extends VirtualEvents {}
interface SwiperEvents extends ZoomEvents {}
interface SwiperEvents extends FreeModeEvents {} | the_stack |
export interface SvgCoord {
x: number;
y: number;
}
export interface SvgGraphItem {
activity: MapActivity;
position: SvgCoord;
}
export interface SvgGraphPath {
points: SvgCoord[];
}
export interface SvgGraph {
map: SkillMap;
items: SvgGraphItem[];
paths: SvgGraphPath[];
width: number;
height: number
}
export const UNIT = 10;
export const PADDING = 4;
export const MIN_HEIGHT = 40 * UNIT;
export const MIN_WIDTH = 60 * UNIT;
export function getGraph(map: SkillMap): SvgGraph {
let nodes: GraphNode[] = [];
switch (map.layout) {
case "manual":
nodes = nodes.concat(manualGraph(map.root));
break;
case "ortho":
default:
nodes = nodes.concat(orthogonalGraph(map.root));
}
let maxDepth = 0, maxOffset = 0;
// Convert into renderable items
const items: SvgGraphItem[] = [];
const paths: SvgGraphPath[] = [];
for (let current of nodes) {
const { depth, offset } = current;
items.push({
activity: current,
position: getPosition(depth, offset)
} as any);
if (current.edges) {
current.edges.forEach(edge => {
const points: SvgCoord[] = [];
edge.forEach(n => points.push(getPosition(n.depth, n.offset)));
paths.push({ points });
});
}
maxDepth = Math.max(maxDepth, current.depth);
maxOffset = Math.max(maxOffset, current.offset);
}
const width = getX(maxDepth) + UNIT * PADDING;
const height = getY(maxOffset) + UNIT * PADDING;
return { map, items, paths, width, height };
}
// This function converts graph position (no units) to x/y (SVG units)
function getPosition(depth: number, offset: number): SvgCoord {
return { x: getX(depth), y: getY(offset) }
}
function getX(position: number) {
return ((position * 12) + PADDING) * UNIT;
}
function getY(position: number) {
return ((position * 9) + PADDING) * UNIT;
}
////////////////////////////////////////////
//////// ////////
//////// GRAPH LAYOUT ////////
//////// ////////
////////////////////////////////////////////
export function manualGraph(root: MapNode): GraphNode[] {
const visited: string[] = [];
const graphNode = cloneGraph(root);
const nodes = dfsArray(graphNode).filter(node => node.kind !== "layout");
nodes.forEach(n => {
if (visited.indexOf(n.activityId) < 0) {
visited.push(n.activityId);
n.depth = n.position?.depth || 0;
n.offset = n.position?.offset || 0;
// Generate straight-line edges between nodes
const edges: GraphCoord[][] = []
n.next.forEach((next, i) => {
const nextDepth = next.position?.depth || 0;
const nextOffset = next.position?.offset || 0;
// Edge starts from current node
const edge = [{depth: n.depth, offset: n.offset }];
// If manual edge is specified for this node, push edge points
if (n.edges?.[i]) {
n.edges[i].forEach(el => {
const prev = edge[edge.length - 1];
// Ensure that there are only horizontal and vertical segments
if (el.depth !== prev.depth && el.offset !== prev.offset) {
edge.push({ depth: prev.depth, offset: el.offset });
}
edge.push(el);
})
}
// Edge ends at "next" node, ensure only horizontal/vertical
const prev = edge[edge.length - 1];
if (nextDepth !== prev.depth && nextOffset !== prev.offset) {
edge.push({ depth: prev.depth, offset: nextOffset });
}
edge.push({ depth: nextDepth, offset: nextOffset });
edges.push(edge);
});
n.edges = edges;
}
})
return nodes;
}
export function orthogonalGraph(root: MapNode): GraphNode[] {
const graphNode = cloneGraph(root);
let activities: GraphNode[] = [graphNode];
// Compute two coordiantes (depth, offset) for each node. The placement heuristic
// here is roughly based off of "The DFS-heuristic for orthogonal graph drawing"
// found at: https://core.ac.uk/download/pdf/82771879.pdf
const prevChildPosition: { [key: string]: GraphCoord } = {};
const visited: { [key: string]: boolean } = {};
let totalOffset = 0;
while (activities.length > 0) {
let current = activities.shift();
if (current && !visited[current.activityId]) {
visited[current.activityId] = true;
const parent = current.parents?.[0];
if (parent) {
const prevChild = prevChildPosition[parent.activityId] || { depth: 0, offset: 0 };
// If we can place it horizontally do so, otherwise place at bottom of the graph
if (prevChild.depth == 0) {
prevChild.depth = 1;
current.offset = parent.offset + prevChild.offset;
} else {
totalOffset += 1
prevChild.offset = totalOffset;
current.offset = totalOffset;
}
current.depth = parent.depth + prevChild.depth;
prevChildPosition[parent.activityId] = prevChild;
} else {
// This is a root node
current.depth = 0;
current.offset = 0;
}
// Assign the current node as the parent of its children
const next = current.next.map((el: BaseNode) => {
let node = el as GraphNode;
if (!node.parents) {
node.parents = [current!];
} else {
node.parents.push(current!);
}
return node;
})
// If we have already seen this child node (attached to earlier parent)
// 1. Increase child offset by one unit (so it's between the parents) and adjust the total if necessary
// 2. Increase child depth if necessary (should be deeper than parent)
next.filter(n => visited[n.activityId]).forEach(n => {
// Skip the increment if the nodes are adjacent siblings
if (!isAdjacent(n, current!)) {
n.offset += 1;
totalOffset = Math.max(totalOffset, n.offset);
n.depth = Math.max(n.depth, current!.depth + 1);
}
})
activities = next.concat(activities);
}
}
const nodes = dfsArray(graphNode).filter(node => node.kind !== "layout");
// Get map of node offsets at each level of the graph
const offsetMap: { [key: number]: number[] } = {};
nodes.forEach(n => {
if (offsetMap[n.depth] == undefined) {
offsetMap[n.depth] = [];
}
offsetMap[n.depth].push(n.offset);
})
// Shrink long leaf branches
nodes.forEach(node => {
if ((!node.next || node.next.length == 0) && node.parents?.length == 1) {
const parent = node.parents[0];
const offsets = offsetMap[node.depth];
const siblingOffset = offsets[offsets.indexOf(node.offset) - 1];
const distance = siblingOffset ? node.offset - siblingOffset : Math.abs(node.depth - parent.depth) + Math.abs(node.offset - parent.offset);
if (distance > 2) {
node.depth = parent.depth;
node.offset = (siblingOffset || parent.offset) + 1;
}
}
})
// Calculate edge segments from parent nodes
nodes.forEach(n => {
if (n.parents) {
n.edges = [];
// We will try to flip the edge (draw vertical before horizontal) if
// there is a parent on the horizontal axis, or more than two parents
const tryFlipEdge = n.parents.some(p => p.offset == n.offset) || n.parents.length > 2;
n.parents.forEach(p => {
const edge = [{ depth: p.depth, offset: p.offset }];
if (tryFlipEdge) {
// Grab node index, check the siblings to see if there is space to draw the flipped edge
const offsets = offsetMap[n.depth];
const nodeIndex = offsets.indexOf(n.offset);
const spaceBelow = n.offset > p.offset && !((offsets[nodeIndex + 1] - offsets[nodeIndex]) < (n.offset - p.offset));
const spaceAbove = n.offset < p.offset && !((offsets[nodeIndex] - offsets[nodeIndex - 1]) < (p.offset - n.offset));
if (spaceBelow || spaceAbove) {
edge.push({ depth: n.depth, offset: p.offset });
} else {
edge.push({ depth: p.depth, offset: n.offset });
}
} else {
edge.push({ depth: p.depth, offset: n.offset });
}
edge.push({ depth: n.depth, offset: n.offset });
n.edges?.push(edge);
})
}
})
return nodes;
}
// Simple tree-like layout, does not handle loops very well
export function treeGraph(root: BaseNode): GraphNode[] {
let graphNode = cloneGraph(root);
let activities: GraphNode[] = [graphNode];
// Pass to set the width of each node
setWidths(graphNode);
// We keep a map of how deep the graph is at this depth
const offsetMap: { [key: number]: number } = {};
// BFS traversal to set the offset and depth
while (activities.length > 0) {
let current = activities.shift();
if (current) {
current.depth = current.parents ? (Math.min(...current.parents.map((el: GraphNode) => el.depth)) + 1) : 0;
if (offsetMap[current.depth] === undefined) {
offsetMap[current.depth] = 1;
}
// Set the offset of the node, track it in our map
if (!current.offset) {
const parent = current.parents?.map((el: GraphNode) => el.offset) || [0];
current.offset = Math.max(offsetMap[current.depth], ...parent);
offsetMap[current.depth] = current.offset + current.width!;
}
// Assign this node as the parent of all children
const next = current.next.map((el: BaseNode) => {
let node = el as GraphNode;
if (!node.parents) {
node.parents = [current!];
} else {
node.parents.push(current!);
}
return node;
})
activities = activities.concat(next);
}
}
const nodes = bfsArray(graphNode).filter(node => node.kind !== "layout");
nodes.forEach(n => {
if (n.parents) {
n.edges = [];
n.parents.forEach(p => {
// Edge from parent, vertically down, then horizontal to child
n.edges?.push([ { depth: p.depth, offset: p.offset },
{ depth: n.depth, offset: p.offset },
{ depth: n.depth, offset: n.offset } ])
})
}
})
return nodes;
}
function setWidths(node: GraphNode): number {
if (!node.next || node.next.length == 0) {
node.width = 1;
} else {
node.width = node.next.map((el: any) => setWidths(el)).reduce((total: number, w: number) => total + w);
}
return node.width;
}
function isAdjacent(a: GraphNode, b: GraphNode): boolean {
if (!a.parents || !b.parents) return false;
let sharedParent: GraphNode | undefined;
a.parents.forEach((p: GraphNode) => {
if (b.parents!.indexOf(p) >= 0) sharedParent = p;
})
return !!sharedParent
&& Math.abs(sharedParent.nextIds.indexOf(a.activityId) - sharedParent.nextIds.indexOf(b.activityId)) == 1
&& a.depth == b.depth;
}
function bfsArray(root: GraphNode): GraphNode[] {
let nodes = [];
let queue = [root];
let visited: { [key: string]: boolean } = {};
while (queue.length > 0) {
let current = queue.shift();
if (current && !visited[current.activityId]) {
visited[current.activityId] = true;
nodes.push(current);
queue = queue.concat(current.next as any);
}
}
return nodes;
}
function dfsArray(root: GraphNode): GraphNode[] {
let nodes = [];
let queue = [root];
let visited: { [key: string]: boolean } = {};
while (queue.length > 0) {
let current = queue.shift();
if (current && !visited[current.activityId]) {
visited[current.activityId] = true;
nodes.push(current);
queue = (current.next as any).concat(queue);
}
}
return nodes;
}
function cloneGraph(root: BaseNode): GraphNode {
const nodes = bfsArray(root as GraphNode);
const clones: { [key: string]: GraphNode} = {};
// Clone all nodes, assign children to cloned nodes
nodes.forEach(n => {
let nextCopy = n.next.slice();
n.next.length = 0;
clones[n.activityId] = JSON.parse(JSON.stringify(n));
n.next = nextCopy;
});
Object.keys(clones).forEach(cloneId => clones[cloneId].next = clones[cloneId].nextIds.map(id => clones[id] as any));
return clones[root.activityId];
} | the_stack |
import { URL, URLSearchParams } from "url";
import * as vscode from "vscode";
import { Base64 } from "js-base64";
import { RequestParams } from "../clientDevice";
import {
Request,
Response,
Header,
ResponseFollowupChunk,
PartialResponse,
} from "../networkMessageData";
import { EditorColorThemesHelper, SystemColorTheme } from "../../../common/editorColorThemesHelper";
import { SettingsHelper } from "../../settingsHelper";
import { combineBase64Chunks } from "../requestBodyFormatters/utils";
import { FormattedBody } from "../requestBodyFormatters/requestBodyFormatter";
import { InspectorView } from "./inspectorView";
interface ConsoleNetworkRequestDataView {
title: string;
networkRequestData: {
URL: string;
Method: string;
Status: number;
Duration: string;
"Request Headers": Record<string, string>;
"Response Headers": Record<string, string>;
"Request Body": FormattedBody | null | undefined;
"Request Query Parameters"?: Record<string, string> | undefined;
"Response Body": FormattedBody | null | undefined;
};
}
export class InspectorConsoleView extends InspectorView {
private readonly maxResponseBodyLength = 75000;
private readonly openDeveloperToolsCommand = "workbench.action.toggleDevTools";
private readonly consoleLogsColors = {
Blue: "#0000ff",
Orange: "#f28b54",
};
private consoleLogsColor: string;
public async init(): Promise<void> {
if (!this.isInitialized) {
this.isInitialized = true;
await vscode.commands.executeCommand(this.openDeveloperToolsCommand);
if (EditorColorThemesHelper.isAutoDetectColorSchemeEnabled()) {
this.setupConsoleLogsColor(EditorColorThemesHelper.getCurrentSystemColorTheme());
} else {
this.setupConsoleLogsColor(
SettingsHelper.getNetworkInspectorConsoleLogsColorTheme(),
);
}
}
}
public handleMessage(data: RequestParams): void {
if (data.params) {
switch (data.method) {
case "newRequest":
this.handleRequest(data.params as Request);
break;
case "newResponse":
this.handleResponse(data.params as Response);
break;
case "partialResponse":
this.handlePartialResponse(data.params as Response | ResponseFollowupChunk);
break;
}
}
}
private setupConsoleLogsColor(systemColorTheme: SystemColorTheme): void {
if (systemColorTheme === SystemColorTheme.Light) {
this.consoleLogsColor = this.consoleLogsColors.Blue;
} else {
this.consoleLogsColor = this.consoleLogsColors.Orange;
}
}
private handleRequest(data: Request): void {
this.requests.set(data.id, data);
}
private handleResponse(data: Response): void {
this.responses.set(data.id, data);
if (this.requests.has(data.id)) {
this.printNetworkRequestData(
this.createNetworkRequestData(this.requests.get(data.id) as Request, data),
);
}
}
private handlePartialResponse(data: Response | ResponseFollowupChunk): void {
/* Some clients (such as low end Android devices) struggle to serialise large payloads in one go, so partial responses allow them
to split payloads into chunks and serialise each individually.
Such responses will be distinguished between normal responses by both:
* Being sent to the partialResponse method.
* Having a totalChunks value > 1.
The first chunk will always be included in the initial response. This response must have index 0.
The remaining chunks will be sent in ResponseFollowupChunks, which each contain another piece of the payload, along with their index from 1 onwards.
The payload of each chunk is individually encoded in the same way that full responses are.
The order that initialResponse, and followup chunks are recieved is not guaranteed to be in index order.
*/
let newPartialResponseEntry;
let responseId;
if (data.index !== undefined && data.index > 0) {
// It's a follow up chunk
const followupChunk: ResponseFollowupChunk = data as ResponseFollowupChunk;
const partialResponseEntry = this.partialResponses.get(followupChunk.id) ?? {
followupChunks: {},
};
newPartialResponseEntry = Object.assign({}, partialResponseEntry);
newPartialResponseEntry.followupChunks[followupChunk.index] = followupChunk.data;
responseId = followupChunk.id;
} else {
// It's an initial chunk
const partialResponse: Response = data as Response;
const partialResponseEntry = this.partialResponses.get(partialResponse.id) ?? {
followupChunks: {},
};
newPartialResponseEntry = {
...partialResponseEntry,
initialResponse: partialResponse,
};
responseId = partialResponse.id;
}
const response = this.assembleChunksIfResponseIsComplete(newPartialResponseEntry);
if (response) {
this.handleResponse(response);
this.partialResponses.delete(responseId);
} else {
this.partialResponses.set(responseId, newPartialResponseEntry);
}
}
/**
* @preserve
* Start region: the code is borrowed from https://github.com/facebook/flipper/blob/v0.79.1/desktop/plugins/network/index.tsx#L276-L324
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
private assembleChunksIfResponseIsComplete(
partialResponseEntry: PartialResponse,
): Response | null {
const numChunks = partialResponseEntry.initialResponse?.totalChunks;
if (
!partialResponseEntry.initialResponse ||
!numChunks ||
Object.keys(partialResponseEntry.followupChunks).length + 1 < numChunks
) {
// Partial response not yet complete, do nothing.
return null;
}
// Partial response has all required chunks, convert it to a full Response.
const response: Response = partialResponseEntry.initialResponse;
const allChunks: string[] =
response.data != null
? [
response.data,
...Object.entries(partialResponseEntry.followupChunks)
// It's important to parseInt here or it sorts lexicographically
.sort((a, b) => parseInt(a[0], 10) - parseInt(b[0], 10))
.map(([_k, v]: [string, string]) => v),
]
: [];
const data = combineBase64Chunks(allChunks);
const newResponse = {
...response,
// Currently data is always decoded at render time, so re-encode it to match the single response format.
data: Base64.btoa(data),
};
return newResponse;
}
/**
* @preserve
* End region: https://github.com/facebook/flipper/blob/v0.79.1/desktop/plugins/network/index.tsx#L276-L324
*/
private createNetworkRequestData(
request: Request,
response: Response,
): ConsoleNetworkRequestDataView {
const url = new URL(request.url);
const networkRequestConsoleView = {
title: `%cNetwork request: ${request.method} ${
url ? url.host + url.pathname : "<unknown>"
}`,
networkRequestData: {
URL: request.url,
Method: request.method,
Status: response.status,
Duration: this.getRequestDurationString(request.timestamp, response.timestamp),
"Request Headers": this.prepareHeadersViewObject(request.headers),
"Response Headers": this.prepareHeadersViewObject(response.headers),
"Request Body": this.requestBodyDecoder.formatBody(request),
"Response Body": this.requestBodyDecoder.formatBody(response),
},
};
if (url.search) {
networkRequestConsoleView.networkRequestData["Request Query Parameters"] =
this.retrieveURLSearchParams(url.searchParams);
}
return networkRequestConsoleView;
}
private retrieveURLSearchParams(searchParams: URLSearchParams): Record<string, string> {
const formattedSearchParams: Record<string, string> = {};
searchParams.forEach((value: string, key: string) => {
formattedSearchParams[key] = value;
});
return formattedSearchParams;
}
private getRequestDurationString(requestTimestamp: number, responseTimestamp: number): string {
return `${String(Math.abs(responseTimestamp - requestTimestamp))}ms`;
}
private prepareHeadersViewObject(headers: Header[]): Record<string, string> {
return headers.reduce((headersViewObject, header) => {
headersViewObject[header.key] = header.value;
return headersViewObject;
}, {});
}
private printNetworkRequestData(networkRequestData: ConsoleNetworkRequestDataView): void {
const responseBody = networkRequestData.networkRequestData["Response Body"];
if (
responseBody &&
typeof responseBody === "string" &&
responseBody.length > this.maxResponseBodyLength
) {
networkRequestData.networkRequestData["Response Body"] = `${responseBody.substring(
0,
this.maxResponseBodyLength,
)}... (Response body exceeds output limit, the rest its part is omitted)`;
}
console.log(
networkRequestData.title,
`color: ${this.consoleLogsColor}`,
networkRequestData.networkRequestData,
);
this.logger.debug(
`${networkRequestData.title}\ncolor: ${this.consoleLogsColor}\n${JSON.stringify(
networkRequestData.networkRequestData,
null,
2,
)}`,
);
}
} | the_stack |
import { BarcodeGenerator } from "../../../src/barcode/barcode";
import { createElement } from "@syncfusion/ej2-base";
let barcode: BarcodeGenerator;
let ele: HTMLElement;
describe('Code128C - Barcode', () => {
describe('checking Code128C barcode rendering all lines check', () => {
beforeAll((): void => {
ele = createElement('div', { id: 'barcode128C1' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '114px', height: '150px',
type: 'Code128C',
value: '11223344',
mode:'SVG'
});
barcode.appendTo('#barcode128C1');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
var output1 = {
0: { width: "2.38", height: "116.50", x: 10, y: 10 },
1: { width: "1.19", height: "116.50", x: 14, y: 10 },
2: { width: "3.57", height: "116.50", x: 17, y: 10 },
3: { width: "2.38", height: "116.50", x: 23, y: 10 },
4: { width: "1.19", height: "116.50", x: 29, y: 10 },
5: { width: "1.19", height: "116.50", x: 33, y: 10 },
6: { width: "2.38", height: "116.50", x: 36, y: 10 },
7: { width: "3.57", height: "116.50", x: 41, y: 10 },
8: { width: "1.19", height: "116.50", x: 46, y: 10 },
9: { width: "1.19", height: "116.50", x: 49, y: 10 },
10: { width: "1.19", height: "116.50", x: 52, y: 10 },
11: { width: "2.38", height: "116.50", x: 56, y: 10 },
12: { width: "1.19", height: "116.50", x: 62, y: 10 },
13: { width: "2.38", height: "116.50", x: 67, y: 10 },
14: { width: "3.57", height: "116.50", x: 71, y: 10 },
15: { width: "3.57", height: "116.50", x: 75, y: 10 },
16: { width: "2.38", height: "116.50", x: 80, y: 10 },
17: { width: "3.57", height: "116.50", x: 84, y: 10 },
18: { width: "2.38", height: "116.50", x: 89, y: 10 },
19: { width: "3.57", height: "116.50", x: 94, y: 10 },
20: { width: "1.19", height: "116.50", x: 99, y: 10 },
21: { width: "2.38", height: "116.50", x: 102, y: 10 },
};
it('checking Code128C barcode rendering with display text margin and barcode margin', (done: Function) => {
let barcode = document.getElementById('barcode128C1')
let children: HTMLElement = barcode.children[0] as HTMLElement
expect((Math.round(Number(children.children[0].getAttribute('x'))) === 9)
&& (children.children[0] as HTMLElement).style.fontSize === '20px').toBe(true);
for (let j: number = 1; j < children.children.length - 1; j++) {
expect(Math.round(Number(children.children[j + 1].getAttribute('x'))) === output1[j].x && Math.round(Number(children.children[j + 1].getAttribute('y'))) === output1[j].y
&& parseFloat((children.children[j + 1].getAttribute('width'))).toFixed(2) === output1[j].width
&& parseFloat((children.children[j + 1].getAttribute('height'))).toFixed(2) === output1[j].height).toBe(true);
}
done();
});
});
describe('checking Code128C barcode rendering all lines check', () => {
//let barcode: BarcodeGenerator;
//let ele: HTMLElement;
beforeAll((): void => {
ele = createElement('div', { id: 'barcode128C1' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '214px', height: '150px',
type: 'Code128C',
margin:{left:30,right:30,top:30,bottom:30},
value: '123456789198765432',
mode: 'SVG'
});
barcode.appendTo('#barcode128C1');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
var output1 = {
0: { width: "2.30", height: "76.50", x: 30, y: 30 },
1: { width: "1.15", height: "76.50", x: 33, y: 30 },
2: { width: "3.45", height: "76.50", x: 37, y: 30 },
3: { width: "1.15", height: "76.50", x: 43, y: 30 },
4: { width: "2.30", height: "76.50", x: 45, y: 30 },
5: { width: "3.45", height: "76.50", x: 50, y: 30 },
6: { width: "1.15", height: "76.50", x: 55, y: 30 },
7: { width: "1.15", height: "76.50", x: 60, y: 30 },
8: { width: "2.30", height: "76.50", x: 62, y: 30 },
9: { width: "3.45", height: "76.50", x: 68, y: 30 },
10: { width: "1.15", height: "76.50", x: 75, y: 30 },
11: { width: "2.30", height: "76.50", x: 77, y: 30 },
12: { width: "2.30", height: "76.50", x: 81, y: 30 },
13: { width: "1.15", height: "76.50", x: 87, y: 30 },
14: { width: "1.15", height: "76.50", x: 90, y: 30 },
15: { width: "4.60", height: "76.50", x: 93, y: 30 },
16: { width: "2.30", height: "76.50", x: 99, y: 30 },
17: { width: "2.30", height: "76.50", x: 102, y: 30 },
18: { width: "4.60", height: "76.50", x: 106, y: 30 },
19: { width: "1.15", height: "76.50", x: 112, y: 30 },
20: { width: "1.15", height: "76.50", x: 116, y: 30 },
21: { width: "2.30", height: "76.50", x: 118, y: 30 },
22: { width: "1.15", height: "76.50", x: 123, y: 30 },
23: { width: "1.15", height: "76.50", x: 125, y: 30 },
24: { width: "3.45", height: "76.50", x: 131, y: 30 },
25: { width: "1.15", height: "76.50", x: 136, y: 30 },
26: { width: "2.30", height: "76.50", x: 138, y: 30 },
27: { width: "2.30", height: "76.50", x: 144, y: 30 },
28: { width: "2.30", height: "76.50", x: 150, y: 30 },
29: { width: "2.30", height: "76.50", x: 153, y: 30 },
30: { width: "2.30", height: "76.50", x: 156, y: 30 },
31: { width: "1.15", height: "76.50", x: 161, y: 30 },
32: { width: "1.15", height: "76.50", x: 163, y: 30 },
33: { width: "2.30", height: "76.50", x: 169, y: 30 },
34: { width: "3.45", height: "76.50", x: 175, y: 30 },
35: { width: "1.15", height: "76.50", x: 179, y: 30 },
36: { width: "2.30", height: "76.50", x: 182, y: 30 },
};
it('checking Code128C barcode rendering with display text margin and barcode margin', (done: Function) => {
let barcode = document.getElementById('barcode128C1')
let children: HTMLElement = barcode.children[0] as HTMLElement
expect((Math.round(Number(children.children[0].getAttribute('x'))) === -1)
&& (children.children[0] as HTMLElement).style.fontSize === '20px').toBe(true);
for (let j: number = 1; j < children.children.length - 1; j++) {
expect(Math.round(Number(children.children[j + 1].getAttribute('x'))) === output1[j].x && Math.round(Number(children.children[j + 1].getAttribute('y'))) === output1[j].y
&& parseFloat((children.children[j + 1].getAttribute('width'))).toFixed(2) === output1[j].width
&& parseFloat((children.children[j + 1].getAttribute('height'))).toFixed(2) === output1[j].height).toBe(true);
}
done();
});
});
describe('checking Code128C barcode rendering all lines check', () => {
//let barcode: BarcodeGenerator;
//let ele: HTMLElement;
beforeAll((): void => {
ele = createElement('div', { id: 'barcode128C1' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '214px', height: '150px',
type: 'Code128C',
margin:{left:30,right:30,top:30,bottom:30},
value: '123456789198765432',
mode: 'SVG'
});
barcode.appendTo('#barcode128C1');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
var output1 = {
0: {width: "2.30", height: "76.50", x: 30, y: 30},
1: {width: "1.15", height: "76.50", x: 33, y: 30},
2: {width: "3.45", height: "76.50", x: 37, y: 30},
3: {width: "1.15", height: "76.50", x: 43, y: 30},
4: {width: "2.30", height: "76.50", x: 45, y: 30},
5: {width: "3.45", height: "76.50", x: 50, y: 30},
6: {width: "1.15", height: "76.50", x: 55, y: 30},
7: {width: "1.15", height: "76.50", x: 60, y: 30},
8: {width: "2.30", height: "76.50", x: 62, y: 30},
9: {width: "3.45", height: "76.50", x: 68, y: 30},
10: {width: "1.15", height: "76.50", x: 75, y: 30},
11: {width: "2.30", height: "76.50", x: 77, y: 30},
12: {width: "2.30", height: "76.50", x: 81, y: 30},
13: {width: "1.15", height: "76.50", x: 87, y: 30},
14: {width: "1.15", height: "76.50", x: 90, y: 30},
15: {width: "4.60", height: "76.50", x: 93, y: 30},
16: {width: "2.30", height: "76.50", x: 99, y: 30},
17: {width: "2.30", height: "76.50", x: 102, y: 30},
18: {width: "4.60", height: "76.50", x: 106, y: 30},
19: {width: "1.15", height: "76.50", x: 112, y: 30},
20: {width: "1.15", height: "76.50", x: 116, y: 30},
21: {width: "2.30", height: "76.50", x: 118, y: 30},
22: {width: "1.15", height: "76.50", x: 123, y: 30},
23: {width: "1.15", height: "76.50", x: 125, y: 30},
24: {width: "3.45", height: "76.50", x: 131, y: 30},
25: {width: "1.15", height: "76.50", x: 136, y: 30},
26: {width: "2.30", height: "76.50", x: 138, y: 30},
27: {width: "2.30", height: "76.50", x: 144, y: 30},
28: {width: "2.30", height: "76.50", x: 150, y: 30},
29: {width: "2.30", height: "76.50", x: 153, y: 30},
30: {width: "2.30", height: "76.50", x: 156, y: 30},
31: {width: "1.15", height: "76.50", x: 161, y: 30},
32: {width: "1.15", height: "76.50", x: 163, y: 30},
33: {width: "2.30", height: "76.50", x: 169, y: 30},
34: {width: "3.45", height: "76.50", x: 175, y: 30},
35: {width: "1.15", height: "76.50", x: 179, y: 30},
36: {width: "2.30", height: "76.50", x: 182, y: 30},
};
it('checking Code128C barcode rendering with display text margin and barcode margin', (done: Function) => {
let barcode = document.getElementById('barcode128C1')
let children: HTMLElement = barcode.children[0] as HTMLElement
expect((Math.round(Number(children.children[0].getAttribute('x'))) === -1)
&& (children.children[0] as HTMLElement).style.fontSize === '20px').toBe(true);
for (let j: number = 1; j < children.children.length - 1; j++) {
expect(Math.round(Number(children.children[j + 1].getAttribute('x'))) === output1[j].x && Math.round(Number(children.children[j + 1].getAttribute('y'))) === output1[j].y
&& parseFloat((children.children[j + 1].getAttribute('width'))).toFixed(2) === output1[j].width
&& parseFloat((children.children[j + 1].getAttribute('height'))).toFixed(2) === output1[j].height).toBe(true);
}
done();
});
});
describe('checking Code128C barcode rendering invalid character', () => {
//let barcode: BarcodeGenerator;
//let ele: HTMLElement;
beforeAll((): void => {
ele = createElement('div', { id: 'barcode128invalid' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '214px', height: '150px',
type: 'Code128C',
value: '12345678919876543',
mode: 'SVG'
});
barcode.appendTo('#barcode128invalid');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('checking Code128C barcode rendering invalid character', (done: Function) => {
let barcode = document.getElementById('barcode128invalid')
let children: HTMLElement = barcode.children[0] as HTMLElement
//error
expect(children.childElementCount===0).toBe(true);
done();
});
});
}); | the_stack |
import {
IExecuteFunctions,
} from 'n8n-core';
import {
IDataObject,
ILoadOptionsFunctions,
INodeExecutionData,
INodePropertyOptions,
INodeType,
INodeTypeDescription,
NodeApiError,
NodeOperationError,
} from 'n8n-workflow';
import {
codaApiRequest,
codaApiRequestAllItems,
} from './GenericFunctions';
import {
tableFields,
tableOperations,
} from './TableDescription';
import {
formulaFields,
formulaOperations,
} from './FormulaDescription';
import {
controlFields,
controlOperations,
} from './ControlDescription';
import {
viewFields,
viewOperations,
} from './ViewDescription';
export class Coda implements INodeType {
description: INodeTypeDescription = {
displayName: 'Coda',
name: 'coda',
icon: 'file:coda.svg',
group: ['output'],
version: 1,
subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}',
description: 'Consume Coda API',
defaults: {
name: 'Coda',
},
inputs: ['main'],
outputs: ['main'],
credentials: [
{
name: 'codaApi',
required: true,
},
],
properties: [
{
displayName: 'Resource',
name: 'resource',
type: 'options',
options: [
{
name: 'Control',
value: 'control',
description: 'Controls provide a user-friendly way to input a value that can affect other parts of the doc.',
},
{
name: 'Formula',
value: 'formula',
description: 'Formulas can be great for performing one-off computations',
},
{
name: 'Table',
value: 'table',
description: `Access data of tables in documents.`,
},
{
name: 'View',
value: 'view',
description: `Access data of views in documents.`,
},
],
default: 'table',
description: 'Resource to consume.',
},
...tableOperations,
...tableFields,
...formulaOperations,
...formulaFields,
...controlOperations,
...controlFields,
...viewOperations,
...viewFields,
],
};
methods = {
loadOptions: {
// Get all the available docs to display them to user so that he can
// select them easily
async getDocs(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
const qs = {};
const docs = await codaApiRequestAllItems.call(this,'items', 'GET', `/docs`, {}, qs);
for (const doc of docs) {
const docName = doc.name;
const docId = doc.id;
returnData.push({
name: docName,
value: docId,
});
}
return returnData;
},
// Get all the available tables to display them to user so that he can
// select them easily
async getTables(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
const docId = this.getCurrentNodeParameter('docId');
const tables = await codaApiRequestAllItems.call(this, 'items', 'GET', `/docs/${docId}/tables`, {});
for (const table of tables) {
const tableName = table.name;
const tableId = table.id;
returnData.push({
name: tableName,
value: tableId,
});
}
return returnData;
},
// Get all the available columns to display them to user so that he can
// select them easily
async getColumns(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
const docId = this.getCurrentNodeParameter('docId');
const tableId = this.getCurrentNodeParameter('tableId');
const columns = await codaApiRequestAllItems.call(this, 'items', 'GET', `/docs/${docId}/tables/${tableId}/columns`, {});
for (const column of columns) {
const columnName = column.name;
const columnId = column.id;
returnData.push({
name: columnName,
value: columnId,
});
}
return returnData;
},
// Get all the available views to display them to user so that he can
// select them easily
async getViews(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
const docId = this.getCurrentNodeParameter('docId');
const views = await codaApiRequestAllItems.call(this, 'items', 'GET', `/docs/${docId}/tables?tableTypes=view`, {});
for (const view of views) {
const viewName = view.name;
const viewId = view.id;
returnData.push({
name: viewName,
value: viewId,
});
}
return returnData;
},
// Get all the available formulas to display them to user so that he can
// select them easily
async getFormulas(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
const docId = this.getCurrentNodeParameter('docId');
const formulas = await codaApiRequestAllItems.call(this, 'items', 'GET', `/docs/${docId}/formulas`, {});
for (const formula of formulas) {
const formulaName = formula.name;
const formulaId = formula.id;
returnData.push({
name: formulaName,
value: formulaId,
});
}
return returnData;
},
// Get all the available view rows to display them to user so that he can
// select them easily
async getViewRows(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
const docId = this.getCurrentNodeParameter('docId');
const viewId = this.getCurrentNodeParameter('viewId');
const viewRows = await codaApiRequestAllItems.call(this, 'items', 'GET', `/docs/${docId}/tables/${viewId}/rows`, {});
for (const viewRow of viewRows) {
const viewRowName = viewRow.name;
const viewRowId = viewRow.id;
returnData.push({
name: viewRowName,
value: viewRowId,
});
}
return returnData;
},
// Get all the available view columns to display them to user so that he can
// select them easily
async getViewColumns(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
const docId = this.getCurrentNodeParameter('docId');
const viewId = this.getCurrentNodeParameter('viewId');
const viewColumns = await codaApiRequestAllItems.call(this, 'items', 'GET', `/docs/${docId}/tables/${viewId}/columns`, {});
for (const viewColumn of viewColumns) {
const viewColumnName = viewColumn.name;
const viewColumnId = viewColumn.id;
returnData.push({
name: viewColumnName,
value: viewColumnId,
});
}
return returnData;
},
},
};
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const returnData: IDataObject[] = [];
const items = this.getInputData();
let responseData;
const resource = this.getNodeParameter('resource', 0) as string;
const operation = this.getNodeParameter('operation', 0) as string;
let qs: IDataObject = {};
if (resource === 'table') {
// https://coda.io/developers/apis/v1beta1#operation/upsertRows
if (operation === 'createRow') {
try {
const sendData = {} as IDataObject;
for (let i = 0; i < items.length; i++) {
qs = {};
const docId = this.getNodeParameter('docId', i) as string;
const tableId = this.getNodeParameter('tableId', i) as string;
const options = this.getNodeParameter('options', i) as IDataObject;
const endpoint = `/docs/${docId}/tables/${tableId}/rows`;
if (options.disableParsing) {
qs.disableParsing = options.disableParsing as boolean;
}
const cells = [];
cells.length = 0;
for (const key of Object.keys(items[i].json)) {
cells.push({
column: key,
value: items[i].json[key],
});
}
// Collect all the data for the different docs/tables
if (sendData[endpoint] === undefined) {
sendData[endpoint] = {
rows: [],
// TODO: This is not perfect as it ignores if qs changes between
// different items but should be OK for now
qs,
};
}
((sendData[endpoint]! as IDataObject).rows! as IDataObject[]).push({ cells });
if (options.keyColumns) {
// @ts-ignore
(sendData[endpoint]! as IDataObject).keyColumns! = options.keyColumns.split(',') as string[];
}
}
// Now that all data got collected make all the requests
for (const endpoint of Object.keys(sendData)) {
await codaApiRequest.call(this, 'POST', endpoint, sendData[endpoint], (sendData[endpoint]! as IDataObject).qs! as IDataObject);
}
} catch (error) {
if (this.continueOnFail()) {
return [this.helpers.returnJsonArray({ error: error.message })];
}
throw error;
}
// Return the incoming data
return [items];
}
// https://coda.io/developers/apis/v1beta1#operation/getRow
if (operation === 'getRow') {
for (let i = 0; i < items.length; i++) {
try {
const docId = this.getNodeParameter('docId', i) as string;
const tableId = this.getNodeParameter('tableId', i) as string;
const rowId = this.getNodeParameter('rowId', i) as string;
const options = this.getNodeParameter('options', i) as IDataObject;
const endpoint = `/docs/${docId}/tables/${tableId}/rows/${rowId}`;
if (options.useColumnNames === false) {
qs.useColumnNames = options.useColumnNames as boolean;
} else {
qs.useColumnNames = true;
}
if (options.valueFormat) {
qs.valueFormat = options.valueFormat as string;
}
responseData = await codaApiRequest.call(this, 'GET', endpoint, {}, qs);
if (options.rawData === true) {
returnData.push(responseData);
} else {
returnData.push({
id: responseData.id,
...responseData.values,
});
}
} catch (error) {
if (this.continueOnFail()) {
returnData.push({ error: error.message });
continue;
}
throw error;
}
}
return [this.helpers.returnJsonArray(returnData)];
}
// https://coda.io/developers/apis/v1beta1#operation/listRows
if (operation === 'getAllRows') {
const docId = this.getNodeParameter('docId', 0) as string;
const returnAll = this.getNodeParameter('returnAll', 0) as boolean;
const tableId = this.getNodeParameter('tableId', 0) as string;
const options = this.getNodeParameter('options', 0) as IDataObject;
const endpoint = `/docs/${docId}/tables/${tableId}/rows`;
if (options.useColumnNames === false) {
qs.useColumnNames = options.useColumnNames as boolean;
} else {
qs.useColumnNames = true;
}
if (options.valueFormat) {
qs.valueFormat = options.valueFormat as string;
}
if (options.sortBy) {
qs.sortBy = options.sortBy as string;
}
if (options.visibleOnly) {
qs.visibleOnly = options.visibleOnly as boolean;
}
if (options.query) {
qs.query = options.query as string;
}
try {
if (returnAll === true) {
responseData = await codaApiRequestAllItems.call(this, 'items', 'GET', endpoint, {}, qs);
} else {
qs.limit = this.getNodeParameter('limit', 0) as number;
responseData = await codaApiRequest.call(this, 'GET', endpoint, {}, qs);
responseData = responseData.items;
}
} catch (error) {
if (this.continueOnFail()) {
return [this.helpers.returnJsonArray({ error: error.message })];
}
throw new NodeApiError(this.getNode(), error);
}
if (options.rawData === true) {
return [this.helpers.returnJsonArray(responseData)];
} else {
for (const item of responseData) {
returnData.push({
id: item.id,
...item.values,
});
}
return [this.helpers.returnJsonArray(returnData)];
}
}
// https://coda.io/developers/apis/v1beta1#operation/deleteRows
if (operation === 'deleteRow') {
try {
const sendData = {} as IDataObject;
for (let i = 0; i < items.length; i++) {
const docId = this.getNodeParameter('docId', i) as string;
const tableId = this.getNodeParameter('tableId', i) as string;
const rowId = this.getNodeParameter('rowId', i) as string;
const endpoint = `/docs/${docId}/tables/${tableId}/rows`;
// Collect all the data for the different docs/tables
if (sendData[endpoint] === undefined) {
sendData[endpoint] = [];
}
(sendData[endpoint] as string[]).push(rowId);
}
// Now that all data got collected make all the requests
for (const endpoint of Object.keys(sendData)) {
await codaApiRequest.call(this, 'DELETE', endpoint, { rowIds: sendData[endpoint]}, qs);
}
} catch (error) {
if (this.continueOnFail()) {
return [this.helpers.returnJsonArray({ error: error.message })];
}
throw error;
}
// Return the incoming data
return [items];
}
// https://coda.io/developers/apis/v1beta1#operation/pushButton
if (operation === 'pushButton') {
for (let i = 0; i < items.length; i++) {
try {
const docId = this.getNodeParameter('docId', i) as string;
const tableId = this.getNodeParameter('tableId', i) as string;
const rowId = this.getNodeParameter('rowId', i) as string;
const columnId = this.getNodeParameter('columnId', i) as string;
const endpoint = `/docs/${docId}/tables/${tableId}/rows/${rowId}/buttons/${columnId}`;
responseData = await codaApiRequest.call(this, 'POST', endpoint, {});
returnData.push(responseData);
} catch (error) {
if (this.continueOnFail()) {
returnData.push({ error: error.message });
continue;
}
throw error;
}
}
return [this.helpers.returnJsonArray(returnData)];
}
//https://coda.io/developers/apis/v1beta1#operation/getColumn
if (operation === 'getColumn') {
for (let i = 0; i < items.length; i++) {
try {
const docId = this.getNodeParameter('docId', i) as string;
const tableId = this.getNodeParameter('tableId', i) as string;
const columnId = this.getNodeParameter('columnId', i) as string;
const endpoint = `/docs/${docId}/tables/${tableId}/columns/${columnId}`;
responseData = await codaApiRequest.call(this, 'GET', endpoint, {});
returnData.push(responseData);
} catch (error) {
if (this.continueOnFail()) {
returnData.push({ error: error.message });
continue;
}
throw error;
}
}
return [this.helpers.returnJsonArray(returnData)];
}
//https://coda.io/developers/apis/v1beta1#operation/listColumns
if (operation === 'getAllColumns') {
for (let i = 0; i < items.length; i++) {
try {
const returnAll = this.getNodeParameter('returnAll', 0) as boolean;
const docId = this.getNodeParameter('docId', i) as string;
const tableId = this.getNodeParameter('tableId', i) as string;
const endpoint = `/docs/${docId}/tables/${tableId}/columns`;
if (returnAll) {
responseData = await codaApiRequestAllItems.call(this, 'items', 'GET', endpoint, {});
} else {
qs.limit = this.getNodeParameter('limit', 0) as number;
responseData = await codaApiRequest.call(this, 'GET', endpoint, {}, qs);
responseData = responseData.items;
}
returnData.push.apply(returnData,responseData);
} catch (error) {
if (this.continueOnFail()) {
returnData.push({ error: error.message });
continue;
}
throw error;
}
}
return [this.helpers.returnJsonArray(returnData)];
}
}
if (resource === 'formula') {
//https://coda.io/developers/apis/v1beta1#operation/getFormula
if (operation === 'get') {
for (let i = 0; i < items.length; i++) {
try {
const docId = this.getNodeParameter('docId', i) as string;
const formulaId = this.getNodeParameter('formulaId', i) as string;
const endpoint = `/docs/${docId}/formulas/${formulaId}`;
responseData = await codaApiRequest.call(this, 'GET', endpoint, {});
returnData.push(responseData);
} catch (error) {
if (this.continueOnFail()) {
returnData.push({ error: error.message });
continue;
}
throw error;
}
}
return [this.helpers.returnJsonArray(returnData)];
}
//https://coda.io/developers/apis/v1beta1#operation/listFormulas
if (operation === 'getAll') {
for (let i = 0; i < items.length; i++) {
try {
const returnAll = this.getNodeParameter('returnAll', 0) as boolean;
const docId = this.getNodeParameter('docId', i) as string;
const endpoint = `/docs/${docId}/formulas`;
if (returnAll) {
responseData = await codaApiRequestAllItems.call(this, 'items', 'GET', endpoint, {});
} else {
qs.limit = this.getNodeParameter('limit', 0) as number;
responseData = await codaApiRequest.call(this, 'GET', endpoint, {}, qs);
responseData = responseData.items;
}
returnData.push.apply(returnData,responseData);
} catch (error) {
if (this.continueOnFail()) {
returnData.push({ error: error.message });
continue;
}
throw error;
}
}
return [this.helpers.returnJsonArray(returnData)];
}
}
if (resource === 'control') {
//https://coda.io/developers/apis/v1beta1#operation/getControl
if (operation === 'get') {
for (let i = 0; i < items.length; i++) {
try {
const docId = this.getNodeParameter('docId', i) as string;
const controlId = this.getNodeParameter('controlId', i) as string;
const endpoint = `/docs/${docId}/controls/${controlId}`;
responseData = await codaApiRequest.call(this, 'GET', endpoint, {});
returnData.push(responseData);
} catch (error) {
if (this.continueOnFail()) {
returnData.push({ error: error.message });
continue;
}
throw error;
}
}
return [this.helpers.returnJsonArray(returnData)];
}
//https://coda.io/developers/apis/v1beta1#operation/listControls
if (operation === 'getAll') {
for (let i = 0; i < items.length; i++) {
try {
const returnAll = this.getNodeParameter('returnAll', 0) as boolean;
const docId = this.getNodeParameter('docId', i) as string;
const endpoint = `/docs/${docId}/controls`;
if (returnAll) {
responseData = await codaApiRequestAllItems.call(this, 'items', 'GET', endpoint, {});
} else {
qs.limit = this.getNodeParameter('limit', 0) as number;
responseData = await codaApiRequest.call(this, 'GET', endpoint, {}, qs);
responseData = responseData.items;
}
returnData.push.apply(returnData,responseData);
} catch (error) {
if (this.continueOnFail()) {
returnData.push({ error: error.message });
continue;
}
throw error;
}
}
return [this.helpers.returnJsonArray(returnData)];
}
}
if (resource === 'view') {
//https://coda.io/developers/apis/v1beta1#operation/getView
if (operation === 'get') {
for (let i = 0; i < items.length; i++) {
const docId = this.getNodeParameter('docId', i) as string;
const viewId = this.getNodeParameter('viewId', i) as string;
const endpoint = `/docs/${docId}/tables/${viewId}`;
responseData = await codaApiRequest.call(this, 'GET', endpoint, {});
returnData.push(responseData);
}
return [this.helpers.returnJsonArray(returnData)];
}
//https://coda.io/developers/apis/v1beta1#operation/listViews
if (operation === 'getAll') {
for (let i = 0; i < items.length; i++) {
try {
const returnAll = this.getNodeParameter('returnAll', 0) as boolean;
const docId = this.getNodeParameter('docId', i) as string;
const endpoint = `/docs/${docId}/tables?tableTypes=view`;
if (returnAll) {
responseData = await codaApiRequestAllItems.call(this, 'items', 'GET', endpoint, {});
} else {
qs.limit = this.getNodeParameter('limit', 0) as number;
responseData = await codaApiRequest.call(this, 'GET', endpoint, {}, qs);
responseData = responseData.items;
}
returnData.push.apply(returnData,responseData);
} catch (error) {
if (this.continueOnFail()) {
returnData.push({ error: error.message });
continue;
}
throw error;
}
}
return [this.helpers.returnJsonArray(returnData)];
}
if (operation === 'getAllViewRows') {
const docId = this.getNodeParameter('docId', 0) as string;
const returnAll = this.getNodeParameter('returnAll', 0) as boolean;
const viewId = this.getNodeParameter('viewId', 0) as string;
const options = this.getNodeParameter('options', 0) as IDataObject;
const endpoint = `/docs/${docId}/tables/${viewId}/rows`;
if (options.useColumnNames === false) {
qs.useColumnNames = options.useColumnNames as boolean;
} else {
qs.useColumnNames = true;
}
if (options.valueFormat) {
qs.valueFormat = options.valueFormat as string;
}
if (options.sortBy) {
qs.sortBy = options.sortBy as string;
}
if (options.query) {
qs.query = options.query as string;
}
try {
if (returnAll === true) {
responseData = await codaApiRequestAllItems.call(this, 'items', 'GET', endpoint, {}, qs);
} else {
qs.limit = this.getNodeParameter('limit', 0) as number;
responseData = await codaApiRequest.call(this, 'GET', endpoint, {}, qs);
responseData = responseData.items;
}
} catch (error) {
if (this.continueOnFail()) {
return [this.helpers.returnJsonArray({ error: error.message })];
}
throw new NodeApiError(this.getNode(), error);
}
if (options.rawData === true) {
return [this.helpers.returnJsonArray(responseData)];
} else {
for (const item of responseData) {
returnData.push({
id: item.id,
...item.values,
});
}
return [this.helpers.returnJsonArray(returnData)];
}
}
//https://coda.io/developers/apis/v1beta1#operation/deleteViewRow
if (operation === 'deleteViewRow') {
for (let i = 0; i < items.length; i++) {
try {
const docId = this.getNodeParameter('docId', i) as string;
const viewId = this.getNodeParameter('viewId', i) as string;
const rowId = this.getNodeParameter('rowId', i) as string;
const endpoint = `/docs/${docId}/tables/${viewId}/rows/${rowId}`;
responseData = await codaApiRequest.call(this, 'DELETE', endpoint);
returnData.push.apply(returnData,responseData);
} catch (error) {
if (this.continueOnFail()) {
returnData.push({ error: error.message });
continue;
}
throw error;
}
}
return [this.helpers.returnJsonArray(returnData)];
}
//https://coda.io/developers/apis/v1beta1#operation/pushViewButton
if (operation === 'pushViewButton') {
for (let i = 0; i < items.length; i++) {
try {
const docId = this.getNodeParameter('docId', i) as string;
const viewId = this.getNodeParameter('viewId', i) as string;
const rowId = this.getNodeParameter('rowId', i) as string;
const columnId = this.getNodeParameter('columnId', i) as string;
const endpoint = `/docs/${docId}/tables/${viewId}/rows/${rowId}/buttons/${columnId}`;
responseData = await codaApiRequest.call(this, 'POST', endpoint);
returnData.push.apply(returnData,responseData);
} catch (error) {
if (this.continueOnFail()) {
returnData.push({ error: error.message });
continue;
}
throw error;
}
}
return [this.helpers.returnJsonArray(returnData)];
}
if (operation === 'getAllViewColumns') {
for (let i = 0; i < items.length; i++) {
try {
const returnAll = this.getNodeParameter('returnAll', 0) as boolean;
const docId = this.getNodeParameter('docId', i) as string;
const viewId = this.getNodeParameter('viewId', i) as string;
const endpoint = `/docs/${docId}/tables/${viewId}/columns`;
if (returnAll) {
responseData = await codaApiRequestAllItems.call(this, 'items', 'GET', endpoint, {});
} else {
qs.limit = this.getNodeParameter('limit', 0) as number;
responseData = await codaApiRequest.call(this, 'GET', endpoint, {}, qs);
responseData = responseData.items;
}
returnData.push.apply(returnData,responseData);
} catch (error) {
if (this.continueOnFail()) {
returnData.push({ error: error.message });
continue;
}
throw error;
}
}
return [this.helpers.returnJsonArray(returnData)];
}
//https://coda.io/developers/apis/v1beta1#operation/updateViewRow
if (operation === 'updateViewRow') {
for (let i = 0; i < items.length; i++) {
try {
qs = {};
const docId = this.getNodeParameter('docId', i) as string;
const viewId = this.getNodeParameter('viewId', i) as string;
const rowId = this.getNodeParameter('rowId', i) as string;
const keyName = this.getNodeParameter('keyName', i) as string;
const options = this.getNodeParameter('options', i) as IDataObject;
const body: IDataObject = {};
const endpoint = `/docs/${docId}/tables/${viewId}/rows/${rowId}`;
if (options.disableParsing) {
qs.disableParsing = options.disableParsing as boolean;
}
const cells = [];
cells.length = 0;
//@ts-ignore
for (const key of Object.keys(items[i].json[keyName])) {
cells.push({
column: key,
//@ts-ignore
value: items[i].json[keyName][key],
});
}
body.row = {
cells,
};
await codaApiRequest.call(this, 'PUT', endpoint, body, qs);
} catch (error) {
if (this.continueOnFail()) {
items[i].json = { error: error.message };
continue;
}
throw error;
}
}
return [items];
}
}
return [];
}
} | the_stack |
import { Source, SourceResolver, sourcePositionToStringKey } from "../src/source-resolver";
import { SelectionBroker } from "../src/selection-broker";
import { View } from "../src/view";
import { MySelection } from "../src/selection";
import { ViewElements } from "../src/util";
import { SelectionHandler } from "./selection-handler";
export enum CodeMode {
MAIN_SOURCE = "main function",
INLINED_SOURCE = "inlined function"
}
export class CodeView extends View {
broker: SelectionBroker;
source: Source;
sourceResolver: SourceResolver;
codeMode: CodeMode;
sourcePositionToHtmlElement: Map<string, HTMLElement>;
showAdditionalInliningPosition: boolean;
selectionHandler: SelectionHandler;
selection: MySelection;
createViewElement() {
const sourceContainer = document.createElement("div");
sourceContainer.classList.add("source-container");
return sourceContainer;
}
constructor(parent: HTMLElement, broker: SelectionBroker, sourceResolver: SourceResolver, sourceFunction: Source, codeMode: CodeMode) {
super(parent);
const view = this;
view.broker = broker;
view.sourceResolver = sourceResolver;
view.source = sourceFunction;
view.codeMode = codeMode;
this.sourcePositionToHtmlElement = new Map();
this.showAdditionalInliningPosition = false;
const selectionHandler = {
clear: function () {
view.selection.clear();
view.updateSelection();
broker.broadcastClear(this);
},
select: function (sourcePositions, selected) {
const locations = [];
for (const sourcePosition of sourcePositions) {
locations.push(sourcePosition);
sourceResolver.addInliningPositions(sourcePosition, locations);
}
if (locations.length == 0) return;
view.selection.select(locations, selected);
view.updateSelection();
broker.broadcastSourcePositionSelect(this, locations, selected);
},
brokeredSourcePositionSelect: function (locations, selected) {
const firstSelect = view.selection.isEmpty();
for (const location of locations) {
const translated = sourceResolver.translateToSourceId(view.source.sourceId, location);
if (!translated) continue;
view.selection.select([translated], selected);
}
view.updateSelection(firstSelect);
},
brokeredClear: function () {
view.selection.clear();
view.updateSelection();
},
};
view.selection = new MySelection(sourcePositionToStringKey);
broker.addSourcePositionHandler(selectionHandler);
this.selectionHandler = selectionHandler;
this.initializeCode();
}
addHtmlElementToSourcePosition(sourcePosition, element) {
const key = sourcePositionToStringKey(sourcePosition);
if (this.sourcePositionToHtmlElement.has(key)) {
console.log("Warning: duplicate source position", sourcePosition);
}
this.sourcePositionToHtmlElement.set(key, element);
}
getHtmlElementForSourcePosition(sourcePosition) {
const key = sourcePositionToStringKey(sourcePosition);
return this.sourcePositionToHtmlElement.get(key);
}
updateSelection(scrollIntoView: boolean = false): void {
const mkVisible = new ViewElements(this.divNode.parentNode as HTMLElement);
for (const [sp, el] of this.sourcePositionToHtmlElement.entries()) {
const isSelected = this.selection.isKeySelected(sp);
mkVisible.consider(el, isSelected);
el.classList.toggle("selected", isSelected);
}
mkVisible.apply(scrollIntoView);
}
getCodeHtmlElementName() {
return `source-pre-${this.source.sourceId}`;
}
getCodeHeaderHtmlElementName() {
return `source-pre-${this.source.sourceId}-header`;
}
getHtmlCodeLines(): NodeListOf<HTMLElement> {
const ordereList = this.divNode.querySelector(`#${this.getCodeHtmlElementName()} ol`);
return ordereList.childNodes as NodeListOf<HTMLElement>;
}
onSelectLine(lineNumber: number, doClear: boolean) {
if (doClear) {
this.selectionHandler.clear();
}
const positions = this.sourceResolver.linetoSourcePositions(lineNumber - 1);
if (positions !== undefined) {
this.selectionHandler.select(positions, undefined);
}
}
onSelectSourcePosition(sourcePosition, doClear: boolean) {
if (doClear) {
this.selectionHandler.clear();
}
this.selectionHandler.select([sourcePosition], undefined);
}
initializeCode() {
const view = this;
const source = this.source;
const sourceText = source.sourceText;
if (!sourceText) return;
const sourceContainer = view.divNode;
if (this.codeMode == CodeMode.MAIN_SOURCE) {
sourceContainer.classList.add("main-source");
} else {
sourceContainer.classList.add("inlined-source");
}
const codeHeader = document.createElement("div");
codeHeader.setAttribute("id", this.getCodeHeaderHtmlElementName());
codeHeader.classList.add("code-header");
const codeFileFunction = document.createElement("div");
codeFileFunction.classList.add("code-file-function");
codeFileFunction.innerHTML = `${source.sourceName}:${source.functionName}`;
codeHeader.appendChild(codeFileFunction);
const codeModeDiv = document.createElement("div");
codeModeDiv.classList.add("code-mode");
codeModeDiv.innerHTML = `${this.codeMode}`;
codeHeader.appendChild(codeModeDiv);
const clearDiv = document.createElement("div");
clearDiv.style.clear = "both";
codeHeader.appendChild(clearDiv);
sourceContainer.appendChild(codeHeader);
const codePre = document.createElement("pre");
codePre.setAttribute("id", this.getCodeHtmlElementName());
codePre.classList.add("prettyprint");
sourceContainer.appendChild(codePre);
codeHeader.onclick = function myFunction() {
if (codePre.style.display === "none") {
codePre.style.display = "block";
} else {
codePre.style.display = "none";
}
};
if (sourceText != "") {
codePre.classList.add("linenums");
codePre.textContent = sourceText;
try {
// Wrap in try to work when offline.
PR.prettyPrint(undefined, sourceContainer);
} catch (e) {
console.log(e);
}
view.divNode.onclick = function (e: MouseEvent) {
if (e.target instanceof Element && e.target.tagName == "DIV") {
const targetDiv = e.target as HTMLDivElement;
if (targetDiv.classList.contains("line-number")) {
e.stopPropagation();
view.onSelectLine(Number(targetDiv.dataset.lineNumber), !e.shiftKey);
}
} else {
view.selectionHandler.clear();
}
};
const base: number = source.startPosition;
let current = 0;
const lineListDiv = this.getHtmlCodeLines();
let newlineAdjust = 0;
for (let i = 0; i < lineListDiv.length; i++) {
// Line numbers are not zero-based.
const lineNumber = i + 1;
const currentLineElement = lineListDiv[i];
currentLineElement.id = "li" + i;
currentLineElement.dataset.lineNumber = "" + lineNumber;
const spans = currentLineElement.childNodes;
for (const currentSpan of spans) {
if (currentSpan instanceof HTMLSpanElement) {
const pos = base + current;
const end = pos + currentSpan.textContent.length;
current += currentSpan.textContent.length;
this.insertSourcePositions(currentSpan, lineNumber, pos, end, newlineAdjust);
newlineAdjust = 0;
}
}
this.insertLineNumber(currentLineElement, lineNumber);
while ((current < sourceText.length) &&
(sourceText[current] == '\n' || sourceText[current] == '\r')) {
++current;
++newlineAdjust;
}
}
}
}
insertSourcePositions(currentSpan, lineNumber, pos, end, adjust) {
const view = this;
const sps = this.sourceResolver.sourcePositionsInRange(this.source.sourceId, pos - adjust, end);
let offset = 0;
for (const sourcePosition of sps) {
this.sourceResolver.addAnyPositionToLine(lineNumber, sourcePosition);
const textnode = currentSpan.tagName == 'SPAN' ? currentSpan.lastChild : currentSpan;
if (!(textnode instanceof Text)) continue;
const splitLength = Math.max(0, sourcePosition.scriptOffset - pos - offset);
offset += splitLength;
const replacementNode = textnode.splitText(splitLength);
const span = document.createElement('span');
span.setAttribute("scriptOffset", sourcePosition.scriptOffset);
span.classList.add("source-position");
const marker = document.createElement('span');
marker.classList.add("marker");
span.appendChild(marker);
const inlining = this.sourceResolver.getInliningForPosition(sourcePosition);
if (inlining != undefined && view.showAdditionalInliningPosition) {
const sourceName = this.sourceResolver.getSourceName(inlining.sourceId);
const inliningMarker = document.createElement('span');
inliningMarker.classList.add("inlining-marker");
inliningMarker.setAttribute("data-descr", `${sourceName} was inlined here`);
span.appendChild(inliningMarker);
}
span.onclick = function (e) {
e.stopPropagation();
view.onSelectSourcePosition(sourcePosition, !e.shiftKey);
};
view.addHtmlElementToSourcePosition(sourcePosition, span);
textnode.parentNode.insertBefore(span, replacementNode);
}
}
insertLineNumber(lineElement: HTMLElement, lineNumber: number) {
const view = this;
const lineNumberElement = document.createElement("div");
lineNumberElement.classList.add("line-number");
lineNumberElement.dataset.lineNumber = `${lineNumber}`;
lineNumberElement.innerText = `${lineNumber}`;
lineElement.insertBefore(lineNumberElement, lineElement.firstChild);
// Don't add lines to source positions of not in backwardsCompatibility mode.
if (this.source.backwardsCompatibility === true) {
for (const sourcePosition of this.sourceResolver.linetoSourcePositions(lineNumber - 1)) {
view.addHtmlElementToSourcePosition(sourcePosition, lineElement);
}
}
}
} | the_stack |
import { rectangle, line, ellipse } from './wired-lib';
import { randomSeed, fireEvent } from './wired-base';
import { css, TemplateResult, html, LitElement, PropertyValues } from 'lit';
import { customElement, property } from 'lit/decorators.js';
interface AreaSize {
width: number;
height: number;
}
interface CalendarCell {
value: string;
text: string;
selected: boolean;
dimmed: boolean;
disabled?: boolean;
}
// GLOBAL CONSTANTS
const SECOND = 1000;
const MINUTE = SECOND * 60;
const HOUR = MINUTE * 60;
const DAY = HOUR * 24;
const TABLE_PADDING = 8; // pixels
@customElement('wired-calendar')
export class WiredCalendar extends LitElement {
@property({ type: Number }) elevation = 3;
@property({ type: String }) selected?: string; // pre-selected date
@property({ type: String }) firstdate?: string; // date range lower limit
@property({ type: String }) lastdate?: string; // date range higher limit
@property({ type: String }) locale?: string; // BCP 47 language tag like `es-MX`
@property({ type: Boolean, reflect: true }) disabled = false;
@property({ type: Boolean, reflect: true }) initials = false; // days of week
@property({ type: Object }) value?: { date: Date, text: string };
@property({ type: Function }) format: Function = (d: Date) => this.months_short[d.getMonth()] + ' ' + d.getDate() + ', ' + d.getFullYear();
// Initial calendar headers (will be replaced if different locale than `en` or `en-US`)
private weekdays_short: string[] = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
private months: string[] = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
// Fix month shorts for internal value comparations (not changed by locale)
private months_short: string[] = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
private resizeHandler?: EventListenerOrEventListenerObject;
private firstOfMonthDate: Date = new Date(); // Only month and year relevant
private fDate: Date | undefined = undefined; // Date obj for firstdate string
private lDate: Date | undefined = undefined; // Date obj for lastdate string
private calendarRefSize: AreaSize = { width: 0, height: 0 };
private tblColWidth: number = 0;
private tblRowHeight: number = 0;
private tblHeadHeight: number = 0;
private monthYear: string = '';
private weeks: CalendarCell[][] = [[]];
private seed = randomSeed();
connectedCallback() {
super.connectedCallback();
if (!this.resizeHandler) {
this.resizeHandler = this.debounce(this.resized.bind(this), 200, false, this);
window.addEventListener('resize', this.resizeHandler, { passive: true });
}
// Initial setup (now that `wired-calendar` element is ready in DOM)
this.localizeCalendarHeaders();
this.setInitialConditions();
this.computeCalendar();
this.refreshSelection();
setTimeout(() => this.updated());
}
disconnectedCallback() {
super.disconnectedCallback();
if (this.resizeHandler) {
window.removeEventListener('resize', this.resizeHandler);
delete this.resizeHandler;
}
}
static get styles() {
return css`
:host {
display: inline-block;
font-family: inherit;
position: relative;
outline: none;
opacity: 0;
}
:host(.wired-disabled) {
opacity: 0.5 !important;
cursor: default;
pointer-events: none;
background: rgba(0, 0, 0, 0.02);
}
:host(.wired-rendered) {
opacity: 1;
}
:host(:focus) path {
stroke-width: 1.5;
}
.overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
pointer-events: none;
}
svg {
display: block;
}
.calendar path {
stroke: var(--wired-calendar-color, black);
stroke-width: 0.7;
fill: transparent;
}
.selected path {
stroke: var(--wired-calendar-selected-color, red);
stroke-width: 2.5;
fill: transparent;
transition: transform 0.05s ease;
}
table {
position: relative;
background: var(--wired-calendar-bg, white);
border-collapse: collapse;
font-size: inherit;
text-transform: capitalize;
line-height: unset;
cursor: default;
overflow: hidden;
}
table:focus {
outline: none !important;
}
td,
th {
border-radius: 4px;
text-align: center;
}
td.disabled {
color: var(--wired-calendar-disabled-color, lightgray);
cursor: not-allowed;
}
td.dimmed {
color: var(--wired-calendar-dimmed-color, gray);
}
td.selected {
position: absolute;
}
td:not(.disabled):not(.selected):hover {
background-color: #d0d0d0;
cursor: pointer;
}
.pointer {
cursor: pointer;
}
`;
}
render(): TemplateResult {
/*
* Template to render a one month calendar
*
* The template consists of one `table` and one overlay `div`.
* The `table` consiste of two header rows plus one row for each week of the month.
* The underlaying data is an array of weeks. Each week consist of an array of days.
* The days are objects with `CalendarCell` interface. Each one is rendered ...
* ... according with the boolean conditions `disabled` and `selected`.
* Particulary, a `selected` day is rendered with its own extra overlay ...
* ... (and svg tag) to draw over it.
*/
return html`
<table style="width:${this.calendarRefSize.width}px;height:${this.calendarRefSize.height}px;border:${TABLE_PADDING}px solid transparent"
@mousedown="${this.onItemClick}"
@touchstart="${this.onItemClick}">
${ /* 1st header row with calendar title and prev/next controls */ ''}
<tr class="top-header" style="height:${this.tblHeadHeight}px;">
<th id="prevCal" class="pointer" @click="${this.onPrevClick}"><<</th>
<th colSpan="5">${this.monthYear}</th>
<th id="nextCal" class="pointer" @click="${this.onNextClick}">>></th>
</tr>
${ /* 2nd header row with the seven weekdays names (short or initials) */ ''}
<tr class="header" style="height:${this.tblHeadHeight}px;">
${this.weekdays_short
.map((d) =>
html`<th style="width: ${this.tblColWidth};">${this.initials ? d[0] : d}</th>
`
)
}
</tr>
${ /* Loop thru weeks building one row `<tr>` for each week */ ''}
${this.weeks
.map((weekDays: CalendarCell[]) =>
html`<tr style="height:${this.tblRowHeight}px;">
${ /* Loop thru weeekdays in each week building one data cell `<td>` for each day */ ''}
${weekDays
.map((d: CalendarCell) =>
// This blank space left on purpose for clarity
html`${d.selected ?
// Render "selected" cell
html`
<td class="selected" value="${d.value}">
<div style="width: ${this.tblColWidth}px; line-height:${this.tblRowHeight}px;">${d.text}</div>
<div class="overlay">
<svg id="svgTD" class="selected"></svg>
</div></td>
` :
// Render "not selected" cell
html`
<td .className="${d.disabled ? 'disabled' : (d.dimmed ? 'dimmed' : '')}"
value="${d.disabled ? '' : d.value}">${d.text}</td>
`}
`
// This blank space left on purpose for clarity
)
}${ /* End `weekDays` map loop */ ''}
</tr>`
)
}${ /* End `weeks` map loop */ ''}
</table>
<div class="overlay">
<svg id="svg" class="calendar"></svg>
</div>
`;
}
firstUpdated() {
this.setAttribute('role', 'dialog');
}
updated(changed?: PropertyValues) {
if (changed && changed instanceof Map) {
if (changed.has('disabled')) this.refreshDisabledState();
if (changed.has('selected')) this.refreshSelection();
}
// Redraw calendar sketchy bounding box
const svg = (this.shadowRoot!.getElementById('svg') as any) as SVGSVGElement;
while (svg.hasChildNodes()) {
svg.removeChild(svg.lastChild!);
}
const s: AreaSize = this.getCalendarSize();
const elev = Math.min(Math.max(1, this.elevation), 5);
const w = s.width + ((elev - 1) * 2);
const h = s.height + ((elev - 1) * 2);
svg.setAttribute('width', `${w}`);
svg.setAttribute('height', `${h}`);
rectangle(svg, 2, 2, s.width - 4, s.height - 4, this.seed);
for (let i = 1; i < elev; i++) {
(line(svg, (i * 2), s.height - 4 + (i * 2), s.width - 4 + (i * 2), s.height - 4 + (i * 2), this.seed)).style.opacity = `${(85 - (i * 10)) / 100}`;
(line(svg, s.width - 4 + (i * 2), s.height - 4 + (i * 2), s.width - 4 + (i * 2), i * 2, this.seed)).style.opacity = `${(85 - (i * 10)) / 100}`;
(line(svg, (i * 2), s.height - 4 + (i * 2), s.width - 4 + (i * 2), s.height - 4 + (i * 2), this.seed)).style.opacity = `${(85 - (i * 10)) / 100}`;
(line(svg, s.width - 4 + (i * 2), s.height - 4 + (i * 2), s.width - 4 + (i * 2), i * 2, this.seed)).style.opacity = `${(85 - (i * 10)) / 100}`;
}
// Redraw sketchy red circle `selected` cell
const svgTD = (this.shadowRoot!.getElementById('svgTD') as any) as SVGSVGElement;
if (svgTD) {
while (svgTD.hasChildNodes()) {
svgTD.removeChild(svgTD.lastChild!);
}
const iw = Math.max(this.tblColWidth * 1.0, 20);
const ih = Math.max(this.tblRowHeight * 0.9, 18);
const c = ellipse(svgTD, this.tblColWidth / 2, this.tblRowHeight / 2, iw, ih, this.seed);
svgTD.appendChild(c);
}
this.classList.add('wired-rendered');
}
setSelectedDate(formatedDate: string): void {
// TODO: Validate `formatedDate`
this.selected = formatedDate;
if (this.selected) {
const d = new Date(this.selected);
this.firstOfMonthDate = new Date(d.getFullYear(), d.getMonth(), 1);
this.computeCalendar();
this.requestUpdate();
this.fireSelected();
}
}
/* private methods */
/*
* Change calendar headers according to locale parameter or browser locale
* Notes:
* This only change the rendered text in the calendar
* All the internal parsing of string dates do not use locale
*/
private localizeCalendarHeaders() {
// Find locale preference when parameter not set
if (!this.locale) {
// Guess from different browser possibilities
const n: any = navigator;
if (n.hasOwnProperty('systemLanguage')) this.locale = n['systemLanguage'];
else if (n.hasOwnProperty('browserLanguage')) this.locale = n['browserLanguage'];
else this.locale = (navigator.languages || ['en'])[0];
}
// Replace localized calendar texts when not `en-US` or not `en`
const l = (this.locale || '').toLowerCase();
if (l !== 'en-us' && l !== 'en') {
const d = new Date();
// Compute weekday header texts (like "Sun", "Mon", "Tue", ...)
const weekDayOffset = d.getUTCDay();
const daySunday = new Date(d.getTime() - DAY * weekDayOffset);
for (let i = 0; i < 7; i++) {
const weekdayDate = new Date(daySunday);
weekdayDate.setDate(daySunday.getDate() + i);
this.weekdays_short[i] = weekdayDate.toLocaleString(this.locale, { weekday: 'short' });
}
// Compute month header texts (like "January", "February", ...)
d.setDate(1); // Set to first of the month to avoid cases like "February 30"
for (let m = 0; m < 12; m++) {
d.setMonth(m);
this.months[m] = d.toLocaleString(this.locale, { month: 'long' });
// Beware: month shorts are used in `en-US` internally. Do not change.
// this.months_short[m] = d.toLocaleString(this.locale, {month: 'short'});
}
}
}
private setInitialConditions() {
// Initialize calendar element size
this.calendarRefSize = this.getCalendarSize();
// Define an initial reference date either from a paramenter or new today date
let d: Date;
// TODO: Validate `this.selected`
if (this.selected) {
// TODO: Validate `this.selected`
d = new Date(this.selected);
this.value = { date: new Date(this.selected), text: this.selected };
} else {
d = new Date();
}
// Define a reference date used to build one month calendar
this.firstOfMonthDate = new Date(d.getFullYear(), d.getMonth(), 1);
// Convert string paramenters (when present) to Date objects
// TODO: Validate `this.firstdate`
if (this.firstdate) this.fDate = new Date(this.firstdate);
// TODO: Validate `this.lastdate`
if (this.lastdate) this.lDate = new Date(this.lastdate);
}
private refreshSelection() {
// Loop thru all weeks and thru all day in each week
this.weeks.forEach((week: CalendarCell[]) =>
week.forEach((day: CalendarCell) => {
// Set calendar day `selected` according to user's `this.selected`
day.selected = this.selected && (day.value === this.selected) || false;
})
);
this.requestUpdate();
}
private resized(): void {
// Reinitialize calendar element size
this.calendarRefSize = this.getCalendarSize();
this.computeCalendar();
this.refreshSelection();
}
private getCalendarSize(): AreaSize {
const limits = this.getBoundingClientRect();
return {
width: limits.width > 180 ? limits.width : 320,
height: limits.height > 180 ? limits.height : 320
};
}
private computeCellsizes(size: AreaSize, rows: number): void {
const numerOfHeaderRows = 2;
const headerRealStateProportion = 0.25; // 1 equals 100%
const borderSpacing = 2; // See browser's table {border-spacing: 2px;}
this.tblColWidth = (size.width / 7) - borderSpacing; // A week has 7 days
this.tblHeadHeight =
(size.height * headerRealStateProportion / numerOfHeaderRows) - borderSpacing;
this.tblRowHeight =
(size.height * (1 - headerRealStateProportion) / rows) - borderSpacing;
}
private refreshDisabledState() {
if (this.disabled) {
this.classList.add('wired-disabled');
} else {
this.classList.remove('wired-disabled');
}
this.tabIndex = this.disabled ? -1 : +(this.getAttribute('tabindex') || 0);
}
private onItemClick(event: CustomEvent) {
event.stopPropagation();
const sel = event.target as HTMLElement;
// Attribute 'value' empty means: is a disabled date (should not be 'selected')
if (sel && sel.hasAttribute('value') && sel.getAttribute('value') !== '') {
this.selected = sel.getAttribute('value') || undefined;
this.refreshSelection();
this.fireSelected();
}
}
private fireSelected() {
if (this.selected) {
this.value = { date: new Date(this.selected), text: this.selected };
fireEvent(this, 'selected', { selected: this.selected });
}
}
private computeCalendar(): void {
// Compute month and year for table header
this.monthYear = this.months[this.firstOfMonthDate.getMonth()] + ' ' + this.firstOfMonthDate.getFullYear();
// Compute all month dates (one per day, 7 days per week, all weeks of the month)
const first_day_in_month = new Date(this.firstOfMonthDate.getFullYear(), this.firstOfMonthDate.getMonth(), 1);
// Initialize offset (negative because calendar commonly starts few days before the first of the month)
let dayInMonthOffset = 0 - first_day_in_month.getDay();
const amountOfWeeks = Math.ceil((new Date(this.firstOfMonthDate.getFullYear(), this.firstOfMonthDate.getMonth() + 1, 0).getDate() - dayInMonthOffset) / 7);
this.weeks = []; // Clear previous weeks
for (let weekIndex = 0; weekIndex < amountOfWeeks; weekIndex++) {
this.weeks[weekIndex] = [];
for (let dayOfWeekIndex = 0; dayOfWeekIndex < 7; dayOfWeekIndex++) {
// Compute day date (using an incrementing offset)
const day = new Date(first_day_in_month.getTime() + DAY * dayInMonthOffset);
const formatedDate: string = this.format(day);
this.weeks[weekIndex][dayOfWeekIndex] = {
value: formatedDate,
text: day.getDate().toString(),
selected: formatedDate === this.selected,
dimmed: day.getMonth() !== first_day_in_month.getMonth(),
disabled: this.isDateOutOfRange(day)
};
// Increment offset (advance one day in calendar)
dayInMonthOffset++;
}
}
// Compute row and column sizes
this.computeCellsizes(this.calendarRefSize, amountOfWeeks);
}
private onPrevClick(): void {
// Is there a preious month limit due to `firstdate`?
if (this.fDate === undefined ||
new Date(this.fDate.getFullYear(), this.fDate.getMonth() - 1, 1).getMonth() !==
new Date(this.firstOfMonthDate.getFullYear(), this.firstOfMonthDate.getMonth() - 1, 1).getMonth()) {
// No limit found, so update `firstOfMonthDate` to first of the previous month
this.firstOfMonthDate = new Date(this.firstOfMonthDate.getFullYear(), this.firstOfMonthDate.getMonth() - 1, 1);
this.computeCalendar();
this.refreshSelection();
}
}
private onNextClick(): void {
// Is there a next month limit due to `lastdate`?
if (this.lDate === undefined ||
new Date(this.lDate.getFullYear(), this.lDate.getMonth() + 1, 1).getMonth() !==
new Date(this.firstOfMonthDate.getFullYear(), this.firstOfMonthDate.getMonth() + 1, 1).getMonth()) {
// No limit found, so update `firstOfMonthDate` to first of the next month
this.firstOfMonthDate = new Date(this.firstOfMonthDate.getFullYear(), this.firstOfMonthDate.getMonth() + 1, 1);
this.computeCalendar();
this.refreshSelection();
}
}
private isDateOutOfRange(day: Date): boolean {
if (this.fDate && this.lDate) {
return day < this.fDate || this.lDate < day;
} else if (this.fDate) {
return day < this.fDate;
} else if (this.lDate) {
return this.lDate < day;
}
return false;
}
/* Util */
private debounce(func: Function, wait: number, immediate: boolean, context: HTMLElement): EventListenerOrEventListenerObject {
let timeout = 0;
return () => {
const args = arguments;
const later = () => {
timeout = 0;
if (!immediate) {
func.apply(context, args);
}
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = window.setTimeout(later, wait);
if (callNow) {
func.apply(context, args);
}
};
}
} | the_stack |
import {
AccountSASPermissions,
AccountSASResourceTypes,
AccountSASServices
} from "@azure/storage-blob";
import Operation from "../generated/artifacts/operation";
import { AccountSASPermission } from "./AccountSASPermissions";
import { AccountSASResourceType } from "./AccountSASResourceTypes";
import { AccountSASService } from "./AccountSASServices";
export class OperationAccountSASPermission {
constructor(
public readonly service: string,
public readonly resourceType: string,
public readonly permission: string
) {}
public validate(
services: AccountSASServices | string,
resourceTypes: AccountSASResourceTypes | string,
permissions: AccountSASPermissions | string
): boolean {
return (
this.validateServices(services) &&
this.validateResourceTypes(resourceTypes) &&
this.validatePermissions(permissions)
);
}
public validateServices(services: AccountSASServices | string): boolean {
return services.toString().includes(this.service);
}
public validateResourceTypes(
resourceTypes: AccountSASResourceTypes | string
): boolean {
for (const p of this.resourceType) {
if (resourceTypes.toString().includes(p)) {
return true;
}
}
return false;
}
public validatePermissions(
permissions: AccountSASPermissions | string
): boolean {
for (const p of this.permission) {
if (permissions.toString().includes(p)) {
return true;
}
}
return false;
}
}
// See https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas
// TODO: Check all required operations
const OPERATION_ACCOUNT_SAS_PERMISSIONS = new Map<
Operation,
OperationAccountSASPermission
>();
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Service_GetAccountInfo,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Service +
AccountSASResourceType.Container +
AccountSASResourceType.Object,
AccountSASPermission.Read +
AccountSASPermission.Create +
AccountSASPermission.Delete +
AccountSASPermission.List +
AccountSASPermission.Process +
AccountSASPermission.Read +
AccountSASPermission.Update +
AccountSASPermission.Write
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Service_GetAccountInfoWithHead,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Service +
AccountSASResourceType.Container +
AccountSASResourceType.Object,
AccountSASPermission.Read +
AccountSASPermission.Create +
AccountSASPermission.Delete +
AccountSASPermission.List +
AccountSASPermission.Process +
AccountSASPermission.Read +
AccountSASPermission.Update +
AccountSASPermission.Write
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Container_GetAccountInfo,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Service +
AccountSASResourceType.Container +
AccountSASResourceType.Object,
AccountSASPermission.Read +
AccountSASPermission.Create +
AccountSASPermission.Delete +
AccountSASPermission.List +
AccountSASPermission.Process +
AccountSASPermission.Read +
AccountSASPermission.Update +
AccountSASPermission.Write
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Container_GetAccountInfoWithHead,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Service +
AccountSASResourceType.Container +
AccountSASResourceType.Object,
AccountSASPermission.Read +
AccountSASPermission.Create +
AccountSASPermission.Delete +
AccountSASPermission.List +
AccountSASPermission.Process +
AccountSASPermission.Read +
AccountSASPermission.Update +
AccountSASPermission.Write
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Blob_GetAccountInfo,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Service +
AccountSASResourceType.Container +
AccountSASResourceType.Object,
AccountSASPermission.Read +
AccountSASPermission.Create +
AccountSASPermission.Delete +
AccountSASPermission.List +
AccountSASPermission.Process +
AccountSASPermission.Read +
AccountSASPermission.Update +
AccountSASPermission.Write
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Blob_GetAccountInfoWithHead,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Service +
AccountSASResourceType.Container +
AccountSASResourceType.Object,
AccountSASPermission.Read +
AccountSASPermission.Create +
AccountSASPermission.Delete +
AccountSASPermission.List +
AccountSASPermission.Process +
AccountSASPermission.Read +
AccountSASPermission.Update +
AccountSASPermission.Write
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Service_ListContainersSegment,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Service,
AccountSASPermission.List
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Service_GetProperties,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Service,
AccountSASPermission.Read
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Service_SetProperties,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Service,
AccountSASPermission.Write
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Service_GetStatistics,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Service,
AccountSASPermission.Read
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Container_Create,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Container,
AccountSASPermission.Create + AccountSASPermission.Write
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Container_SetAccessPolicy,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Container,
"" // NOT ALLOWED
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Container_GetAccessPolicy,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Container,
"" // NOT ALLOWED
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Container_GetProperties,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Container,
AccountSASPermission.Read
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Container_GetPropertiesWithHead,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Container,
AccountSASPermission.Read
)
);
// TODO: Get container metadata is missing in swagger
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Container_SetMetadata,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Container,
AccountSASPermission.Write
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Container_BreakLease,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Container,
AccountSASPermission.Write + AccountSASPermission.Delete
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Container_RenewLease,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Container,
AccountSASPermission.Write
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Container_ChangeLease,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Container,
AccountSASPermission.Write
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Container_AcquireLease,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Container,
AccountSASPermission.Write
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Container_ReleaseLease,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Container,
AccountSASPermission.Write
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Container_Delete,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Container,
AccountSASPermission.Delete
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Container_ListBlobHierarchySegment,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Container,
AccountSASPermission.List
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Container_ListBlobFlatSegment,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Container,
AccountSASPermission.List
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.BlockBlob_Upload,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
// Create permission is only available for non existing block blob. Handle this scenario separately
AccountSASPermission.Write + AccountSASPermission.Create
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.PageBlob_Create,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
// Create permission is only available for non existing page blob. Handle this scenario separately
AccountSASPermission.Write + AccountSASPermission.Create
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.AppendBlob_Create,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
// Create permission is only available for non existing append blob. Handle this scenario separately
AccountSASPermission.Write + AccountSASPermission.Create
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Blob_Download,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
AccountSASPermission.Read
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Blob_GetProperties,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
AccountSASPermission.Read
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Blob_SetHTTPHeaders,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
AccountSASPermission.Write
)
);
// TODO: Get blob metadata is missing in swagger
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Blob_GetProperties,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
AccountSASPermission.Read
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Blob_SetMetadata,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
AccountSASPermission.Write
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Blob_Delete,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
AccountSASPermission.Delete
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Blob_BreakLease,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
AccountSASPermission.Delete + AccountSASPermission.Write
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Blob_RenewLease,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
AccountSASPermission.Write
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Blob_ChangeLease,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
AccountSASPermission.Write
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Blob_AcquireLease,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
AccountSASPermission.Write
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Blob_ReleaseLease,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
AccountSASPermission.Write
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Blob_CreateSnapshot,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
AccountSASPermission.Write + AccountSASPermission.Create
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Blob_StartCopyFromURL,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
// If destination is an existing blob, create permission is not enough
AccountSASPermission.Write + AccountSASPermission.Create
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Blob_CopyFromURL,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
// If destination is an existing blob, create permission is not enough
AccountSASPermission.Write + AccountSASPermission.Create
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.PageBlob_CopyIncremental,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
AccountSASPermission.Write + AccountSASPermission.Create
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Blob_AbortCopyFromURL,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
AccountSASPermission.Write
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.BlockBlob_StageBlock,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
AccountSASPermission.Write
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.BlockBlob_CommitBlockList,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
AccountSASPermission.Write
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.BlockBlob_GetBlockList,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
AccountSASPermission.Read
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.PageBlob_UploadPages,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
AccountSASPermission.Write
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.PageBlob_GetPageRanges,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
AccountSASPermission.Read
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.PageBlob_GetPageRangesDiff,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
AccountSASPermission.Read
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.AppendBlob_AppendBlock,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
AccountSASPermission.Add + AccountSASPermission.Write
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.PageBlob_ClearPages,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
AccountSASPermission.Write
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.Blob_SetTier,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
AccountSASPermission.Write
)
);
OPERATION_ACCOUNT_SAS_PERMISSIONS.set(
Operation.PageBlob_UpdateSequenceNumber,
new OperationAccountSASPermission(
AccountSASService.Blob,
AccountSASResourceType.Object,
AccountSASPermission.Write
)
);
export default OPERATION_ACCOUNT_SAS_PERMISSIONS; | the_stack |
import { Nullable } from "../types";
import { Vector3, Vector2 } from "../Maths/math.vector";
import { StringDictionary } from "./stringDictionary";
// Mainly based on these 2 articles :
// Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx
// & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
/**
* Defines the potential axis of a Joystick
*/
export enum JoystickAxis {
/** X axis */
X,
/** Y axis */
Y,
/** Z axis */
Z
}
/**
* Represents the different customization options available
* for VirtualJoystick
*/
interface VirtualJoystickCustomizations {
/**
* Size of the joystick's puck
*/
puckSize: number;
/**
* Size of the joystick's container
*/
containerSize: number;
/**
* Color of the joystick && puck
*/
color: string;
/**
* Image URL for the joystick's puck
*/
puckImage?: string;
/**
* Image URL for the joystick's container
*/
containerImage?: string;
/**
* Defines the unmoving position of the joystick container
*/
position?: { x: number, y: number };
/**
* Defines whether or not the joystick container is always visible
*/
alwaysVisible: boolean;
/**
* Defines whether or not to limit the movement of the puck to the joystick's container
*/
limitToContainer: boolean;
}
/**
* Class used to define virtual joystick (used in touch mode)
*/
export class VirtualJoystick {
/**
* Gets or sets a boolean indicating that left and right values must be inverted
*/
public reverseLeftRight: boolean;
/**
* Gets or sets a boolean indicating that up and down values must be inverted
*/
public reverseUpDown: boolean;
/**
* Gets the offset value for the position (ie. the change of the position value)
*/
public deltaPosition: Vector3;
/**
* Gets a boolean indicating if the virtual joystick was pressed
*/
public pressed: boolean;
/**
* Canvas the virtual joystick will render onto, default z-index of this is 5
*/
public static Canvas: Nullable<HTMLCanvasElement>;
/**
* boolean indicating whether or not the joystick's puck's movement should be limited to the joystick's container area
*/
public limitToContainer: boolean;
// Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
private static _globalJoystickIndex: number = 0;
private static _alwaysVisibleSticks: number = 0;
private static vjCanvasContext: CanvasRenderingContext2D;
private static vjCanvasWidth: number;
private static vjCanvasHeight: number;
private static halfWidth: number;
private static _GetDefaultOptions(): VirtualJoystickCustomizations {
return {
puckSize: 40,
containerSize: 60,
color: "cyan",
puckImage: undefined,
containerImage: undefined,
position: undefined,
alwaysVisible: false,
limitToContainer: false,
};
}
private _action: () => any;
private _axisTargetedByLeftAndRight: JoystickAxis;
private _axisTargetedByUpAndDown: JoystickAxis;
private _joystickSensibility: number;
private _inversedSensibility: number;
private _joystickPointerId: number;
private _joystickColor: string;
private _joystickPointerPos: Vector2;
private _joystickPreviousPointerPos: Vector2;
private _joystickPointerStartPos: Vector2;
private _deltaJoystickVector: Vector2;
private _leftJoystick: boolean;
private _touches: StringDictionary<{ x: number, y: number, prevX: number, prevY: number } | PointerEvent>;
private _joystickPosition: Nullable<Vector2>;
private _alwaysVisible: boolean;
private _puckImage: HTMLImageElement;
private _containerImage: HTMLImageElement;
// size properties
private _joystickPuckSize: number;
private _joystickContainerSize: number;
private _clearPuckSize: number;
private _clearContainerSize: number;
private _clearPuckSizeOffset: number;
private _clearContainerSizeOffset: number;
private _onPointerDownHandlerRef: (e: PointerEvent) => any;
private _onPointerMoveHandlerRef: (e: PointerEvent) => any;
private _onPointerUpHandlerRef: (e: PointerEvent) => any;
private _onResize: (e: any) => any;
/**
* Creates a new virtual joystick
* @param leftJoystick defines that the joystick is for left hand (false by default)
* @param customizations Defines the options we want to customize the VirtualJoystick
*/
constructor(leftJoystick?: boolean, customizations?: Partial<VirtualJoystickCustomizations>) {
const options = {
...VirtualJoystick._GetDefaultOptions(),
...customizations
};
if (leftJoystick) {
this._leftJoystick = true;
}
else {
this._leftJoystick = false;
}
VirtualJoystick._globalJoystickIndex++;
// By default left & right arrow keys are moving the X
// and up & down keys are moving the Y
this._axisTargetedByLeftAndRight = JoystickAxis.X;
this._axisTargetedByUpAndDown = JoystickAxis.Y;
this.reverseLeftRight = false;
this.reverseUpDown = false;
// collections of pointers
this._touches = new StringDictionary<{ x: number, y: number, prevX: number, prevY: number } | PointerEvent>();
this.deltaPosition = Vector3.Zero();
this._joystickSensibility = 25;
this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
this._onResize = (evt) => {
VirtualJoystick.vjCanvasWidth = window.innerWidth;
VirtualJoystick.vjCanvasHeight = window.innerHeight;
if (VirtualJoystick.Canvas) {
VirtualJoystick.Canvas.width = VirtualJoystick.vjCanvasWidth;
VirtualJoystick.Canvas.height = VirtualJoystick.vjCanvasHeight;
}
VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
};
// injecting a canvas element on top of the canvas 3D game
if (!VirtualJoystick.Canvas) {
window.addEventListener("resize", this._onResize, false);
VirtualJoystick.Canvas = document.createElement("canvas");
VirtualJoystick.vjCanvasWidth = window.innerWidth;
VirtualJoystick.vjCanvasHeight = window.innerHeight;
VirtualJoystick.Canvas.width = window.innerWidth;
VirtualJoystick.Canvas.height = window.innerHeight;
VirtualJoystick.Canvas.style.width = "100%";
VirtualJoystick.Canvas.style.height = "100%";
VirtualJoystick.Canvas.style.position = "absolute";
VirtualJoystick.Canvas.style.backgroundColor = "transparent";
VirtualJoystick.Canvas.style.top = "0px";
VirtualJoystick.Canvas.style.left = "0px";
VirtualJoystick.Canvas.style.zIndex = "5";
(VirtualJoystick.Canvas.style as any).msTouchAction = "none";
VirtualJoystick.Canvas.style.touchAction = "none"; // fix https://forum.babylonjs.com/t/virtualjoystick-needs-to-set-style-touch-action-none-explicitly/9562
// Support for jQuery PEP polyfill
VirtualJoystick.Canvas.setAttribute("touch-action", "none");
let context = VirtualJoystick.Canvas.getContext('2d');
if (!context) {
throw new Error("Unable to create canvas for virtual joystick");
}
VirtualJoystick.vjCanvasContext = context;
VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
VirtualJoystick.vjCanvasContext.lineWidth = 2;
document.body.appendChild(VirtualJoystick.Canvas);
}
VirtualJoystick.halfWidth = VirtualJoystick.Canvas.width / 2;
this.pressed = false;
this.limitToContainer = options.limitToContainer;
// default joystick color
this._joystickColor = options.color;
// default joystick size
this.containerSize = options.containerSize;
this.puckSize = options.puckSize;
if (options.position) {
this.setPosition(options.position.x, options.position.y);
}
if (options.puckImage) {
this.setPuckImage(options.puckImage);
}
if (options.containerImage) {
this.setContainerImage(options.containerImage);
}
if (options.alwaysVisible) {
VirtualJoystick._alwaysVisibleSticks++;
}
// must come after position potentially set
this.alwaysVisible = options.alwaysVisible;
this._joystickPointerId = -1;
// current joystick position
this._joystickPointerPos = new Vector2(0, 0);
this._joystickPreviousPointerPos = new Vector2(0, 0);
// origin joystick position
this._joystickPointerStartPos = new Vector2(0, 0);
this._deltaJoystickVector = new Vector2(0, 0);
this._onPointerDownHandlerRef = (evt) => {
this._onPointerDown(evt);
};
this._onPointerMoveHandlerRef = (evt) => {
this._onPointerMove(evt);
};
this._onPointerUpHandlerRef = (evt) => {
this._onPointerUp(evt);
};
VirtualJoystick.Canvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
VirtualJoystick.Canvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
VirtualJoystick.Canvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
VirtualJoystick.Canvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
VirtualJoystick.Canvas.addEventListener("contextmenu", (evt) => {
evt.preventDefault(); // Disables system menu
}, false);
requestAnimationFrame(() => { this._drawVirtualJoystick(); });
}
/**
* Defines joystick sensibility (ie. the ratio between a physical move and virtual joystick position change)
* @param newJoystickSensibility defines the new sensibility
*/
public setJoystickSensibility(newJoystickSensibility: number) {
this._joystickSensibility = newJoystickSensibility;
this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
}
private _onPointerDown(e: PointerEvent) {
var positionOnScreenCondition: boolean;
e.preventDefault();
if (this._leftJoystick === true) {
positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
}
else {
positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
}
if (positionOnScreenCondition && this._joystickPointerId < 0) {
// First contact will be dedicated to the virtual joystick
this._joystickPointerId = e.pointerId;
if (this._joystickPosition) {
this._joystickPointerStartPos = this._joystickPosition.clone();
this._joystickPointerPos = this._joystickPosition.clone();
this._joystickPreviousPointerPos = this._joystickPosition.clone();
// in case the user only clicks down && doesn't move:
// this ensures the delta is properly set
this._onPointerMove(e);
} else {
this._joystickPointerStartPos.x = e.clientX;
this._joystickPointerStartPos.y = e.clientY;
this._joystickPointerPos = this._joystickPointerStartPos.clone();
this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
}
this._deltaJoystickVector.x = 0;
this._deltaJoystickVector.y = 0;
this.pressed = true;
this._touches.add(e.pointerId.toString(), e);
}
else {
// You can only trigger the action buttons with a joystick declared
if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
this._action();
this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
}
}
}
private _onPointerMove(e: PointerEvent) {
// If the current pointer is the one associated to the joystick (first touch contact)
if (this._joystickPointerId == e.pointerId) {
// limit to container if need be
if (this.limitToContainer) {
let vector = new Vector2(e.clientX - this._joystickPointerStartPos.x, e.clientY - this._joystickPointerStartPos.y);
let distance = vector.length();
if (distance > this.containerSize) {
vector.scaleInPlace(this.containerSize / distance);
}
this._joystickPointerPos.x = this._joystickPointerStartPos.x + vector.x;
this._joystickPointerPos.y = this._joystickPointerStartPos.y + vector.y;
} else {
this._joystickPointerPos.x = e.clientX;
this._joystickPointerPos.y = e.clientY;
}
// create delta vector
this._deltaJoystickVector = this._joystickPointerPos.clone();
this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
// if a joystick is always visible, there will be clipping issues if
// you drag the puck from one over the container of the other
if (0 < VirtualJoystick._alwaysVisibleSticks) {
if (this._leftJoystick) {
this._joystickPointerPos.x = Math.min(VirtualJoystick.halfWidth, this._joystickPointerPos.x);
} else {
this._joystickPointerPos.x = Math.max(VirtualJoystick.halfWidth, this._joystickPointerPos.x);
}
}
var directionLeftRight = this.reverseLeftRight ? -1 : 1;
var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
switch (this._axisTargetedByLeftAndRight) {
case JoystickAxis.X:
this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
break;
case JoystickAxis.Y:
this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
break;
case JoystickAxis.Z:
this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
break;
}
var directionUpDown = this.reverseUpDown ? 1 : -1;
var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
switch (this._axisTargetedByUpAndDown) {
case JoystickAxis.X:
this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
break;
case JoystickAxis.Y:
this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
break;
case JoystickAxis.Z:
this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
break;
}
}
else {
let data = this._touches.get(e.pointerId.toString());
if (data) {
(data as any).x = e.clientX;
(data as any).y = e.clientY;
}
}
}
private _onPointerUp(e: PointerEvent) {
if (this._joystickPointerId == e.pointerId) {
this._clearPreviousDraw();
this._joystickPointerId = -1;
this.pressed = false;
}
else {
var touch = <{ x: number, y: number, prevX: number, prevY: number }>this._touches.get(e.pointerId.toString());
if (touch) {
VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
}
}
this._deltaJoystickVector.x = 0;
this._deltaJoystickVector.y = 0;
this._touches.remove(e.pointerId.toString());
}
/**
* Change the color of the virtual joystick
* @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
*/
public setJoystickColor(newColor: string) {
this._joystickColor = newColor;
}
/**
* Size of the joystick's container
*/
public set containerSize(newSize: number) {
this._joystickContainerSize = newSize;
this._clearContainerSize = ~~(this._joystickContainerSize * 2.1);
this._clearContainerSizeOffset = ~~(this._clearContainerSize / 2);
}
public get containerSize() {
return this._joystickContainerSize;
}
/**
* Size of the joystick's puck
*/
public set puckSize(newSize: number) {
this._joystickPuckSize = newSize;
this._clearPuckSize = ~~(this._joystickPuckSize * 2.1);
this._clearPuckSizeOffset = ~~(this._clearPuckSize / 2);
}
public get puckSize() {
return this._joystickPuckSize;
}
/**
* Clears the set position of the joystick
*/
public clearPosition() {
this.alwaysVisible = false;
this._joystickPosition = null;
}
/**
* Defines whether or not the joystick container is always visible
*/
public set alwaysVisible(value: boolean) {
if (this._alwaysVisible === value) {
return;
}
if (value && this._joystickPosition) {
VirtualJoystick._alwaysVisibleSticks++;
this._alwaysVisible = true;
} else {
VirtualJoystick._alwaysVisibleSticks--;
this._alwaysVisible = false;
}
}
public get alwaysVisible() {
return this._alwaysVisible;
}
/**
* Sets the constant position of the Joystick container
* @param x X axis coordinate
* @param y Y axis coordinate
*/
public setPosition(x: number, y: number) {
// just in case position is moved while the container is visible
if (this._joystickPointerStartPos) {
this._clearPreviousDraw();
}
this._joystickPosition = new Vector2(x, y);
}
/**
* Defines a callback to call when the joystick is touched
* @param action defines the callback
*/
public setActionOnTouch(action: () => any) {
this._action = action;
}
/**
* Defines which axis you'd like to control for left & right
* @param axis defines the axis to use
*/
public setAxisForLeftRight(axis: JoystickAxis) {
switch (axis) {
case JoystickAxis.X:
case JoystickAxis.Y:
case JoystickAxis.Z:
this._axisTargetedByLeftAndRight = axis;
break;
default:
this._axisTargetedByLeftAndRight = JoystickAxis.X;
break;
}
}
/**
* Defines which axis you'd like to control for up & down
* @param axis defines the axis to use
*/
public setAxisForUpDown(axis: JoystickAxis) {
switch (axis) {
case JoystickAxis.X:
case JoystickAxis.Y:
case JoystickAxis.Z:
this._axisTargetedByUpAndDown = axis;
break;
default:
this._axisTargetedByUpAndDown = JoystickAxis.Y;
break;
}
}
/**
* Clears the canvas from the previous puck / container draw
*/
private _clearPreviousDraw() {
var jp = this._joystickPosition || this._joystickPointerStartPos;
// clear container pixels
VirtualJoystick.vjCanvasContext.clearRect(
jp.x - this._clearContainerSizeOffset,
jp.y - this._clearContainerSizeOffset,
this._clearContainerSize,
this._clearContainerSize
);
// clear puck pixels
VirtualJoystick.vjCanvasContext.clearRect(
this._joystickPreviousPointerPos.x - this._clearPuckSizeOffset,
this._joystickPreviousPointerPos.y - this._clearPuckSizeOffset,
this._clearPuckSize,
this._clearPuckSize
);
}
/**
* Loads `urlPath` to be used for the container's image
* @param urlPath defines the urlPath of an image to use
*/
public setContainerImage(urlPath: string) {
var image = new Image();
image.src = urlPath;
image.onload = () => this._containerImage = image;
}
/**
* Loads `urlPath` to be used for the puck's image
* @param urlPath defines the urlPath of an image to use
*/
public setPuckImage(urlPath: string) {
var image = new Image();
image.src = urlPath;
image.onload = () => this._puckImage = image;
}
/**
* Draws the Virtual Joystick's container
*/
private _drawContainer() {
var jp = this._joystickPosition || this._joystickPointerStartPos;
this._clearPreviousDraw();
if (this._containerImage) {
VirtualJoystick.vjCanvasContext.drawImage(
this._containerImage,
jp.x - this.containerSize,
jp.y - this.containerSize,
this.containerSize * 2,
this.containerSize * 2
);
} else {
// outer container
VirtualJoystick.vjCanvasContext.beginPath();
VirtualJoystick.vjCanvasContext.strokeStyle = this._joystickColor;
VirtualJoystick.vjCanvasContext.lineWidth = 2;
VirtualJoystick.vjCanvasContext.arc(jp.x, jp.y, this.containerSize, 0, Math.PI * 2, true);
VirtualJoystick.vjCanvasContext.stroke();
VirtualJoystick.vjCanvasContext.closePath();
// inner container
VirtualJoystick.vjCanvasContext.beginPath();
VirtualJoystick.vjCanvasContext.lineWidth = 6;
VirtualJoystick.vjCanvasContext.strokeStyle = this._joystickColor;
VirtualJoystick.vjCanvasContext.arc(jp.x, jp.y, this.puckSize, 0, Math.PI * 2, true);
VirtualJoystick.vjCanvasContext.stroke();
VirtualJoystick.vjCanvasContext.closePath();
}
}
/**
* Draws the Virtual Joystick's puck
*/
private _drawPuck() {
if (this._puckImage) {
VirtualJoystick.vjCanvasContext.drawImage(
this._puckImage,
this._joystickPointerPos.x - this.puckSize,
this._joystickPointerPos.y - this.puckSize,
this.puckSize * 2,
this.puckSize * 2
);
} else {
VirtualJoystick.vjCanvasContext.beginPath();
VirtualJoystick.vjCanvasContext.strokeStyle = this._joystickColor;
VirtualJoystick.vjCanvasContext.lineWidth = 2;
VirtualJoystick.vjCanvasContext.arc(this._joystickPointerPos.x, this._joystickPointerPos.y, this.puckSize, 0, Math.PI * 2, true);
VirtualJoystick.vjCanvasContext.stroke();
VirtualJoystick.vjCanvasContext.closePath();
}
}
private _drawVirtualJoystick() {
if (this.alwaysVisible) {
this._drawContainer();
}
if (this.pressed) {
this._touches.forEach((key, touch) => {
if ((<PointerEvent>touch).pointerId === this._joystickPointerId) {
if (!this.alwaysVisible) {
this._drawContainer();
}
this._drawPuck();
// store current pointer for next clear
this._joystickPreviousPointerPos = this._joystickPointerPos.clone();
}
else {
VirtualJoystick.vjCanvasContext.clearRect((<any>touch).prevX - 44, (<any>touch).prevY - 44, 88, 88);
VirtualJoystick.vjCanvasContext.beginPath();
VirtualJoystick.vjCanvasContext.fillStyle = "white";
VirtualJoystick.vjCanvasContext.beginPath();
VirtualJoystick.vjCanvasContext.strokeStyle = "red";
VirtualJoystick.vjCanvasContext.lineWidth = 6;
VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
VirtualJoystick.vjCanvasContext.stroke();
VirtualJoystick.vjCanvasContext.closePath();
(<any>touch).prevX = touch.x;
(<any>touch).prevY = touch.y;
}
});
}
requestAnimationFrame(() => { this._drawVirtualJoystick(); });
}
/**
* Release internal HTML canvas
*/
public releaseCanvas() {
if (VirtualJoystick.Canvas) {
VirtualJoystick.Canvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
VirtualJoystick.Canvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
VirtualJoystick.Canvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
VirtualJoystick.Canvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
window.removeEventListener("resize", this._onResize);
document.body.removeChild(VirtualJoystick.Canvas);
VirtualJoystick.Canvas = null;
}
}
} | the_stack |
import { Component, ViewChild, OnInit, NgZone } from '@angular/core';
import { environment } from '../../../environments/environment';
import { AdminService } from '../../shared/admin.service';
import { FileService } from '../../shared/file.service';
import { Session } from '../../shared/session.model';
import { SessionService } from '../../shared/session.service';
import { Speaker } from '../../shared/speaker.model';
import { SpeakerService } from '../../shared/speaker.service';
import { AuthService } from '../../shared/auth.service';
import { TransitionService } from '../../shared/transition.service';
import { ToastComponent } from '../../shared/toast.component';
import * as _ from 'lodash';
@Component({
selector: 'uploads',
templateUrl: './uploads.component.html',
styleUrls: ['./uploads.component.scss']
})
export class UploadsComponent implements OnInit {
baseUrl = environment.production ? '' : 'http://localhost:3000';
@ViewChild('toast') toast: ToastComponent;
speaker: Speaker;
speakerSessions: Session[] = [];
defaultFileString = 'Choose a file...';
headshotFileString = '';
selectedHeadshotFile: File;
w9FileString = '';
selectedW9File: File;
handoutsFileString = '';
selectedHandoutsFile: File;
uploadAllFileString = '';
selectedUploadAllFile: File;
constructor(private transitionService: TransitionService,
private adminService: AdminService,
private authService: AuthService,
private fileService: FileService,
private sessionService: SessionService,
private speakerService: SpeakerService) {
this.authService.user.subscribe(user => {
this.speaker = this.speakerService.getSpeaker(user._id);
});
};
ngOnInit() {
this.headshotFileString = this.defaultFileString;
this.w9FileString = this.defaultFileString;
this.handoutsFileString = this.defaultFileString;
this.uploadAllFileString = this.defaultFileString;
this.transitionService.transition();
this.sessionService.sessionsUnfiltered.subscribe(sessions => {
this.speakerSessions = this.sessionService.getSpeakerSessions(this.speaker._id);
});
}
fileSelected(files: FileList, whichFile: string) {
if (!files[0]) return;
switch (whichFile) {
case 'headshot':
this.selectedHeadshotFile = files[0];
this.headshotFileString = this.selectedHeadshotFile.name;
break;
case 'w9':
this.selectedW9File = files[0];
this.w9FileString = this.selectedW9File.name;
break;
case 'handouts':
this.selectedHandoutsFile = files[0];
this.handoutsFileString = this.selectedHandoutsFile.name;
break;
case 'all':
this.selectedUploadAllFile = files[0];
this.uploadAllFileString = this.selectedUploadAllFile.name;
break;
default:
break;
}
}
validateFile(selectedFile: File, type: string): string {
let typeError = 'Please only upload image files.';
let sizeError = 'Image too large, size limit is 10mb.';
if (type === 'headshot') {
if (selectedFile.type.substring(0, 5) !== 'image') {
return typeError;
}
} /*else if (type === 'w9' || type === 'handouts') {
// Too many valid file types to check for...Care on Brooke's part req'd
if (selectedFile.type.substring(0, 5) !== 'image' &&
selectedFile.type.substring(0, 4) !== 'text' &&
selectedFile.type !== 'application/pdf') {
return typeError;
}
}*/
if (selectedFile.size > 10000000) return sizeError;
return '';
}
upload(directory: string) {
let selectedFile: File;
switch (directory) {
case 'headshot':
selectedFile = this.selectedHeadshotFile;
break;
case 'w9':
selectedFile = this.selectedW9File;
break;
default:
break;
}
if (!selectedFile) {
this.toast.error('Please select a file to upload.');
return;
}
let invalid = this.validateFile(selectedFile, directory);
if (invalid) {
this.toast.error(invalid);
return;
}
let ext = selectedFile.name.split('.').pop();
let userFilename = `${this.speaker.nameLast}_${this.speaker.email}_${directory}.${ext}`;
this.transitionService.setLoading(true);
let data = new FormData();
data.append('userFilename', userFilename);
data.append('file', selectedFile);
let speakerName = this.speaker.nameFirst + ' ' + this.speaker.nameLast;
this.fileService
.uploadToServer(data)
.then(res => {
this.speakerService
.sendToDropbox(userFilename, directory, speakerName)
.then(dbxRes => {
if (dbxRes.status ) {
this.toast.error('Uploaded unsuccessful. Please try again!');
} else {
if (directory === 'headshot') this.speaker.headshot = dbxRes;
else if (directory === 'w9') {
if (!this.speaker.responseForm) this.speaker.responseForm = <any>{};
this.speaker.responseForm.w9 = dbxRes;
}
this.speakerService
.updateSpeaker(this.speaker)
.then(res => {
this.toast.success('Upload success!');
this.transitionService.setLoading(false);
});
}
});
});
}
uploadHandout(sessionId: string) {
if (!this.selectedHandoutsFile) return;
if (!sessionId) {
this.toast.error('Please select the session this handout is for.')
return;
}
let invalid = this.validateFile(this.selectedHandoutsFile, 'handout');
if (invalid) {
this.toast.error(invalid);
return;
}
let selectedSession = _.find(this.speakerSessions, sess => sess._id === sessionId);
let handoutNumber = selectedSession.handouts.length + 1;
let ext = this.selectedHandoutsFile.name.split('.').pop();
let userFilename = `${selectedSession.title.substring(0, 15)}_${this.speaker.email}_${handoutNumber}.${ext}`;
this.transitionService.setLoading(true);
let data = new FormData();
data.append('userFilename', userFilename);
data.append('file', this.selectedHandoutsFile);
let speakerName = this.speaker.nameFirst + ' ' + this.speaker.nameLast;
this.fileService
.uploadToServer(data)
.then(res => {
this.speakerService
.sendToDropbox(userFilename, 'handouts', speakerName)
.then(dbxRes => {
if (dbxRes.status ) {
this.toast.error('Upload unsuccessful. Please try again!');
} else {
if (!selectedSession.handouts) selectedSession.handouts = [];
selectedSession.handouts.push(dbxRes);
this.sessionService
.updateSession(selectedSession, 'handout')
.then(res => {
this.toast.success('Upload success!');
this.transitionService.setLoading(false);
});
}
});
});
}
uploadToAll(uploadTitle: string) {
if (!this.selectedUploadAllFile) return;
let defaultConf = this.adminService.defaultConference.getValue();
let ext = this.selectedUploadAllFile.name.split('.').pop();
let userFilename = `${uploadTitle}.${ext}`;
this.transitionService.setLoading(true);
let data = new FormData();
data.append('userFilename', userFilename);
data.append('file', this.selectedUploadAllFile);
let speakerName = this.speaker.nameFirst + ' ' + this.speaker.nameLast;
this.fileService
.uploadToServer(data)
.then(res => {
this.speakerService
.sendToDropbox(userFilename, 'all', speakerName)
.then(dbxRes => {
if (dbxRes.status ) {
this.toast.error('Upload unsuccessful. Please try again!');
} else {
if (!defaultConf.uploads) defaultConf.uploads = [];
let upload = {
title: uploadTitle,
url: dbxRes
};
defaultConf.uploads.push(upload);
this.adminService
.addConfUpload(defaultConf)
.then(res => {
this.toast.success('Upload Success!');
this.transitionService.setLoading(false);
})
.catch(err => {
this.toast.error(err.message);
});
}
});
});
}
deleteUpload(upload: {title: string; url: string;}) {
this.adminService
.deleteUpload(upload)
.then(res => {
this.toast.success('Removed upload. You still need to delete it from dropbox.')
});
}
} | the_stack |
require('./data-table.css');
import { Ajax } from '../../../utils/ajax/ajax';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { AttributeInfo, Attributes, findByName, Dataset } from 'plywood';
import { titleCase } from '../../../../common/utils/string/string';
import { pluralIfNeeded } from "../../../../common/utils/general/general";
import { generateUniqueName } from '../../../../common/utils/string/string';
import { STRINGS } from "../../../config/constants";
import { DataCube } from '../../../../common/models/index';
import { classNames } from '../../../utils/dom/dom';
import { SvgIcon, SimpleTable, SimpleTableColumn, Notifier, Loader } from '../../../components/index';
import { AttributeModal, SuggestionModal, DataCubeFilterModal } from '../../../modals/index';
import { LoadingMessageDelegate, LoadingMessageState } from '../../../delegates/index';
const LOADING = {
suggestions: 'Loading suggestions…',
data: 'Loading data…'
};
export interface DataTableProps extends React.Props<any> {
dataCube?: DataCube;
onChange?: (newDataCube: DataCube) => void;
}
export interface DataTableState extends LoadingMessageState {
editedAttribute?: AttributeInfo;
showSuggestionsModal?: boolean;
attributeSuggestions?: Attributes;
showAddAttributeModal?: boolean;
showSubsetFilterModal?: boolean;
dataset?: Dataset;
}
export class DataTable extends React.Component<DataTableProps, DataTableState> {
private mounted: boolean;
private loadingDelegate: LoadingMessageDelegate;
constructor() {
super();
this.state = {
dataset: null
};
this.loadingDelegate = new LoadingMessageDelegate(this);
}
componentDidMount() {
this.mounted = true;
this.fetchData(this.props.dataCube);
}
componentWillReceiveProps(nextProps: DataTableProps) {
const { dataCube } = this.props;
if (!dataCube.equals(nextProps.dataCube)) {
this.fetchData(nextProps.dataCube);
}
}
componentWillUnmount() {
this.mounted = false;
this.loadingDelegate.unmount();
}
fetchData(dataCube: DataCube): void {
this.loadingDelegate.startNow(LOADING.data);
Ajax.query({
method: "POST",
url: 'settings/preview',
data: {
dataCube
}
})
.then(
(resp: any) => {
if (!this.mounted) return;
this.loadingDelegate.stop();
this.setState({
dataset: Dataset.fromJS(resp.dataset)
});
},
(error: Error) => {
if (!this.mounted) return;
this.loadingDelegate.stop();
}
);
}
renderHeader(attribute: AttributeInfo, isPrimary: boolean, column: SimpleTableColumn, hovered: boolean): JSX.Element {
const iconPath = `dim-${attribute.type.toLowerCase().replace('/', '-')}`;
return <div
className={classNames('header', {hover: hovered})}
style={{width: column.width}}
key={attribute.name}
>
<div className="cell name">
<div className="label">{attribute.name}</div>
<SvgIcon svg={require('../../../icons/full-edit.svg')}/>
</div>
<div className="cell type">
<SvgIcon svg={require(`../../../icons/${iconPath}.svg`)}/>
<div className="label">{titleCase(attribute.type) + (isPrimary ? ' (primary)' : '')}</div>
</div>
</div>;
}
onHeaderClick(column: SimpleTableColumn) {
this.loadingDelegate.stop();
this.setState({
editedAttribute: column.data
});
// Don't sort
return false;
}
renderEditModal() {
const { dataCube, onChange } = this.props;
const { editedAttribute } = this.state;
if (!editedAttribute) return null;
const onClose = () => {
this.setState({
editedAttribute: null
});
};
const onSave = (newAttribute: AttributeInfo) => {
onChange(dataCube.updateAttribute(newAttribute));
onClose();
};
const onRemove = () => {
onClose();
this.askToRemoveAttribute(editedAttribute);
};
return <AttributeModal
attributeInfo={editedAttribute}
onClose={onClose}
onSave={onSave}
onRemove={onRemove}
/>;
}
askToRemoveAttribute(attribute: AttributeInfo) {
var { dataCube, onChange } = this.props;
const dependantDimensions = dataCube.getDimensionsForAttribute(attribute.name);
const dependantMeasures = dataCube.getMeasuresForAttribute(attribute.name);
const dependants = dependantDimensions.length + dependantMeasures.length;
const remove = () => {
onChange(dataCube.removeAttribute(attribute.name));
Notifier.removeQuestion();
};
var message: string | JSX.Element;
if (dependants > 0) {
message = <div className="message">
<p>This attribute has {pluralIfNeeded(dependantDimensions.length, 'dimension')}
and {pluralIfNeeded(dependantMeasures.length, 'measure')} relying on it.</p>
<p>Removing it will remove them as well.</p>
<div className="dependency-list">
{dependantDimensions.map(d => <p key={d.name}>{d.title}</p>)}
{dependantMeasures.map(m => <p key={m.name}>{m.title}</p>)}
</div>
</div>;
} else {
message = 'This cannot be undone.';
}
Notifier.ask({
title: `Remove the attribute "${attribute.name}"?`,
message,
choices: [
{label: 'Remove', callback: remove, type: 'warn'},
{label: 'Cancel', callback: Notifier.removeQuestion, type: 'secondary'}
],
onClose: Notifier.removeQuestion
});
}
getColumns(): SimpleTableColumn[] {
const dataCube = this.props.dataCube as DataCube;
const primaryTimeAttribute = dataCube.getPrimaryTimeAttribute();
return dataCube.attributes.map(a => {
let isPrimary = a.name === primaryTimeAttribute;
return {
label: a.name,
data: a,
field: a.name,
width: 170,
render: this.renderHeader.bind(this, a, isPrimary)
};
});
}
renderFiltersModal() {
const { dataCube, onChange } = this.props;
const { showSubsetFilterModal } = this.state;
if (!showSubsetFilterModal) return null;
const onClose = () => {
this.setState({
showSubsetFilterModal: false
});
};
const onSave = (dataCube: DataCube) => {
onChange(dataCube);
onClose();
};
return <DataCubeFilterModal
onSave={onSave}
onClose={onClose}
dataCube={dataCube}
/>;
}
onFiltersClick() {
this.setState({
showSubsetFilterModal: true
});
}
fetchSuggestions() {
const { dataCube } = this.props;
this.loadingDelegate.startNow(LOADING.suggestions);
Ajax.query({
method: "POST",
url: 'settings/attributes',
data: {
clusterName: dataCube.clusterName,
source: dataCube.source
}
})
.then(
(resp) => {
if (!this.mounted) return;
this.loadingDelegate.stop();
this.setState({
attributeSuggestions: dataCube.filterAttributes(AttributeInfo.fromJSs(resp.attributes))
});
},
(xhr: XMLHttpRequest) => {
if (!this.mounted) return;
this.loadingDelegate.stop();
Notifier.failure('Woops', 'Something bad happened');
}
)
.done();
}
openSuggestionsModal() {
this.loadingDelegate.stop();
this.setState({
showSuggestionsModal: true
});
this.fetchSuggestions();
}
closeAttributeSuggestions() {
this.setState({
attributeSuggestions: null,
showSuggestionsModal: false,
showAddAttributeModal: false
});
}
renderAttributeSuggestions() {
const { onChange, dataCube } = this.props;
const { attributeSuggestions, showSuggestionsModal, isLoading, loadingMessage } = this.state;
if (!showSuggestionsModal) return null;
const getAttributeLabel = (a: AttributeInfo) => {
var special = a.special ? ` [${a.special}]` : '';
return `${a.name} as ${a.type}${special}`;
};
const suggestions = (attributeSuggestions || []).map(a => {
return {label: getAttributeLabel(a), value: a};
});
const onOk = {
label: (n: number) => `${STRINGS.add} ${pluralIfNeeded(n, 'attribute')}`,
callback: (extraAttributes: Attributes) => {
onChange(dataCube.changeAttributes(dataCube.attributes.concat(extraAttributes).sort()));
this.closeAttributeSuggestions();
}
};
const onDoNothing = {
label: () => STRINGS.cancel,
callback: this.closeAttributeSuggestions.bind(this)
};
const onAlternateView = {
label: () => STRINGS.orAddASpecificAttribute,
callback: () => {
this.setState({
showSuggestionsModal: false,
showAddAttributeModal: true
});
}
};
const AttributeSuggestionModal = SuggestionModal.specialize<AttributeInfo>();
return <AttributeSuggestionModal
onOk={onOk}
onDoNothing={onDoNothing}
onAlternateView={onAlternateView}
suggestions={suggestions}
loadingState={{isLoading, loadingMessage}}
onClose={this.closeAttributeSuggestions.bind(this)}
title={`${STRINGS.attribute} ${STRINGS.suggestions}`}
/>;
}
renderAttributeAdd() {
const { onChange, dataCube } = this.props;
const { showAddAttributeModal } = this.state;
if (!showAddAttributeModal) return null;
const attributes = dataCube.attributes;
const attribute = new AttributeInfo({
name: generateUniqueName('a', (name) => attributes.filter(a => a.name === name).length === 0 ),
type: 'STRING'
});
const onSave = (attribute: AttributeInfo) => {
onChange(dataCube.changeAttributes(dataCube.attributes.concat([attribute]).sort()));
this.closeAttributeSuggestions();
};
const onAlternateClick = () => {
this.setState({
showSuggestionsModal: true,
showAddAttributeModal: false
});
};
return <AttributeModal
attributeInfo={attribute}
onClose={this.closeAttributeSuggestions.bind(this)}
onSave={onSave}
onAlternateClick={onAlternateClick}
mode="create"
/>;
}
render() {
const { dataset, isLoading, loadingMessage } = this.state;
return <div className="data-table">
<div className="header">
<div className="title">{STRINGS.attributes}</div>
<div className="actions">
<button onClick={this.onFiltersClick.bind(this)}>{STRINGS.filters}</button>
<button onClick={this.openSuggestionsModal.bind(this)}>{STRINGS.addAttributes}</button>
</div>
</div>
<SimpleTable
columns={this.getColumns()}
rows={dataset ? dataset.data : []}
headerHeight={83}
onHeaderClick={this.onHeaderClick.bind(this)}
/>
{ this.renderEditModal() }
{ this.renderAttributeSuggestions() }
{ this.renderAttributeAdd() }
{ this.renderFiltersModal() }
{ isLoading && loadingMessage !== LOADING.suggestions ? <Loader/> : null }
</div>;
}
} | the_stack |
namespace DotVVM.Samples.Common.Api.Owin {
class ClientBase {
public transformOptions(options: RequestInit) {
options.credentials = "same-origin";
return Promise.resolve(options);
}
}
/* tslint:disable */
/* eslint-disable */
//----------------------
// <auto-generated>
// Generated using the NSwag toolchain v13.13.2.0 (NJsonSchema v10.5.2.0 (Newtonsoft.Json v10.0.0.0)) (http://NSwag.org)
// </auto-generated>
//----------------------
// ReSharper disable InconsistentNaming
export class CompaniesClient extends ClientBase {
private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
private baseUrl: string;
protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;
constructor(baseUrl?: string, http?: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> }) {
super();
this.http = http ? http : <any>window;
this.baseUrl = baseUrl !== undefined && baseUrl !== null ? baseUrl : "http://localhost:61453";
}
/**
* @return OK
*/
get(): Promise<CompanyOfString[]> {
let url_ = this.baseUrl + "/api/companies";
url_ = url_.replace(/[?&]$/, "");
let options_ = <RequestInit>{
method: "GET",
headers: {
"Accept": "application/json"
}
};
return this.transformOptions(options_).then(transformedOptions_ => {
return this.http.fetch(url_, transformedOptions_);
}).then((_response: Response) => {
return this.processGet(_response);
});
}
protected processGet(response: Response): Promise<CompanyOfString[]> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 200) {
return response.text().then((_responseText) => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
if (Array.isArray(resultData200)) {
result200 = [] as any;
for (let item of resultData200)
result200!.push(CompanyOfString.fromJS(item));
}
else {
result200 = <any>null;
}
return result200;
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<CompanyOfString[]>(<any>null);
}
/**
* @param sortingOptions (optional)
* @param sortingOptions_SortDescending (optional)
* @param sortingOptions_SortExpression (optional)
* @return OK
*/
getWithSorting(sortingOptions?: any | null | undefined, sortingOptions_SortDescending?: boolean | null | undefined, sortingOptions_SortExpression?: string | null | undefined): Promise<GridViewDataSetOfCompanyOfBoolean> {
let url_ = this.baseUrl + "/api/companies/sorted?";
if (sortingOptions !== undefined && sortingOptions !== null)
url_ += "sortingOptions=" + encodeURIComponent("" + sortingOptions) + "&";
if (sortingOptions_SortDescending !== undefined && sortingOptions_SortDescending !== null)
url_ += "sortingOptions.SortDescending=" + encodeURIComponent("" + sortingOptions_SortDescending) + "&";
if (sortingOptions_SortExpression !== undefined && sortingOptions_SortExpression !== null)
url_ += "sortingOptions.SortExpression=" + encodeURIComponent("" + sortingOptions_SortExpression) + "&";
url_ = url_.replace(/[?&]$/, "");
let options_ = <RequestInit>{
method: "GET",
headers: {
"Accept": "application/json"
}
};
return this.transformOptions(options_).then(transformedOptions_ => {
return this.http.fetch(url_, transformedOptions_);
}).then((_response: Response) => {
return this.processGetWithSorting(_response);
});
}
protected processGetWithSorting(response: Response): Promise<GridViewDataSetOfCompanyOfBoolean> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 200) {
return response.text().then((_responseText) => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result200 = GridViewDataSetOfCompanyOfBoolean.fromJS(resultData200);
return result200;
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<GridViewDataSetOfCompanyOfBoolean>(<any>null);
}
/**
* @param pagingOptions (optional)
* @param pagingOptions_PageIndex (optional)
* @param pagingOptions_PageSize (optional)
* @param pagingOptions_TotalItemsCount (optional)
* @return OK
*/
getWithPaging(pagingOptions?: any | null | undefined, pagingOptions_PageIndex?: number | null | undefined, pagingOptions_PageSize?: number | null | undefined, pagingOptions_TotalItemsCount?: number | null | undefined): Promise<GridViewDataSetOfCompanyOfString> {
let url_ = this.baseUrl + "/api/companies/paged?";
if (pagingOptions !== undefined && pagingOptions !== null)
url_ += "pagingOptions=" + encodeURIComponent("" + pagingOptions) + "&";
if (pagingOptions_PageIndex !== undefined && pagingOptions_PageIndex !== null)
url_ += "pagingOptions.PageIndex=" + encodeURIComponent("" + pagingOptions_PageIndex) + "&";
if (pagingOptions_PageSize !== undefined && pagingOptions_PageSize !== null)
url_ += "pagingOptions.PageSize=" + encodeURIComponent("" + pagingOptions_PageSize) + "&";
if (pagingOptions_TotalItemsCount !== undefined && pagingOptions_TotalItemsCount !== null)
url_ += "pagingOptions.TotalItemsCount=" + encodeURIComponent("" + pagingOptions_TotalItemsCount) + "&";
url_ = url_.replace(/[?&]$/, "");
let options_ = <RequestInit>{
method: "GET",
headers: {
"Accept": "application/json"
}
};
return this.transformOptions(options_).then(transformedOptions_ => {
return this.http.fetch(url_, transformedOptions_);
}).then((_response: Response) => {
return this.processGetWithPaging(_response);
});
}
protected processGetWithPaging(response: Response): Promise<GridViewDataSetOfCompanyOfString> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 200) {
return response.text().then((_responseText) => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result200 = GridViewDataSetOfCompanyOfString.fromJS(resultData200);
return result200;
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<GridViewDataSetOfCompanyOfString>(<any>null);
}
/**
* @param sortingOptions (optional)
* @param sortingOptions_SortDescending (optional)
* @param sortingOptions_SortExpression (optional)
* @param pagingOptions (optional)
* @param pagingOptions_PageIndex (optional)
* @param pagingOptions_PageSize (optional)
* @param pagingOptions_TotalItemsCount (optional)
* @return OK
*/
getWithSortingAndPaging(sortingOptions?: any | null | undefined, sortingOptions_SortDescending?: boolean | null | undefined, sortingOptions_SortExpression?: string | null | undefined, pagingOptions?: any | null | undefined, pagingOptions_PageIndex?: number | null | undefined, pagingOptions_PageSize?: number | null | undefined, pagingOptions_TotalItemsCount?: number | null | undefined): Promise<GridViewDataSetOfCompanyOfString> {
let url_ = this.baseUrl + "/api/companies/sortedandpaged?";
if (sortingOptions !== undefined && sortingOptions !== null)
url_ += "sortingOptions=" + encodeURIComponent("" + sortingOptions) + "&";
if (sortingOptions_SortDescending !== undefined && sortingOptions_SortDescending !== null)
url_ += "sortingOptions.SortDescending=" + encodeURIComponent("" + sortingOptions_SortDescending) + "&";
if (sortingOptions_SortExpression !== undefined && sortingOptions_SortExpression !== null)
url_ += "sortingOptions.SortExpression=" + encodeURIComponent("" + sortingOptions_SortExpression) + "&";
if (pagingOptions !== undefined && pagingOptions !== null)
url_ += "pagingOptions=" + encodeURIComponent("" + pagingOptions) + "&";
if (pagingOptions_PageIndex !== undefined && pagingOptions_PageIndex !== null)
url_ += "pagingOptions.PageIndex=" + encodeURIComponent("" + pagingOptions_PageIndex) + "&";
if (pagingOptions_PageSize !== undefined && pagingOptions_PageSize !== null)
url_ += "pagingOptions.PageSize=" + encodeURIComponent("" + pagingOptions_PageSize) + "&";
if (pagingOptions_TotalItemsCount !== undefined && pagingOptions_TotalItemsCount !== null)
url_ += "pagingOptions.TotalItemsCount=" + encodeURIComponent("" + pagingOptions_TotalItemsCount) + "&";
url_ = url_.replace(/[?&]$/, "");
let options_ = <RequestInit>{
method: "GET",
headers: {
"Accept": "application/json"
}
};
return this.transformOptions(options_).then(transformedOptions_ => {
return this.http.fetch(url_, transformedOptions_);
}).then((_response: Response) => {
return this.processGetWithSortingAndPaging(_response);
});
}
protected processGetWithSortingAndPaging(response: Response): Promise<GridViewDataSetOfCompanyOfString> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 200) {
return response.text().then((_responseText) => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result200 = GridViewDataSetOfCompanyOfString.fromJS(resultData200);
return result200;
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<GridViewDataSetOfCompanyOfString>(<any>null);
}
}
export class OrdersClient extends ClientBase {
private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
private baseUrl: string;
protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;
constructor(baseUrl?: string, http?: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> }) {
super();
this.http = http ? http : <any>window;
this.baseUrl = baseUrl !== undefined && baseUrl !== null ? baseUrl : "http://localhost:61453";
}
/**
* @param pageIndex (optional)
* @param pageSize (optional)
* @return OK
*/
get(companyId: number, pageIndex?: number | null | undefined, pageSize?: number | null | undefined): Promise<Order[]> {
let url_ = this.baseUrl + "/api/orders?";
if (companyId === undefined || companyId === null)
throw new Error("The parameter 'companyId' must be defined and cannot be null.");
else
url_ += "companyId=" + encodeURIComponent("" + companyId) + "&";
if (pageIndex !== undefined && pageIndex !== null)
url_ += "pageIndex=" + encodeURIComponent("" + pageIndex) + "&";
if (pageSize !== undefined && pageSize !== null)
url_ += "pageSize=" + encodeURIComponent("" + pageSize) + "&";
url_ = url_.replace(/[?&]$/, "");
let options_ = <RequestInit>{
method: "GET",
headers: {
"Accept": "application/json"
}
};
return this.transformOptions(options_).then(transformedOptions_ => {
return this.http.fetch(url_, transformedOptions_);
}).then((_response: Response) => {
return this.processGet(_response);
});
}
protected processGet(response: Response): Promise<Order[]> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 200) {
return response.text().then((_responseText) => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
if (Array.isArray(resultData200)) {
result200 = [] as any;
for (let item of resultData200)
result200!.push(Order.fromJS(item));
}
else {
result200 = <any>null;
}
return result200;
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<Order[]>(<any>null);
}
/**
* @return OK
*/
post(order: Order): Promise<any> {
let url_ = this.baseUrl + "/api/orders";
url_ = url_.replace(/[?&]$/, "");
const content_ = JSON.stringify(order);
let options_ = <RequestInit>{
body: content_,
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
};
return this.transformOptions(options_).then(transformedOptions_ => {
return this.http.fetch(url_, transformedOptions_);
}).then((_response: Response) => {
return this.processPost(_response);
});
}
protected processPost(response: Response): Promise<any> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 200) {
return response.text().then((_responseText) => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result200 = resultData200 !== undefined ? resultData200 : <any>null;
return result200;
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<any>(<any>null);
}
/**
* @return OK
*/
getItem(orderId: number): Promise<Order> {
let url_ = this.baseUrl + "/api/orders/{orderId}";
if (orderId === undefined || orderId === null)
throw new Error("The parameter 'orderId' must be defined.");
url_ = url_.replace("{orderId}", encodeURIComponent("" + orderId));
url_ = url_.replace(/[?&]$/, "");
let options_ = <RequestInit>{
method: "GET",
headers: {
"Accept": "application/json"
}
};
return this.transformOptions(options_).then(transformedOptions_ => {
return this.http.fetch(url_, transformedOptions_);
}).then((_response: Response) => {
return this.processGetItem(_response);
});
}
protected processGetItem(response: Response): Promise<Order> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 200) {
return response.text().then((_responseText) => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result200 = Order.fromJS(resultData200);
return result200;
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<Order>(<any>null);
}
/**
* @return OK
*/
put(orderId: number, order: Order): Promise<any> {
let url_ = this.baseUrl + "/api/orders/{orderId}";
if (orderId === undefined || orderId === null)
throw new Error("The parameter 'orderId' must be defined.");
url_ = url_.replace("{orderId}", encodeURIComponent("" + orderId));
url_ = url_.replace(/[?&]$/, "");
const content_ = JSON.stringify(order);
let options_ = <RequestInit>{
body: content_,
method: "PUT",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
};
return this.transformOptions(options_).then(transformedOptions_ => {
return this.http.fetch(url_, transformedOptions_);
}).then((_response: Response) => {
return this.processPut(_response);
});
}
protected processPut(response: Response): Promise<any> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 200) {
return response.text().then((_responseText) => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result200 = resultData200 !== undefined ? resultData200 : <any>null;
return result200;
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<any>(<any>null);
}
/**
* @return No Content
*/
delete(orderId: number): Promise<void> {
let url_ = this.baseUrl + "/api/orders/delete/{orderId}";
if (orderId === undefined || orderId === null)
throw new Error("The parameter 'orderId' must be defined.");
url_ = url_.replace("{orderId}", encodeURIComponent("" + orderId));
url_ = url_.replace(/[?&]$/, "");
let options_ = <RequestInit>{
method: "DELETE",
headers: {
}
};
return this.transformOptions(options_).then(transformedOptions_ => {
return this.http.fetch(url_, transformedOptions_);
}).then((_response: Response) => {
return this.processDelete(_response);
});
}
protected processDelete(response: Response): Promise<void> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 204) {
return response.text().then((_responseText) => {
return;
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<void>(<any>null);
}
}
export class ResetClient extends ClientBase {
private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
private baseUrl: string;
protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;
constructor(baseUrl?: string, http?: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> }) {
super();
this.http = http ? http : <any>window;
this.baseUrl = baseUrl !== undefined && baseUrl !== null ? baseUrl : "http://localhost:61453";
}
/**
* @return No Content
*/
resetData(): Promise<void> {
let url_ = this.baseUrl + "/api/reset/reset";
url_ = url_.replace(/[?&]$/, "");
let options_ = <RequestInit>{
method: "POST",
headers: {
}
};
return this.transformOptions(options_).then(transformedOptions_ => {
return this.http.fetch(url_, transformedOptions_);
}).then((_response: Response) => {
return this.processResetData(_response);
});
}
protected processResetData(response: Response): Promise<void> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 204) {
return response.text().then((_responseText) => {
return;
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<void>(<any>null);
}
}
export class CompanyOfString implements ICompanyOfString {
Id?: number | null;
Name?: string | null;
Owner?: string | null;
Department?: string | null;
constructor(data?: ICompanyOfString) {
if (data) {
for (var property in data) {
if (data.hasOwnProperty(property))
(<any>this)[property] = (<any>data)[property];
}
}
}
init(_data?: any) {
if (_data) {
this.Id = _data["Id"] !== undefined ? _data["Id"] : <any>null;
this.Name = _data["Name"] !== undefined ? _data["Name"] : <any>null;
this.Owner = _data["Owner"] !== undefined ? _data["Owner"] : <any>null;
this.Department = _data["Department"] !== undefined ? _data["Department"] : <any>null;
}
}
static fromJS(data: any): CompanyOfString {
data = typeof data === 'object' ? data : {};
let result = new CompanyOfString();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
data["Id"] = this.Id !== undefined ? this.Id : <any>null;
data["Name"] = this.Name !== undefined ? this.Name : <any>null;
data["Owner"] = this.Owner !== undefined ? this.Owner : <any>null;
data["Department"] = this.Department !== undefined ? this.Department : <any>null;
return data;
}
}
export interface ICompanyOfString {
Id?: number | null;
Name?: string | null;
Owner?: string | null;
Department?: string | null;
}
export class SortingOptions implements ISortingOptions {
SortDescending?: boolean | null;
SortExpression?: string | null;
constructor(data?: ISortingOptions) {
if (data) {
for (var property in data) {
if (data.hasOwnProperty(property))
(<any>this)[property] = (<any>data)[property];
}
}
}
init(_data?: any) {
if (_data) {
this.SortDescending = _data["SortDescending"] !== undefined ? _data["SortDescending"] : <any>null;
this.SortExpression = _data["SortExpression"] !== undefined ? _data["SortExpression"] : <any>null;
}
}
static fromJS(data: any): SortingOptions {
data = typeof data === 'object' ? data : {};
let result = new SortingOptions();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
data["SortDescending"] = this.SortDescending !== undefined ? this.SortDescending : <any>null;
data["SortExpression"] = this.SortExpression !== undefined ? this.SortExpression : <any>null;
return data;
}
}
export interface ISortingOptions {
SortDescending?: boolean | null;
SortExpression?: string | null;
}
export class GridViewDataSetOfCompanyOfBoolean implements IGridViewDataSetOfCompanyOfBoolean {
IsRefreshRequired?: boolean | null;
Items?: CompanyOfBoolean[] | null;
PagingOptions?: IPagingOptions | null;
RowEditOptions?: IRowEditOptions | null;
SortingOptions?: ISortingOptions | null;
constructor(data?: IGridViewDataSetOfCompanyOfBoolean) {
if (data) {
for (var property in data) {
if (data.hasOwnProperty(property))
(<any>this)[property] = (<any>data)[property];
}
}
}
init(_data?: any) {
if (_data) {
this.IsRefreshRequired = _data["IsRefreshRequired"] !== undefined ? _data["IsRefreshRequired"] : <any>null;
if (Array.isArray(_data["Items"])) {
this.Items = [] as any;
for (let item of _data["Items"])
this.Items!.push(CompanyOfBoolean.fromJS(item));
}
else {
this.Items = <any>null;
}
this.PagingOptions = _data["PagingOptions"] ? IPagingOptions.fromJS(_data["PagingOptions"]) : <any>null;
this.RowEditOptions = _data["RowEditOptions"] ? IRowEditOptions.fromJS(_data["RowEditOptions"]) : <any>null;
this.SortingOptions = _data["SortingOptions"] ? ISortingOptions.fromJS(_data["SortingOptions"]) : <any>null;
}
}
static fromJS(data: any): GridViewDataSetOfCompanyOfBoolean {
data = typeof data === 'object' ? data : {};
let result = new GridViewDataSetOfCompanyOfBoolean();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
data["IsRefreshRequired"] = this.IsRefreshRequired !== undefined ? this.IsRefreshRequired : <any>null;
if (Array.isArray(this.Items)) {
data["Items"] = [];
for (let item of this.Items)
data["Items"].push(item.toJSON());
}
data["PagingOptions"] = this.PagingOptions ? this.PagingOptions.toJSON() : <any>null;
data["RowEditOptions"] = this.RowEditOptions ? this.RowEditOptions.toJSON() : <any>null;
data["SortingOptions"] = this.SortingOptions ? this.SortingOptions.toJSON() : <any>null;
return data;
}
}
export interface IGridViewDataSetOfCompanyOfBoolean {
IsRefreshRequired?: boolean | null;
Items?: CompanyOfBoolean[] | null;
PagingOptions?: IPagingOptions | null;
RowEditOptions?: IRowEditOptions | null;
SortingOptions?: ISortingOptions | null;
}
export class CompanyOfBoolean implements ICompanyOfBoolean {
Id?: number | null;
Name?: string | null;
Owner?: string | null;
Department?: boolean | null;
constructor(data?: ICompanyOfBoolean) {
if (data) {
for (var property in data) {
if (data.hasOwnProperty(property))
(<any>this)[property] = (<any>data)[property];
}
}
}
init(_data?: any) {
if (_data) {
this.Id = _data["Id"] !== undefined ? _data["Id"] : <any>null;
this.Name = _data["Name"] !== undefined ? _data["Name"] : <any>null;
this.Owner = _data["Owner"] !== undefined ? _data["Owner"] : <any>null;
this.Department = _data["Department"] !== undefined ? _data["Department"] : <any>null;
}
}
static fromJS(data: any): CompanyOfBoolean {
data = typeof data === 'object' ? data : {};
let result = new CompanyOfBoolean();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
data["Id"] = this.Id !== undefined ? this.Id : <any>null;
data["Name"] = this.Name !== undefined ? this.Name : <any>null;
data["Owner"] = this.Owner !== undefined ? this.Owner : <any>null;
data["Department"] = this.Department !== undefined ? this.Department : <any>null;
return data;
}
}
export interface ICompanyOfBoolean {
Id?: number | null;
Name?: string | null;
Owner?: string | null;
Department?: boolean | null;
}
export class IPagingOptions implements IIPagingOptions {
PageIndex?: number | null;
PageSize?: number | null;
TotalItemsCount?: number | null;
readonly IsFirstPage?: boolean | null;
readonly IsLastPage?: boolean | null;
readonly PagesCount?: number | null;
readonly NearPageIndexes?: number[] | null;
constructor(data?: IIPagingOptions) {
if (data) {
for (var property in data) {
if (data.hasOwnProperty(property))
(<any>this)[property] = (<any>data)[property];
}
}
}
init(_data?: any) {
if (_data) {
this.PageIndex = _data["PageIndex"] !== undefined ? _data["PageIndex"] : <any>null;
this.PageSize = _data["PageSize"] !== undefined ? _data["PageSize"] : <any>null;
this.TotalItemsCount = _data["TotalItemsCount"] !== undefined ? _data["TotalItemsCount"] : <any>null;
(<any>this).IsFirstPage = _data["IsFirstPage"] !== undefined ? _data["IsFirstPage"] : <any>null;
(<any>this).IsLastPage = _data["IsLastPage"] !== undefined ? _data["IsLastPage"] : <any>null;
(<any>this).PagesCount = _data["PagesCount"] !== undefined ? _data["PagesCount"] : <any>null;
if (Array.isArray(_data["NearPageIndexes"])) {
(<any>this).NearPageIndexes = [] as any;
for (let item of _data["NearPageIndexes"])
(<any>this).NearPageIndexes!.push(item);
}
else {
(<any>this).NearPageIndexes = <any>null;
}
}
}
static fromJS(data: any): IPagingOptions {
data = typeof data === 'object' ? data : {};
let result = new IPagingOptions();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
data["PageIndex"] = this.PageIndex !== undefined ? this.PageIndex : <any>null;
data["PageSize"] = this.PageSize !== undefined ? this.PageSize : <any>null;
data["TotalItemsCount"] = this.TotalItemsCount !== undefined ? this.TotalItemsCount : <any>null;
data["IsFirstPage"] = this.IsFirstPage !== undefined ? this.IsFirstPage : <any>null;
data["IsLastPage"] = this.IsLastPage !== undefined ? this.IsLastPage : <any>null;
data["PagesCount"] = this.PagesCount !== undefined ? this.PagesCount : <any>null;
if (Array.isArray(this.NearPageIndexes)) {
data["NearPageIndexes"] = [];
for (let item of this.NearPageIndexes)
data["NearPageIndexes"].push(item);
}
return data;
}
}
export interface IIPagingOptions {
PageIndex?: number | null;
PageSize?: number | null;
TotalItemsCount?: number | null;
IsFirstPage?: boolean | null;
IsLastPage?: boolean | null;
PagesCount?: number | null;
NearPageIndexes?: number[] | null;
}
export class IRowEditOptions implements IIRowEditOptions {
PrimaryKeyPropertyName?: string | null;
EditRowId?: any | null;
constructor(data?: IIRowEditOptions) {
if (data) {
for (var property in data) {
if (data.hasOwnProperty(property))
(<any>this)[property] = (<any>data)[property];
}
}
}
init(_data?: any) {
if (_data) {
this.PrimaryKeyPropertyName = _data["PrimaryKeyPropertyName"] !== undefined ? _data["PrimaryKeyPropertyName"] : <any>null;
this.EditRowId = _data["EditRowId"] !== undefined ? _data["EditRowId"] : <any>null;
}
}
static fromJS(data: any): IRowEditOptions {
data = typeof data === 'object' ? data : {};
let result = new IRowEditOptions();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
data["PrimaryKeyPropertyName"] = this.PrimaryKeyPropertyName !== undefined ? this.PrimaryKeyPropertyName : <any>null;
data["EditRowId"] = this.EditRowId !== undefined ? this.EditRowId : <any>null;
return data;
}
}
export interface IIRowEditOptions {
PrimaryKeyPropertyName?: string | null;
EditRowId?: any | null;
}
export class ISortingOptions implements IISortingOptions {
SortDescending?: boolean | null;
SortExpression?: string | null;
constructor(data?: IISortingOptions) {
if (data) {
for (var property in data) {
if (data.hasOwnProperty(property))
(<any>this)[property] = (<any>data)[property];
}
}
}
init(_data?: any) {
if (_data) {
this.SortDescending = _data["SortDescending"] !== undefined ? _data["SortDescending"] : <any>null;
this.SortExpression = _data["SortExpression"] !== undefined ? _data["SortExpression"] : <any>null;
}
}
static fromJS(data: any): ISortingOptions {
data = typeof data === 'object' ? data : {};
let result = new ISortingOptions();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
data["SortDescending"] = this.SortDescending !== undefined ? this.SortDescending : <any>null;
data["SortExpression"] = this.SortExpression !== undefined ? this.SortExpression : <any>null;
return data;
}
}
export interface IISortingOptions {
SortDescending?: boolean | null;
SortExpression?: string | null;
}
export class PagingOptions implements IPagingOptions {
NearPageIndexesProvider?: INearPageIndexesProvider | null;
readonly IsFirstPage?: boolean | null;
readonly IsLastPage?: boolean | null;
readonly PagesCount?: number | null;
PageIndex?: number | null;
PageSize?: number | null;
TotalItemsCount?: number | null;
readonly NearPageIndexes?: number[] | null;
constructor(data?: IPagingOptions) {
if (data) {
for (var property in data) {
if (data.hasOwnProperty(property))
(<any>this)[property] = (<any>data)[property];
}
}
}
init(_data?: any) {
if (_data) {
this.NearPageIndexesProvider = _data["NearPageIndexesProvider"] ? INearPageIndexesProvider.fromJS(_data["NearPageIndexesProvider"]) : <any>null;
(<any>this).IsFirstPage = _data["IsFirstPage"] !== undefined ? _data["IsFirstPage"] : <any>null;
(<any>this).IsLastPage = _data["IsLastPage"] !== undefined ? _data["IsLastPage"] : <any>null;
(<any>this).PagesCount = _data["PagesCount"] !== undefined ? _data["PagesCount"] : <any>null;
this.PageIndex = _data["PageIndex"] !== undefined ? _data["PageIndex"] : <any>null;
this.PageSize = _data["PageSize"] !== undefined ? _data["PageSize"] : <any>null;
this.TotalItemsCount = _data["TotalItemsCount"] !== undefined ? _data["TotalItemsCount"] : <any>null;
if (Array.isArray(_data["NearPageIndexes"])) {
(<any>this).NearPageIndexes = [] as any;
for (let item of _data["NearPageIndexes"])
(<any>this).NearPageIndexes!.push(item);
}
else {
(<any>this).NearPageIndexes = <any>null;
}
}
}
static fromJS(data: any): PagingOptions {
data = typeof data === 'object' ? data : {};
let result = new PagingOptions();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
data["NearPageIndexesProvider"] = this.NearPageIndexesProvider ? this.NearPageIndexesProvider.toJSON() : <any>null;
data["IsFirstPage"] = this.IsFirstPage !== undefined ? this.IsFirstPage : <any>null;
data["IsLastPage"] = this.IsLastPage !== undefined ? this.IsLastPage : <any>null;
data["PagesCount"] = this.PagesCount !== undefined ? this.PagesCount : <any>null;
data["PageIndex"] = this.PageIndex !== undefined ? this.PageIndex : <any>null;
data["PageSize"] = this.PageSize !== undefined ? this.PageSize : <any>null;
data["TotalItemsCount"] = this.TotalItemsCount !== undefined ? this.TotalItemsCount : <any>null;
if (Array.isArray(this.NearPageIndexes)) {
data["NearPageIndexes"] = [];
for (let item of this.NearPageIndexes)
data["NearPageIndexes"].push(item);
}
return data;
}
}
export interface IPagingOptions {
NearPageIndexesProvider?: INearPageIndexesProvider | null;
IsFirstPage?: boolean | null;
IsLastPage?: boolean | null;
PagesCount?: number | null;
PageIndex?: number | null;
PageSize?: number | null;
TotalItemsCount?: number | null;
NearPageIndexes?: number[] | null;
}
export class INearPageIndexesProvider implements IINearPageIndexesProvider {
constructor(data?: IINearPageIndexesProvider) {
if (data) {
for (var property in data) {
if (data.hasOwnProperty(property))
(<any>this)[property] = (<any>data)[property];
}
}
}
init(_data?: any) {
}
static fromJS(data: any): INearPageIndexesProvider {
data = typeof data === 'object' ? data : {};
let result = new INearPageIndexesProvider();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
return data;
}
}
export interface IINearPageIndexesProvider {
}
export class GridViewDataSetOfCompanyOfString implements IGridViewDataSetOfCompanyOfString {
IsRefreshRequired?: boolean | null;
Items?: CompanyOfString[] | null;
PagingOptions?: IPagingOptions | null;
RowEditOptions?: IRowEditOptions | null;
SortingOptions?: ISortingOptions | null;
constructor(data?: IGridViewDataSetOfCompanyOfString) {
if (data) {
for (var property in data) {
if (data.hasOwnProperty(property))
(<any>this)[property] = (<any>data)[property];
}
}
}
init(_data?: any) {
if (_data) {
this.IsRefreshRequired = _data["IsRefreshRequired"] !== undefined ? _data["IsRefreshRequired"] : <any>null;
if (Array.isArray(_data["Items"])) {
this.Items = [] as any;
for (let item of _data["Items"])
this.Items!.push(CompanyOfString.fromJS(item));
}
else {
this.Items = <any>null;
}
this.PagingOptions = _data["PagingOptions"] ? IPagingOptions.fromJS(_data["PagingOptions"]) : <any>null;
this.RowEditOptions = _data["RowEditOptions"] ? IRowEditOptions.fromJS(_data["RowEditOptions"]) : <any>null;
this.SortingOptions = _data["SortingOptions"] ? ISortingOptions.fromJS(_data["SortingOptions"]) : <any>null;
}
}
static fromJS(data: any): GridViewDataSetOfCompanyOfString {
data = typeof data === 'object' ? data : {};
let result = new GridViewDataSetOfCompanyOfString();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
data["IsRefreshRequired"] = this.IsRefreshRequired !== undefined ? this.IsRefreshRequired : <any>null;
if (Array.isArray(this.Items)) {
data["Items"] = [];
for (let item of this.Items)
data["Items"].push(item.toJSON());
}
data["PagingOptions"] = this.PagingOptions ? this.PagingOptions.toJSON() : <any>null;
data["RowEditOptions"] = this.RowEditOptions ? this.RowEditOptions.toJSON() : <any>null;
data["SortingOptions"] = this.SortingOptions ? this.SortingOptions.toJSON() : <any>null;
return data;
}
}
export interface IGridViewDataSetOfCompanyOfString {
IsRefreshRequired?: boolean | null;
Items?: CompanyOfString[] | null;
PagingOptions?: IPagingOptions | null;
RowEditOptions?: IRowEditOptions | null;
SortingOptions?: ISortingOptions | null;
}
export class Order implements IOrder {
Id?: number | null;
Number?: string | null;
Date?: Date | null;
companyId?: number | null;
OrderItems?: OrderItem[] | null;
constructor(data?: IOrder) {
if (data) {
for (var property in data) {
if (data.hasOwnProperty(property))
(<any>this)[property] = (<any>data)[property];
}
}
}
init(_data?: any) {
if (_data) {
this.Id = _data["Id"] !== undefined ? _data["Id"] : <any>null;
this.Number = _data["Number"] !== undefined ? _data["Number"] : <any>null;
this.Date = _data["Date"] ? new Date(_data["Date"].toString()) : <any>null;
this.companyId = _data["companyId"] !== undefined ? _data["companyId"] : <any>null;
if (Array.isArray(_data["OrderItems"])) {
this.OrderItems = [] as any;
for (let item of _data["OrderItems"])
this.OrderItems!.push(OrderItem.fromJS(item));
}
else {
this.OrderItems = <any>null;
}
}
}
static fromJS(data: any): Order {
data = typeof data === 'object' ? data : {};
let result = new Order();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
data["Id"] = this.Id !== undefined ? this.Id : <any>null;
data["Number"] = this.Number !== undefined ? this.Number : <any>null;
data["Date"] = this.Date ? this.Date.toISOString() : <any>null;
data["companyId"] = this.companyId !== undefined ? this.companyId : <any>null;
if (Array.isArray(this.OrderItems)) {
data["OrderItems"] = [];
for (let item of this.OrderItems)
data["OrderItems"].push(item.toJSON());
}
return data;
}
}
export interface IOrder {
Id?: number | null;
Number?: string | null;
Date?: Date | null;
companyId?: number | null;
OrderItems?: OrderItem[] | null;
}
export class OrderItem implements IOrderItem {
Id?: number | null;
Text?: string | null;
Amount?: number | null;
Discount?: number | null;
IsOnStock?: boolean | null;
constructor(data?: IOrderItem) {
if (data) {
for (var property in data) {
if (data.hasOwnProperty(property))
(<any>this)[property] = (<any>data)[property];
}
}
}
init(_data?: any) {
if (_data) {
this.Id = _data["Id"] !== undefined ? _data["Id"] : <any>null;
this.Text = _data["Text"] !== undefined ? _data["Text"] : <any>null;
this.Amount = _data["Amount"] !== undefined ? _data["Amount"] : <any>null;
this.Discount = _data["Discount"] !== undefined ? _data["Discount"] : <any>null;
this.IsOnStock = _data["IsOnStock"] !== undefined ? _data["IsOnStock"] : <any>null;
}
}
static fromJS(data: any): OrderItem {
data = typeof data === 'object' ? data : {};
let result = new OrderItem();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
data["Id"] = this.Id !== undefined ? this.Id : <any>null;
data["Text"] = this.Text !== undefined ? this.Text : <any>null;
data["Amount"] = this.Amount !== undefined ? this.Amount : <any>null;
data["Discount"] = this.Discount !== undefined ? this.Discount : <any>null;
data["IsOnStock"] = this.IsOnStock !== undefined ? this.IsOnStock : <any>null;
return data;
}
}
export interface IOrderItem {
Id?: number | null;
Text?: string | null;
Amount?: number | null;
Discount?: number | null;
IsOnStock?: boolean | null;
}
export class ApiException extends Error {
message: string;
status: number;
response: string;
headers: { [key: string]: any; };
result: any;
constructor(message: string, status: number, response: string, headers: { [key: string]: any; }, result: any) {
super();
this.message = message;
this.status = status;
this.response = response;
this.headers = headers;
this.result = result;
}
protected isApiException = true;
static isApiException(obj: any): obj is ApiException {
return obj.isApiException === true;
}
}
function throwException(message: string, status: number, response: string, headers: { [key: string]: any; }, result?: any): any {
if (result !== null && result !== undefined)
throw result;
else
throw new ApiException(message, status, response, headers, null);
}
} | the_stack |
export module Constants {
export module Classes {
// animators
export var heightAnimator = "height-animator";
export var panelAnimator = "panel-animator";
export var clearfix = "clearfix";
// changeLogPanel
export var change = "change";
export var changes = "changes";
export var changeBody = "change-body";
export var changeDescription = "change-description";
export var changeImage = "change-image";
export var changeTitle = "change-title";
// checkbox
export var checkboxCheck = "checkboxCheck";
// textArea input control
export var textAreaInput = "textAreaInput";
export var textAreaInputMirror = "textAreaInputMirror";
// popover
export var popover = "popover";
export var popoverArrow = "popover-arrow";
// previewViewer
export var deleteHighlightButton = "delete-highlight";
export var highlightable = "highlightable";
export var highlighted = "highlighted";
export var regionSelection = "region-selection";
export var regionSelectionImage = "region-selection-image";
export var regionSelectionRemoveButton = "region-selection-remove-button";
// pdfPreviewViewer
export var attachmentOverlay = "attachment-overlay";
export var centeredInCanvas = "centered-in-canvas";
export var overlay = "overlay";
export var overlayHidden = "overlay-hidden";
export var overlayNumber = "overlay-number";
export var pdfPreviewImage = "pdf-preview-image";
export var pdfPreviewImageCanvas = "pdf-preview-image-canvas";
export var unselected = "unselected";
export var localPdfPanelTitle = "local-pdf-panel-title";
export var localPdfPanelSubtitle = "local-pdf-panel-subtitle";
// radioButton
export var radioIndicatorFill = "radio-indicator-fill";
// spriteAnimation
export var spinner = "spinner";
// Accessibility
export var srOnly = "sr-only";
// tooltip
export var tooltip = "tooltip";
// rotatingMessageSpriteAnimation
export var centeredInPreview = "centered-in-preview";
}
export module Cookies {
export var clipperInfo = "ClipperInfo";
}
export module Extension {
export module NotificationIds {
export var conflictingExtension = "conflictingExtension";
}
}
export module Ids {
// annotationInput
export var annotationContainer = "annotationContainer";
export var annotationField = "annotationField";
export var annotationFieldMirror = "annotationFieldMirror";
export var annotationPlaceholder = "annotationPlaceholder";
// bookmarkPreview
export var bookmarkThumbnail = "bookmarkThumbnail";
export var bookmarkPreviewContentContainer = "bookmarkPreviewContentContainer";
export var bookmarkPreviewInnerContainer = "bookmarkPreviewInnerContainer";
// clippingPanel
export var clipperApiProgressContainer = "clipperApiProgressContainer";
// clippingPanel
export var clipProgressDelayedMessage = "clipProgressDelayedMessage";
export var clipProgressIndicatorMessage = "clipProgressIndicatorMessage";
// dialogPanel
export var dialogBackButton = "dialogBackButton";
export var dialogButtonContainer = "dialogButtonContainer";
export var dialogDebugMessageContainer = "dialogDebugMessageContainer";
export var dialogMessageContainer = "dialogMessageContainer";
export var dialogContentContainer = "dialogContentContainer";
export var dialogMessage = "dialogMessage";
export var dialogSignOutButton = "dialogSignoutButton";
export var dialogTryAgainButton = "dialogTryAgainButton";
// editorPreviewComponentBase
export var highlightablePreviewBody = "highlightablePreviewBody";
// failurePanel
export var apiErrorMessage = "apiErrorMessage";
export var backToHomeButton = "backToHomeButton";
export var clipperFailureContainer = "clipperFailureContainer";
export var refreshPageButton = "refreshPageButton";
export var tryAgainButton = "tryAgainButton";
// footer
export var clipperFooterContainer = "clipperFooterContainer";
export var currentUserControl = "currentUserControl";
export var currentUserDetails = "currentUserDetails";
export var currentUserEmail = "currentUserEmail";
export var currentUserId = "currentUserId";
export var currentUserName = "currentUserName";
export var feedbackButton = "feedbackButton";
export var feedbackImage = "feedbackImage";
export var signOutButton = "signOutButton";
export var userDropdownArrow = "userDropdownArrow";
export var userSettingsContainer = "userSettingsContainer";
export var feedbackLabel = "feedbackLabel";
export var footerButtonsContainer = "footerButtonsContainer";
// loadingPanel
export var clipperLoadingContainer = "clipperLoadingContainer";
// mainController
export var closeButton = "closeButton";
export var closeButtonContainer = "closeButtonContainer";
export var mainController = "mainController";
// OneNotePicker
export var saveToLocationContainer = "saveToLocationContainer";
// optionsPanel
export var clipButton = "clipButton";
export var clipButtonContainer = "clipButtonContainer";
export var optionLabel = "optionLabel";
// previewViewerPdfHeader
export var radioAllPagesLabel = "radioAllPagesLabel";
export var radioPageRangeLabel = "radioPageRangeLabel";
export var rangeInput = "rangeInput";
// previewViewer
export var previewBody = "previewBody";
export var previewContentContainer = "previewContentContainer";
export var previewHeader = "previewHeader";
export var previewHeaderContainer = "previewHeaderContainer";
export var previewHeaderInput = "previewHeaderInput";
export var previewHeaderInputMirror = "previewHeaderInputMirror";
export var previewTitleContainer = "previewTitleContainer";
export var previewSubtitleContainer = "previewSubtitleContainer";
export var previewInnerContainer = "previewInnerContainer";
export var previewAriaLiveDiv = "previewAriaLiveDiv";
export var previewOptionsContainer = "previewOptionsContainer";
export var previewInnerWrapper = "previewInnerWrapper";
export var previewOuterContainer = "previewOuterContainer";
export var previewUrlContainer = "previewUrlContainer";
export var previewNotesContainer = "previewNotesContainer";
// previewViewerFullPageHeader
export var fullPageControl = "fullPageControl";
export var fullPageHeaderTitle = "fullPageHeaderTitle";
// previewViewerPdfHeader
export var localPdfFileTitle = "localPdfFileTitle";
export var pdfControl = "pdfControl";
export var pdfHeaderTitle = "pdfHeaderTitle";
export var pageRangeControl = "pageRangeControl";
// pdfClipOptions
export var checkboxToDistributePages = "checkboxToDistributePages";
export var pdfIsTooLargeToAttachIndicator = "pdfIsTooLargeToAttachIndicator";
export var checkboxToAttachPdf = "checkboxToAttachPdf";
export var moreClipOptions = "moreClipOptions";
// previewViewerRegionHeader
export var addAnotherRegionButton = "addAnotherRegionButton";
export var addRegionControl = "addRegionControl";
// previewViewerRegionTitleOnlyHeader
export var regionControl = "regionControl";
export var regionHeaderTitle = "regionHeaderTitle";
// previewViewerAugmentationHeader
export var decrementFontSize = "decrementFontSize";
export var fontSizeControl = "fontSizeControl";
export var highlightButton = "highlightButton";
export var highlightControl = "highlightControl";
export var incrementFontSize = "incrementFontSize";
export var serifControl = "serifControl";
export var sansSerif = "sansSerif";
export var serif = "serif";
// previewViewerBookmarkHeader
export var bookmarkControl = "bookmarkControl";
export var bookmarkHeaderTitle = "bookmarkHeaderTitle";
// ratingsPrompt
export var ratingsButtonFeedbackNo = "ratingsButtonFeedbackNo";
export var ratingsButtonFeedbackYes = "ratingsButtonFeedbackYes";
export var ratingsButtonInitNo = "ratingsButtonInitNo";
export var ratingsButtonInitYes = "ratingsButtonInitYes";
export var ratingsButtonRateNo = "ratingsButtonRateNo";
export var ratingsButtonRateYes = "ratingsButtonRateYes";
export var ratingsPromptContainer = "ratingsPromptContainer";
// regionSelectingPanel
export var regionInstructionsContainer = "regionInstructionsContainer";
export var regionClipCancelButton = "regionClipCancelButton";
// regionSelector
export var innerFrame = "innerFrame";
export var outerFrame = "outerFrame";
export var regionSelectorContainer = "regionSelectorContainer";
// rotatingMessageSpriteAnimation
export var spinnerText = "spinnerText";
// sectionPicker
export var locationPickerContainer = "locationPickerContainer";
export var sectionLocationContainer = "sectionLocationContainer";
// signInPanel
export var signInButtonMsa = "signInButtonMsa";
export var signInButtonOrgId = "signInButtonOrgId";
export var signInContainer = "signInContainer";
export var signInErrorCookieInformation = "signInErrorCookieInformation";
export var signInErrorDebugInformation = "signInErrorDebugInformation";
export var signInErrorDebugInformationDescription = "signInErrorDebugInformationDescription";
export var signInErrorDebugInformationContainer = "signInErrorDebugInformationContainer";
export var signInErrorDebugInformationList = "signInErrorDebugInformationList";
export var signInErrorDescription = "signInErrorDescription";
export var signInErrorDescriptionContainer = "signInErrorDescriptionContainer";
export var signInErrorMoreInformation = "signInErrorMoreInformation";
export var signInLogo = "signInLogo";
export var signInMessageLabelContainer = "signInMessageLabelContainer";
export var signInText = "signInText";
export var signInToggleErrorDropdownArrow = "signInToggleErrorDropdownArrow";
export var signInToggleErrorInformationText = "signInToggleErrorInformationText";
// successPanel
export var clipperSuccessContainer = "clipperSuccessContainer";
export var launchOneNoteButton = "launchOneNoteButton";
// tooltipRenderer
export var pageNavAnimatedTooltip = "pageNavAnimatedTooltip";
// unsupportedBrowser
export var unsupportedBrowserContainer = "unsupportedBrowserContainer";
export var unsupportedBrowserPanel = "unsupportedBrowserPanel";
// whatsNewPanel
export var changeLogSubPanel = "changeLogSubPanel";
export var checkOutWhatsNewButton = "checkOutWhatsNewButton";
export var proceedToWebClipperButton = "proceedToWebClipperButton";
export var whatsNewTitleSubPanel = "whatsNewTitleSubPanel";
export var clipperRootScript = "oneNoteCaptureRootScript";
export var clipperUiFrame = "oneNoteWebClipper";
export var clipperPageNavFrame = "oneNoteWebClipperPageNav";
export var clipperExtFrame = "oneNoteWebClipperExtension";
// tooltips
export var brandingContainer = "brandingContainer";
}
export module HeaderValues {
export var accept = "Accept";
export var appIdKey = "MS-Int-AppId";
export var correlationId = "X-CorrelationId";
export var noAuthKey = "X-NoAuth";
export var userSessionIdKey = "X-UserSessionId";
}
export module CommunicationChannels {
// Debug Logging
export var debugLoggingInjectedAndExtension = "DEBUGLOGGINGINJECTED_AND_EXTENSION";
// Web Clipper
export var extensionAndUi = "EXTENSION_AND_UI";
export var injectedAndUi = "INJECTED_AND_UI";
export var injectedAndExtension = "INJECTED_AND_EXTENSION";
// What's New
export var extensionAndPageNavUi = "EXTENSION_AND_PAGENAVUI";
export var pageNavInjectedAndPageNavUi = "PAGENAVINJECTED_AND_PAGENAVUI";
export var pageNavInjectedAndExtension = "PAGENAVINJECTED_AND_EXTENSION";
}
export module FunctionKeys {
export var clipperStrings = "CLIPPER_STRINGS";
export var clipperStringsFrontLoaded = "CLIPPER_STRINGS_FRONT_LOADED";
export var closePageNavTooltip = "CLOSE_PAGE_NAV_TOOLTIP";
export var createHiddenIFrame = "CREATE_HIDDEN_IFRAME";
export var ensureFreshUserBeforeClip = "ENSURE_FRESH_USER_BEFORE_CLIP";
export var escHandler = "ESC_HANDLER";
export var getInitialUser = "GET_INITIAL_USER";
export var getPageNavTooltipProps = "GET_PAGE_NAV_TOOLTIP_PROPS";
export var getStorageValue = "GET_STORAGE_VALUE";
export var getMultipleStorageValues = "GET_MULTIPLE_STORAGE_VALUES";
export var getTooltipToRenderInPageNav = "GET_TOOLTIP_TO_RENDER_IN_PAGE_NAV";
export var hideUi = "HIDE_UI";
export var invokeClipper = "INVOKE_CLIPPER";
export var invokeClipperFromPageNav = "INVOKE_CLIPPER_FROM_PAGE_NAV";
export var invokeDebugLogging = "INVOKE_DEBUG_LOGGING";
export var invokePageNav = "INVOKE_PAGE_NAV";
export var extensionNotAllowedToAccessLocalFiles = "EXTENSION_NOT_ALLOWED_TO_ACCESS_LOCAL_FILES";
export var noOpTracker = "NO_OP_TRACKER";
export var onSpaNavigate = "ON_SPA_NAVIGATE";
export var refreshPage = "REFRESH_PAGE";
export var showRefreshClipperMessage = "SHOW_REFRESH_CLIPPER_MESSAGE";
export var setInjectOptions = "SET_INJECT_OPTIONS";
export var setInvokeOptions = "SET_INVOKE_OPTIONS";
export var setStorageValue = "SET_STORAGE_VALUE";
export var signInUser = "SIGN_IN_USER";
export var signOutUser = "SIGN_OUT_USER";
export var tabToLowestIndexedElement = "TAB_TO_LOWEST_INDEXED_ELEMENT";
export var takeTabScreenshot = "TAKE_TAB_SCREENSHOT";
export var telemetry = "TELEMETRY";
export var toggleClipper = "TOGGLE_CLIPPER";
export var unloadHandler = "UNLOAD_HANDLER";
export var updateFrameHeight = "UPDATE_FRAME_HEIGHT";
export var updatePageInfoIfUrlChanged = "UPDATE_PAGE_INFO_IF_URL_CHANGED";
}
export module KeyCodes {
// event.which is deprecated -.-
export var tab = 9;
export var enter = 13;
export var esc = 27;
export var c = 67;
export var down = 40;
export var up = 38;
export var left = 37;
export var right = 39;
export var space = 32;
export var home = 36;
export var end = 35;
}
export module StringKeyCodes {
export var c = "KeyC";
}
export module SmartValueKeys {
export var clientInfo = "CLIENT_INFO";
export var isFullScreen = "IS_FULL_SCREEN";
export var pageInfo = "PAGE_INFO";
export var sessionId = "SESSION_ID";
export var user = "USER";
}
export module Styles {
export var sectionPickerContainerHeight = 280;
export var clipperUiWidth = 322;
export var customCursorSize = 20;
export var clipperUiTopRightOffset = 20;
export var clipperUiDropShadowBuffer = 7;
export var clipperUiInnerPadding = 30;
export module Colors {
export var oneNoteHighlightColor = "#fefe56";
}
}
export module Urls {
export var serviceDomain = "https://www.onenote.com";
export var augmentationApiUrl = serviceDomain + "/onaugmentation/clipperextract/v1.0/";
export var changelogUrl = serviceDomain + "/whatsnext/webclipper";
export var clipperFeedbackUrl = serviceDomain + "/feedback";
export var clipperInstallPageUrl = serviceDomain + "/clipper/installed";
export var fullPageScreenshotUrl = serviceDomain + "/onaugmentation/clipperDomEnhancer/v1.0/";
export var localizedStringsUrlBase = serviceDomain + "/strings?ids=WebClipper.";
export var msaDomain = "https://login.live.com";
export var orgIdDomain = "https://login.microsoftonline.com";
export module Authentication {
export var authRedirectUrl = serviceDomain + "/webclipper/auth";
export var signInUrl = serviceDomain + "/webclipper/signin";
export var signOutUrl = serviceDomain + "/webclipper/signout";
export var userInformationUrl = serviceDomain + "/webclipper/userinfo";
}
export module QueryParams {
export var authType = "authType";
export var category = "category";
export var changelogLocale = "omkt";
export var channel = "channel";
export var clientType = "clientType";
export var clipperId = "clipperId";
export var clipperVersion = "clipperVersion";
export var correlationId = "correlationId";
export var error = "error";
export var errorDescription = "error_?description";
export var event = "event";
export var eventName = "eventName";
export var failureId = "failureId";
export var failureInfo = "failureInfo";
export var failureType = "failureType";
export var inlineInstall = "inlineInstall";
export var label = "label";
export var noOpType = "noOpType";
export var stackTrace = "stackTrace";
export var timeoutInMs = "timeoutInMs";
export var url = "url";
export var userSessionId = "userSessionId";
export var wdFromClipper = "wdfromclipper"; // This naming convention is standard in OneNote Online
}
}
export module LogCategories {
export var oneNoteClipperUsage = "OneNoteClipperUsage";
}
export module Settings {
export var fontSizeStep = 2;
export var maxClipSuccessForRatingsPrompt = 12;
export var maximumJSTimeValue = 1000 * 60 * 60 * 24 * 100000000; // 100M days in milliseconds, http://ecma-international.org/ecma-262/5.1/#sec-15.9.1.1
export var maximumFontSize = 72;
export var maximumNumberOfTimesToShowTooltips = 3;
export var maximumMimeSizeLimit = 24900000;
export var minClipSuccessForRatingsPrompt = 4;
export var minimumFontSize = 8;
export var minTimeBetweenBadRatings = 1000 * 60 * 60 * 24 * 7 * 10; // 10 weeks
export var noOpTrackerTimeoutDuration = 20 * 1000; // 20 seconds
export var numRetriesPerPatchRequest = 3;
export var pdfCheckCreatePageInterval = 2000; // 2 seconds
export var pdfClippingMessageDelay = 5000; // 5 seconds
export var pdfExtraPageLoadEachSide = 1;
export var pdfInitialPageLoadCount = 3;
export var timeBetweenDifferentTooltips = 1000 * 60 * 60 * 24 * 7 * 1; // 1 week
export var timeBetweenSameTooltip = 1000 * 60 * 60 * 24 * 7 * 3; // 3 weeks
export var timeBetweenTooltips = 1000 * 60 * 60 * 24 * 7 * 3; // 21 days
export var timeUntilPdfPageNumbersFadeOutAfterScroll = 1000; // 1 second
}
export module CustomHtmlAttributes {
export var setNameForArrowKeyNav = "setnameforarrowkeynav";
}
export module AriaSet {
export var modeButtonSet = "ariaModeButtonSet";
export var pdfPageSelection = "pdfPageSelection";
export var serifGroupSet = "serifGroupSet";
}
} | the_stack |
import React from 'react';
import createClass from 'create-react-class';
import { Grid } from './../../index';
export default {
title: 'Layout/Grid',
component: Grid,
parameters: {
docs: {
description: {
component: (Grid as any).peek.description,
},
},
},
};
/* Grid Columns */
export const GridColumns = () => {
const gridStyle = {
half: { background: '#0089c4' },
quarter: { background: '#f7403a' },
third: { background: '#3fa516', color: '#f3f3f3' },
full: { background: '#333333', color: '#f3f3f3' },
auto: { background: '#999999', color: '#f3f3f3' },
flexdefault: { background: '#feb209' },
sharedStyles: {
margin: 0,
padding: 0,
color: '#f3f3f3',
},
vertical: { height: '100px' },
};
const fillCells = (count: any) => {
const cells: any = [];
for (let i = 0; i < count; i++) {
cells.push(
<Grid.Cell key={i}>
<p style={{ ...gridStyle.auto, ...gridStyle.sharedStyles }}>auto</p>
</Grid.Cell>
);
}
return cells;
};
const Component = createClass({
render() {
return (
<div>
<Grid>
<Grid.Cell isFull>
<p style={{ ...gridStyle.full, ...gridStyle.sharedStyles }}>
full
</p>
</Grid.Cell>
</Grid>
<Grid>
<Grid.Cell is2>
<p
style={{ ...gridStyle.flexdefault, ...gridStyle.sharedStyles }}
>
2
</p>
</Grid.Cell>
{fillCells(12 - 2)}
</Grid>
<Grid>
<Grid.Cell is3>
<p
style={{ ...gridStyle.flexdefault, ...gridStyle.sharedStyles }}
>
3
</p>
</Grid.Cell>
{fillCells(12 - 3)}
</Grid>
<Grid>
<Grid.Cell is4>
<p
style={{ ...gridStyle.flexdefault, ...gridStyle.sharedStyles }}
>
4
</p>
</Grid.Cell>
{fillCells(12 - 4)}
</Grid>
<Grid>
<Grid.Cell is5>
<p
style={{ ...gridStyle.flexdefault, ...gridStyle.sharedStyles }}
>
5
</p>
</Grid.Cell>
{fillCells(12 - 5)}
</Grid>
<Grid>
<Grid.Cell is6>
<p
style={{ ...gridStyle.flexdefault, ...gridStyle.sharedStyles }}
>
6
</p>
</Grid.Cell>
{fillCells(12 - 6)}
</Grid>
<Grid>
<Grid.Cell is7>
<p
style={{ ...gridStyle.flexdefault, ...gridStyle.sharedStyles }}
>
7
</p>
</Grid.Cell>
{fillCells(12 - 7)}
</Grid>
<Grid>
<Grid.Cell is8>
<p
style={{ ...gridStyle.flexdefault, ...gridStyle.sharedStyles }}
>
8
</p>
</Grid.Cell>
{fillCells(12 - 8)}
</Grid>
<Grid>
<Grid.Cell is9>
<p
style={{ ...gridStyle.flexdefault, ...gridStyle.sharedStyles }}
>
9
</p>
</Grid.Cell>
{fillCells(12 - 9)}
</Grid>
<Grid>
<Grid.Cell is10>
<p
style={{ ...gridStyle.flexdefault, ...gridStyle.sharedStyles }}
>
10
</p>
</Grid.Cell>
{fillCells(12 - 10)}
</Grid>
<Grid>
<Grid.Cell is11>
<p
style={{ ...gridStyle.flexdefault, ...gridStyle.sharedStyles }}
>
11
</p>
</Grid.Cell>
{fillCells(12 - 11)}
</Grid>
</div>
);
},
});
return <Component />;
};
GridColumns.storyName = 'GridColumns';
/* Gutterless Grid */
export const GutterlessGrid = () => {
const gridStyle = {
half: { background: '#0089c4' },
quarter: { background: '#f7403a' },
third: { background: '#3fa516', color: '#f3f3f3' },
full: { background: '#333333', color: '#f3f3f3' },
auto: { background: '#999999', color: '#f3f3f3' },
flexdefault: { background: '#feb209' },
sharedStyles: {
margin: 0,
padding: 0,
color: '#f3f3f3',
},
vertical: { height: '100px' },
};
const fillCells = (count: any) => {
const cells: any = [];
for (let i = 0; i < count; i++) {
cells.push(
<Grid.Cell key={i}>
<p style={{ ...gridStyle.auto, ...gridStyle.sharedStyles }}>auto</p>
</Grid.Cell>
);
}
return cells;
};
const Component = createClass({
render() {
return (
<Grid isGutterless isMultiline>
<Grid.Cell isHalf>
<p style={{ ...gridStyle.half, ...gridStyle.sharedStyles }}>
gutterless half
</p>
</Grid.Cell>
<Grid.Cell
style={{ ...gridStyle.quarter, ...gridStyle.sharedStyles }}
isQuarter
>
gutterless quarter
</Grid.Cell>
{fillCells(1)}
<Grid.Cell isQuarter>
<p style={{ ...gridStyle.quarter, ...gridStyle.sharedStyles }}>
gutterless quarter
</p>
</Grid.Cell>
<Grid.Cell isQuarter>
<p style={{ ...gridStyle.quarter, ...gridStyle.sharedStyles }}>
gutterless quarter
</p>
</Grid.Cell>
<Grid.Cell isHalf>
<p style={{ ...gridStyle.half, ...gridStyle.sharedStyles }}>
gutterless half
</p>
</Grid.Cell>
</Grid>
);
},
});
return <Component />;
};
GutterlessGrid.storyName = 'GutterlessGrid';
/* Horizontal Multiline Grid */
export const HorizontalMultilineGrid = () => {
const gridStyle = {
half: { background: '#0089c4' },
quarter: { background: '#f7403a' },
third: { background: '#3fa516', color: '#f3f3f3' },
full: { background: '#333333', color: '#f3f3f3' },
auto: { background: '#999999', color: '#f3f3f3' },
flexdefault: { background: '#feb209' },
sharedStyles: {
margin: 0,
padding: 0,
color: '#f3f3f3',
},
vertical: { height: '100px' },
};
const Component = createClass({
render() {
return (
<Grid isHorizontal isMultiline>
<Grid.Cell isHalf>
<p style={{ ...gridStyle.half, ...gridStyle.sharedStyles }}>half</p>
</Grid.Cell>
<Grid.Cell isHalf>
<p style={{ ...gridStyle.half, ...gridStyle.sharedStyles }}>half</p>
</Grid.Cell>
<Grid.Cell isHalf>
<p style={{ ...gridStyle.half, ...gridStyle.sharedStyles }}>half</p>
</Grid.Cell>
<Grid.Cell isFull>
<p style={{ ...gridStyle.full, ...gridStyle.sharedStyles }}>full</p>
</Grid.Cell>
<Grid.Cell isThird>
<p style={{ ...gridStyle.third, ...gridStyle.sharedStyles }}>
third
</p>
</Grid.Cell>
<Grid.Cell isThird>
<p style={{ ...gridStyle.third, ...gridStyle.sharedStyles }}>
third
</p>
</Grid.Cell>
<Grid.Cell isThird>
<p style={{ ...gridStyle.third, ...gridStyle.sharedStyles }}>
third
</p>
</Grid.Cell>
<Grid.Cell isThird>
<p style={{ ...gridStyle.third, ...gridStyle.sharedStyles }}>
third
</p>
</Grid.Cell>
<Grid.Cell isQuarter>
<p style={{ ...gridStyle.quarter, ...gridStyle.sharedStyles }}>
quarter
</p>
</Grid.Cell>
<Grid.Cell isQuarter>
<p style={{ ...gridStyle.quarter, ...gridStyle.sharedStyles }}>
quarter
</p>
</Grid.Cell>
<Grid.Cell isQuarter>
<p style={{ ...gridStyle.quarter, ...gridStyle.sharedStyles }}>
quarter
</p>
</Grid.Cell>
</Grid>
);
},
});
return <Component />;
};
HorizontalMultilineGrid.storyName = 'HorizontalMultilineGrid';
/* Offset Cells */
export const OffsetCells = () => {
const gridStyle = {
half: { background: '#0089c4' },
quarter: { background: '#f7403a' },
third: { background: '#3fa516', color: '#f3f3f3' },
full: { background: '#333333', color: '#f3f3f3' },
auto: { background: '#999999', color: '#f3f3f3' },
flexdefault: { background: '#feb209' },
sharedStyles: {
margin: 0,
padding: 0,
color: '#f3f3f3',
textAlign: 'center',
},
vertical: { height: '100px' },
};
const Component = createClass({
render() {
return (
<div>
<Grid>
<Grid.Cell isHalf isOffsetHalf>
<p
style={{ ...gridStyle.half, ...gridStyle.sharedStyles } as any}
>
half with offset half
</p>
</Grid.Cell>
</Grid>
<Grid>
<Grid.Cell isQuarter isOffsetQuarter>
<p
style={
{ ...gridStyle.quarter, ...gridStyle.sharedStyles } as any
}
>
quarter with offset quarter
</p>
</Grid.Cell>
</Grid>
<Grid>
<Grid.Cell isThird isOffsetThird>
<p
style={{ ...gridStyle.third, ...gridStyle.sharedStyles } as any}
>
third with offset third
</p>
</Grid.Cell>
</Grid>
</div>
);
},
});
return <Component />;
};
OffsetCells.storyName = 'OffsetCells';
/* Vertical Multiline Grid */
export const VerticalMultilineGrid = () => {
const gridStyle = {
half: { background: '#0089c4' },
quarter: { background: '#f7403a' },
third: { background: '#3fa516', color: '#f3f3f3' },
full: { background: '#333333', color: '#f3f3f3' },
auto: { background: '#999999', color: '#f3f3f3' },
flexdefault: { background: '#feb209' },
sharedStyles: {
margin: 0,
padding: 0,
color: '#f3f3f3',
},
vertical: { height: '200px' },
verticalSharedStyles: {
margin: 0,
padding: 0,
color: '#f3f3f3',
flex: 1,
},
};
const Component = createClass({
render() {
return (
<Grid style={{ ...gridStyle.vertical }} isVertical isMultiline>
<Grid.Cell isHalf>
<p style={{ ...gridStyle.half, ...gridStyle.verticalSharedStyles }}>
half
</p>
</Grid.Cell>
<Grid.Cell isHalf>
<p style={{ ...gridStyle.half, ...gridStyle.verticalSharedStyles }}>
half
</p>
</Grid.Cell>
<Grid.Cell isHalf>
<p style={{ ...gridStyle.half, ...gridStyle.verticalSharedStyles }}>
half
</p>
</Grid.Cell>
<Grid.Cell isFull>
<p style={{ ...gridStyle.full, ...gridStyle.verticalSharedStyles }}>
full
</p>
</Grid.Cell>
<Grid.Cell isThird>
<p
style={{ ...gridStyle.third, ...gridStyle.verticalSharedStyles }}
>
third
</p>
</Grid.Cell>
<Grid.Cell isThird>
<p
style={{ ...gridStyle.third, ...gridStyle.verticalSharedStyles }}
>
third
</p>
</Grid.Cell>
<Grid.Cell isThird>
<p
style={{ ...gridStyle.third, ...gridStyle.verticalSharedStyles }}
>
third
</p>
</Grid.Cell>
<Grid.Cell isThird>
<p
style={{ ...gridStyle.third, ...gridStyle.verticalSharedStyles }}
>
third
</p>
</Grid.Cell>
<Grid.Cell isQuarter>
<p
style={{
...gridStyle.quarter,
...gridStyle.verticalSharedStyles,
}}
>
quarter
</p>
</Grid.Cell>
<Grid.Cell isQuarter>
<p
style={{
...gridStyle.quarter,
...gridStyle.verticalSharedStyles,
}}
>
quarter
</p>
</Grid.Cell>
<Grid.Cell isQuarter>
<p
style={{
...gridStyle.quarter,
...gridStyle.verticalSharedStyles,
}}
>
quarter
</p>
</Grid.Cell>
</Grid>
);
},
});
return <Component />;
};
VerticalMultilineGrid.storyName = 'VerticalMultilineGrid'; | the_stack |
import React, { useState, useEffect } from 'react';
import { useHistory, useParams } from 'react-router-dom';
import { DefaultButton, Dropdown, DropdownMenuItemType, IDropdownOption, PrimaryButton, Stack, Checkbox, Toggle, IComboBoxOption, ComboBox, IComboBox, Text, Label } from '@fluentui/react';
import { Component, ComponentTaskTemplate, ComponentTemplate, ScheduleDefinition } from 'teamcloud';
import { useOrg, useProject, useProjectComponentTemplates, useProjectComponents, useProjectMembers, useUser, useCreateProjectSchedule, useProjectSchedule, useUpdateProjectSchedule } from '../hooks';
import { DaysOfWeek, DaysOfWeekNames, ProjectMember, shiftToLocal, shiftToUtc } from '../model';
import { ContentSeparator } from '.';
import { ErrorBar } from './common';
export const ScheduleForm: React.FC = () => {
const history = useHistory();
const { orgId, projectId, itemId } = useParams() as { orgId: string, projectId: string, itemId: string };
const now = new Date();
const [formEnabled, setFormEnabled] = useState<boolean>(true);
const [errorResult, setErrorResult] = useState<any>();
const [componentTaskOptions, setComponentTaskOptions] = useState<IDropdownOption[]>();
const [timeOptions] = useState<IComboBoxOption[]>(
[...Array(24).keys()]
.flatMap(h => [...Array(60).keys()].filter(m => m % 5 === 0).map(m => new Date(now.getFullYear(), now.getMonth(), now.getDate(), h, m, 0, 0)))
.map(d => ({ key: ((d.getHours() * 60) + d.getMinutes()), text: d.toTimeDisplayString(false), data: d })));
const [member, setMember] = useState<ProjectMember>();
const [availableComponents, setAvailableComponents] = useState<{ component: Component, template?: ComponentTemplate }[]>();
const [isNew, setIsNew] = useState(true);
const [daysOfWeek, setDaysOfWeek] = useState([1, 2, 3, 4, 5]);
const [timeDate, setTimeDate] = useState<Date>();
const [enabled, setEnabled] = useState(true);
const [recurring, setRecurring] = useState(true);
const [componentTasks, setComponentTasks] = useState<{ component: Component, template: ComponentTemplate, taskTemplate: ComponentTaskTemplate }[]>([]);
const { data: org } = useOrg();
const { data: user } = useUser();
const { data: project } = useProject();
const { data: members } = useProjectMembers();
const { data: components } = useProjectComponents();
const { data: templates } = useProjectComponentTemplates();
const { data: schedule } = useProjectSchedule();
const createSchedule = useCreateProjectSchedule();
const updateSchedule = useUpdateProjectSchedule();
const timezone = now.toTimeZoneString();
const _scheduleComplete = () => timeDate && daysOfWeek && daysOfWeek.length > 0 && componentTasks && componentTasks.length > 0;
// const _scheduleComplete = () => true;
useEffect(() => {
if (itemId && schedule && components && templates && isNew) {
console.log('setIsNew(false);');
const refDate = new Date();
refDate.setUTCHours(schedule.utcHour!, schedule.utcMinute, 0, 0);
const days = shiftToLocal(schedule.daysOfWeek!, refDate);
const _tasks = schedule.componentTasks?.map(ct => {
const _component = components.find(c => c.id === ct.componentId)!;
const _template = templates.find(t => t.id === _component.templateId)!;
const _taskTemplate = _template.tasks!.find(tt => tt.id === ct.componentTaskTemplateId)!;
return { component: _component, template: _template, taskTemplate: _taskTemplate };
}) ?? [];
setDaysOfWeek(days.indices);
setTimeDate(refDate);
setEnabled(schedule.enabled ?? true);
setRecurring(schedule.recurring ?? true);
setComponentTasks(_tasks);
setIsNew(false);
}
}, [isNew, itemId, schedule, components, templates]);
useEffect(() => {
if (user && members && !member) {
console.log(`+ setMember`);
setMember(members.find(m => m.user.id === user.id));
}
}, [user, member, members]);
useEffect(() => {
if (member && components && templates && !availableComponents) {
console.log(`+ setAvailableComponents`);
const _orgRole = member.user.role.toLowerCase();
const _projectRole = member.projectMembership.role.toLowerCase();
const _isAdmin = _orgRole === 'owner' || _orgRole === 'admin' || _projectRole === 'owner' || _projectRole === 'admin';
if (_isAdmin) {
setAvailableComponents(components.map(c => ({ component: c, template: templates.find(t => t.id === c.templateId) })));
} else {
setAvailableComponents(components.filter(c => c.creator === member.user.id).map(c => ({ component: c, template: templates.find(t => t.id === c.templateId) })));
}
}
}, [member, components, templates, availableComponents]);
useEffect(() => {
if (availableComponents && !componentTaskOptions) {
console.log(`+ setComponentTaskOptions`);
const _options: IDropdownOption[] = [];
availableComponents.forEach(c => {
_options.push({ key: c.component.id, text: c.component.displayName ?? c.component.slug, itemType: DropdownMenuItemType.Header });
if (c.template?.tasks) {
const _tasks = c.template.tasks.map(t => ({ key: `${c.component.id}${t.id!}`, text: t.displayName ?? t.id!, data: { component: c.component, template: c.template!, taskTemplate: t } }));
_options.push(..._tasks);
}
});
setComponentTaskOptions(_options);
}
}, [availableComponents, componentTaskOptions]);
const _submitForm = async () => {
if (timeDate && componentTasks && _scheduleComplete()) {
setFormEnabled(false);
const days = shiftToUtc(daysOfWeek, timeDate);
try {
if (isNew) {
const scheduleDef: ScheduleDefinition = {
enabled: enabled,
recurring: recurring,
utcHour: timeDate.getUTCHours(),
utcMinute: timeDate.getUTCMinutes(),
daysOfWeek: days.names,
componentTasks: componentTasks.map(ct => ({ componentId: ct.component.id, componentTaskTemplateId: ct.taskTemplate.id }))
}
// console.log(JSON.stringify(scheduleDef));
await createSchedule(scheduleDef);
} else if (schedule) {
schedule.enabled = enabled;
schedule.recurring = recurring;
schedule.utcHour = timeDate.getUTCHours();
schedule.utcMinute = timeDate.getUTCMinutes();
schedule.daysOfWeek = days.names;
schedule.componentTasks = componentTasks.map(ct => ({ componentId: ct.component.id, componentTaskTemplateId: ct.taskTemplate.id }));
await updateSchedule(schedule);
}
setFormEnabled(true);
} catch (error) {
setErrorResult(error);
setFormEnabled(true);
}
}
};
const _resetAndCloseForm = () => {
setFormEnabled(true);
history.push(`/orgs/${org?.slug ?? orgId}/projects/${project?.slug ?? projectId}/settings/schedules`);
};
const _onTimeComboBoxChange = (event: React.FormEvent<IComboBox>, option?: IComboBoxOption, index?: number, value?: string): void => {
if (option?.data instanceof Date) {
setTimeDate(option.data);
}
};
const _onComponentDropdownChange = (event: React.FormEvent<HTMLDivElement>, option?: IDropdownOption, index?: number): void => {
if (componentTasks === undefined || option?.data === undefined || option?.selected === undefined) return;
const data = option.data as { component: Component, template: ComponentTemplate, taskTemplate: ComponentTaskTemplate };
const item = componentTasks.find(ct => !!ct.taskTemplate.id && (ct.component.id === data.component.id && ct.taskTemplate.id === data.taskTemplate.id));
if (option.selected && !item)
setComponentTasks([...componentTasks, data]);
else if (!option.selected && !!item)
setComponentTasks(componentTasks.filter(ct => !!ct.taskTemplate.id && !(ct.component.id === data.component.id && ct.taskTemplate.id === data.taskTemplate.id)));
};
const _updateDaysOfWeek = (dayIndex: number, checked?: boolean) => {
if (checked === undefined || dayIndex < 0 || dayIndex > 6) return;
if (checked && !daysOfWeek.includes(dayIndex))
setDaysOfWeek([...daysOfWeek, dayIndex]);
else if (!checked && daysOfWeek.includes(dayIndex))
setDaysOfWeek(daysOfWeek.filter(d => d !== dayIndex))
}
return (
<Stack tokens={{ childrenGap: '40px' }}>
<ErrorBar stackItem error={errorResult} />
<Stack.Item grow styles={{ root: { minWidth: '40%', } }}>
<Stack styles={{ root: { paddingTop: '20px' } }} tokens={{ childrenGap: '20px' }}>
<Stack.Item>
<Stack horizontal tokens={{ childrenGap: '60px' }}>
<Stack.Item>
<Toggle label='Enabled' checked={enabled} onChange={(_, checked) => setEnabled(checked ?? false)} />
</Stack.Item>
<Stack.Item>
<Toggle label='Recurring' checked={recurring} onChange={(_, checked) => setRecurring(checked ?? false)} />
</Stack.Item>
</Stack>
</Stack.Item>
<Stack.Item>
<ContentSeparator />
</Stack.Item>
<Stack.Item>
<Label required>Days of the week</Label>
<Stack horizontal styles={{ root: { paddingTop: '8px' } }} tokens={{ childrenGap: '12px' }}>
{DaysOfWeek
.map(i => (
<Stack.Item key={i}>
<Checkbox key={i} label={DaysOfWeekNames[i]} checked={daysOfWeek.includes(i)} onChange={(_, checked) => _updateDaysOfWeek(i, checked)} />
</Stack.Item>)
)}
</Stack>
</Stack.Item>
<Stack.Item>
<ContentSeparator />
</Stack.Item>
<Stack.Item >
<ComboBox
required
label='Time'
disabled={!formEnabled}
options={timeOptions || []}
selectedKey={timeDate ? ((timeDate.getHours() * 60) + timeDate.getMinutes()) : undefined}
styles={{ root: { maxWidth: '400px' }, optionsContainerWrapper: { maxHeight: '400px' } }}
onChange={_onTimeComboBoxChange} />
<Text variant='small' >{timezone}</Text>
</Stack.Item>
<Stack.Item>
<ContentSeparator />
</Stack.Item>
<Stack.Item>
<Dropdown
required
label='Component Tasks'
disabled={!formEnabled}
options={componentTaskOptions || []}
styles={{ root: { maxWidth: '400px' }, dropdownItemsWrapper: { maxHeight: '400px' } }}
multiSelect
selectedKeys={componentTasks.filter(ct => !!ct.taskTemplate.id).map(ct => `${ct.component.id}${ct.taskTemplate.id!}`)}
onChange={_onComponentDropdownChange} />
</Stack.Item>
<Stack.Item styles={{ root: { paddingTop: '24px' } }}>
<PrimaryButton text={isNew ? 'Create schedule' : 'Update schedule'} disabled={!formEnabled || !_scheduleComplete()} onClick={() => _submitForm()} styles={{ root: { marginRight: 8 } }} />
<DefaultButton text='Cancel' disabled={!formEnabled} onClick={() => _resetAndCloseForm()} />
</Stack.Item>
</Stack>
</Stack.Item>
</Stack>
);
} | the_stack |
export type Maybe<T> = T | null
export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] }
export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> }
export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> }
/** All built-in and custom scalars, mapped to their actual values */
export type Scalars = {
ID: string
String: string
Boolean: boolean
Int: number
Float: number
citext: any
// eslint-disable-next-line @typescript-eslint/ban-types
jsonb: object
timestamptz: string
uuid: string
}
/** columns and relationships of "auth.account_providers" */
export type Auth_Account_Providers = {
__typename?: 'auth_account_providers'
/** An object relationship */
account: Auth_Accounts
account_id: Scalars['uuid']
auth_provider: Scalars['String']
auth_provider_unique_id: Scalars['String']
created_at: Scalars['timestamptz']
id: Scalars['uuid']
/** An object relationship */
provider: Auth_Providers
updated_at: Scalars['timestamptz']
}
/** aggregated selection of "auth.account_providers" */
export type Auth_Account_Providers_Aggregate = {
__typename?: 'auth_account_providers_aggregate'
aggregate?: Maybe<Auth_Account_Providers_Aggregate_Fields>
nodes: Array<Auth_Account_Providers>
}
/** aggregate fields of "auth.account_providers" */
export type Auth_Account_Providers_Aggregate_Fields = {
__typename?: 'auth_account_providers_aggregate_fields'
count: Scalars['Int']
max?: Maybe<Auth_Account_Providers_Max_Fields>
min?: Maybe<Auth_Account_Providers_Min_Fields>
}
/** aggregate fields of "auth.account_providers" */
export type Auth_Account_Providers_Aggregate_FieldsCountArgs = {
columns?: Maybe<Array<Auth_Account_Providers_Select_Column>>
distinct?: Maybe<Scalars['Boolean']>
}
/** aggregate max on columns */
export type Auth_Account_Providers_Max_Fields = {
__typename?: 'auth_account_providers_max_fields'
account_id?: Maybe<Scalars['uuid']>
auth_provider?: Maybe<Scalars['String']>
auth_provider_unique_id?: Maybe<Scalars['String']>
created_at?: Maybe<Scalars['timestamptz']>
id?: Maybe<Scalars['uuid']>
updated_at?: Maybe<Scalars['timestamptz']>
}
/** aggregate min on columns */
export type Auth_Account_Providers_Min_Fields = {
__typename?: 'auth_account_providers_min_fields'
account_id?: Maybe<Scalars['uuid']>
auth_provider?: Maybe<Scalars['String']>
auth_provider_unique_id?: Maybe<Scalars['String']>
created_at?: Maybe<Scalars['timestamptz']>
id?: Maybe<Scalars['uuid']>
updated_at?: Maybe<Scalars['timestamptz']>
}
/** response of any mutation on the table "auth.account_providers" */
export type Auth_Account_Providers_Mutation_Response = {
__typename?: 'auth_account_providers_mutation_response'
/** number of rows affected by the mutation */
affected_rows: Scalars['Int']
/** data from the rows affected by the mutation */
returning: Array<Auth_Account_Providers>
}
/** columns and relationships of "auth.account_roles" */
export type Auth_Account_Roles = {
__typename?: 'auth_account_roles'
/** An object relationship */
account: Auth_Accounts
account_id: Scalars['uuid']
created_at: Scalars['timestamptz']
id: Scalars['uuid']
role: Scalars['String']
/** An object relationship */
roleByRole: Auth_Roles
}
/** aggregated selection of "auth.account_roles" */
export type Auth_Account_Roles_Aggregate = {
__typename?: 'auth_account_roles_aggregate'
aggregate?: Maybe<Auth_Account_Roles_Aggregate_Fields>
nodes: Array<Auth_Account_Roles>
}
/** aggregate fields of "auth.account_roles" */
export type Auth_Account_Roles_Aggregate_Fields = {
__typename?: 'auth_account_roles_aggregate_fields'
count: Scalars['Int']
max?: Maybe<Auth_Account_Roles_Max_Fields>
min?: Maybe<Auth_Account_Roles_Min_Fields>
}
/** aggregate fields of "auth.account_roles" */
export type Auth_Account_Roles_Aggregate_FieldsCountArgs = {
columns?: Maybe<Array<Auth_Account_Roles_Select_Column>>
distinct?: Maybe<Scalars['Boolean']>
}
/** aggregate max on columns */
export type Auth_Account_Roles_Max_Fields = {
__typename?: 'auth_account_roles_max_fields'
account_id?: Maybe<Scalars['uuid']>
created_at?: Maybe<Scalars['timestamptz']>
id?: Maybe<Scalars['uuid']>
role?: Maybe<Scalars['String']>
}
/** aggregate min on columns */
export type Auth_Account_Roles_Min_Fields = {
__typename?: 'auth_account_roles_min_fields'
account_id?: Maybe<Scalars['uuid']>
created_at?: Maybe<Scalars['timestamptz']>
id?: Maybe<Scalars['uuid']>
role?: Maybe<Scalars['String']>
}
/** response of any mutation on the table "auth.account_roles" */
export type Auth_Account_Roles_Mutation_Response = {
__typename?: 'auth_account_roles_mutation_response'
/** number of rows affected by the mutation */
affected_rows: Scalars['Int']
/** data from the rows affected by the mutation */
returning: Array<Auth_Account_Roles>
}
/** columns and relationships of "auth.accounts" */
export type Auth_Accounts = {
__typename?: 'auth_accounts'
/** An array relationship */
account_providers: Array<Auth_Account_Providers>
/** An aggregate relationship */
account_providers_aggregate: Auth_Account_Providers_Aggregate
/** An array relationship */
account_roles: Array<Auth_Account_Roles>
/** An aggregate relationship */
account_roles_aggregate: Auth_Account_Roles_Aggregate
active: Scalars['Boolean']
created_at: Scalars['timestamptz']
custom_register_data?: Maybe<Scalars['jsonb']>
default_role: Scalars['String']
email?: Maybe<Scalars['citext']>
id: Scalars['uuid']
is_anonymous: Scalars['Boolean']
mfa_enabled: Scalars['Boolean']
new_email?: Maybe<Scalars['citext']>
otp_secret?: Maybe<Scalars['String']>
password_hash?: Maybe<Scalars['String']>
/** An array relationship */
refresh_tokens: Array<Auth_Refresh_Tokens>
/** An aggregate relationship */
refresh_tokens_aggregate: Auth_Refresh_Tokens_Aggregate
/** An object relationship */
role: Auth_Roles
ticket: Scalars['uuid']
ticket_expires_at: Scalars['timestamptz']
updated_at: Scalars['timestamptz']
/** An object relationship */
user: Users
user_id: Scalars['uuid']
}
/** columns and relationships of "auth.accounts" */
export type Auth_AccountsAccount_ProvidersArgs = {
distinct_on?: Maybe<Array<Auth_Account_Providers_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Account_Providers_Order_By>>
where?: Maybe<Auth_Account_Providers_Bool_Exp>
}
/** columns and relationships of "auth.accounts" */
export type Auth_AccountsAccount_Providers_AggregateArgs = {
distinct_on?: Maybe<Array<Auth_Account_Providers_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Account_Providers_Order_By>>
where?: Maybe<Auth_Account_Providers_Bool_Exp>
}
/** columns and relationships of "auth.accounts" */
export type Auth_AccountsAccount_RolesArgs = {
distinct_on?: Maybe<Array<Auth_Account_Roles_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Account_Roles_Order_By>>
where?: Maybe<Auth_Account_Roles_Bool_Exp>
}
/** columns and relationships of "auth.accounts" */
export type Auth_AccountsAccount_Roles_AggregateArgs = {
distinct_on?: Maybe<Array<Auth_Account_Roles_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Account_Roles_Order_By>>
where?: Maybe<Auth_Account_Roles_Bool_Exp>
}
/** columns and relationships of "auth.accounts" */
export type Auth_AccountsCustom_Register_DataArgs = {
path?: Maybe<Scalars['String']>
}
/** columns and relationships of "auth.accounts" */
export type Auth_AccountsRefresh_TokensArgs = {
distinct_on?: Maybe<Array<Auth_Refresh_Tokens_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Refresh_Tokens_Order_By>>
where?: Maybe<Auth_Refresh_Tokens_Bool_Exp>
}
/** columns and relationships of "auth.accounts" */
export type Auth_AccountsRefresh_Tokens_AggregateArgs = {
distinct_on?: Maybe<Array<Auth_Refresh_Tokens_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Refresh_Tokens_Order_By>>
where?: Maybe<Auth_Refresh_Tokens_Bool_Exp>
}
/** aggregated selection of "auth.accounts" */
export type Auth_Accounts_Aggregate = {
__typename?: 'auth_accounts_aggregate'
aggregate?: Maybe<Auth_Accounts_Aggregate_Fields>
nodes: Array<Auth_Accounts>
}
/** aggregate fields of "auth.accounts" */
export type Auth_Accounts_Aggregate_Fields = {
__typename?: 'auth_accounts_aggregate_fields'
count: Scalars['Int']
max?: Maybe<Auth_Accounts_Max_Fields>
min?: Maybe<Auth_Accounts_Min_Fields>
}
/** aggregate fields of "auth.accounts" */
export type Auth_Accounts_Aggregate_FieldsCountArgs = {
columns?: Maybe<Array<Auth_Accounts_Select_Column>>
distinct?: Maybe<Scalars['Boolean']>
}
/** aggregate max on columns */
export type Auth_Accounts_Max_Fields = {
__typename?: 'auth_accounts_max_fields'
created_at?: Maybe<Scalars['timestamptz']>
default_role?: Maybe<Scalars['String']>
email?: Maybe<Scalars['citext']>
id?: Maybe<Scalars['uuid']>
new_email?: Maybe<Scalars['citext']>
otp_secret?: Maybe<Scalars['String']>
password_hash?: Maybe<Scalars['String']>
ticket?: Maybe<Scalars['uuid']>
ticket_expires_at?: Maybe<Scalars['timestamptz']>
updated_at?: Maybe<Scalars['timestamptz']>
user_id?: Maybe<Scalars['uuid']>
}
/** aggregate min on columns */
export type Auth_Accounts_Min_Fields = {
__typename?: 'auth_accounts_min_fields'
created_at?: Maybe<Scalars['timestamptz']>
default_role?: Maybe<Scalars['String']>
email?: Maybe<Scalars['citext']>
id?: Maybe<Scalars['uuid']>
new_email?: Maybe<Scalars['citext']>
otp_secret?: Maybe<Scalars['String']>
password_hash?: Maybe<Scalars['String']>
ticket?: Maybe<Scalars['uuid']>
ticket_expires_at?: Maybe<Scalars['timestamptz']>
updated_at?: Maybe<Scalars['timestamptz']>
user_id?: Maybe<Scalars['uuid']>
}
/** response of any mutation on the table "auth.accounts" */
export type Auth_Accounts_Mutation_Response = {
__typename?: 'auth_accounts_mutation_response'
/** number of rows affected by the mutation */
affected_rows: Scalars['Int']
/** data from the rows affected by the mutation */
returning: Array<Auth_Accounts>
}
/** columns and relationships of "auth.providers" */
export type Auth_Providers = {
__typename?: 'auth_providers'
/** An array relationship */
account_providers: Array<Auth_Account_Providers>
/** An aggregate relationship */
account_providers_aggregate: Auth_Account_Providers_Aggregate
provider: Scalars['String']
}
/** columns and relationships of "auth.providers" */
export type Auth_ProvidersAccount_ProvidersArgs = {
distinct_on?: Maybe<Array<Auth_Account_Providers_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Account_Providers_Order_By>>
where?: Maybe<Auth_Account_Providers_Bool_Exp>
}
/** columns and relationships of "auth.providers" */
export type Auth_ProvidersAccount_Providers_AggregateArgs = {
distinct_on?: Maybe<Array<Auth_Account_Providers_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Account_Providers_Order_By>>
where?: Maybe<Auth_Account_Providers_Bool_Exp>
}
/** aggregated selection of "auth.providers" */
export type Auth_Providers_Aggregate = {
__typename?: 'auth_providers_aggregate'
aggregate?: Maybe<Auth_Providers_Aggregate_Fields>
nodes: Array<Auth_Providers>
}
/** aggregate fields of "auth.providers" */
export type Auth_Providers_Aggregate_Fields = {
__typename?: 'auth_providers_aggregate_fields'
count: Scalars['Int']
max?: Maybe<Auth_Providers_Max_Fields>
min?: Maybe<Auth_Providers_Min_Fields>
}
/** aggregate fields of "auth.providers" */
export type Auth_Providers_Aggregate_FieldsCountArgs = {
columns?: Maybe<Array<Auth_Providers_Select_Column>>
distinct?: Maybe<Scalars['Boolean']>
}
/** aggregate max on columns */
export type Auth_Providers_Max_Fields = {
__typename?: 'auth_providers_max_fields'
provider?: Maybe<Scalars['String']>
}
/** aggregate min on columns */
export type Auth_Providers_Min_Fields = {
__typename?: 'auth_providers_min_fields'
provider?: Maybe<Scalars['String']>
}
/** response of any mutation on the table "auth.providers" */
export type Auth_Providers_Mutation_Response = {
__typename?: 'auth_providers_mutation_response'
/** number of rows affected by the mutation */
affected_rows: Scalars['Int']
/** data from the rows affected by the mutation */
returning: Array<Auth_Providers>
}
/** columns and relationships of "auth.refresh_tokens" */
export type Auth_Refresh_Tokens = {
__typename?: 'auth_refresh_tokens'
/** An object relationship */
account: Auth_Accounts
account_id: Scalars['uuid']
created_at: Scalars['timestamptz']
expires_at: Scalars['timestamptz']
refresh_token: Scalars['uuid']
}
/** aggregated selection of "auth.refresh_tokens" */
export type Auth_Refresh_Tokens_Aggregate = {
__typename?: 'auth_refresh_tokens_aggregate'
aggregate?: Maybe<Auth_Refresh_Tokens_Aggregate_Fields>
nodes: Array<Auth_Refresh_Tokens>
}
/** aggregate fields of "auth.refresh_tokens" */
export type Auth_Refresh_Tokens_Aggregate_Fields = {
__typename?: 'auth_refresh_tokens_aggregate_fields'
count: Scalars['Int']
max?: Maybe<Auth_Refresh_Tokens_Max_Fields>
min?: Maybe<Auth_Refresh_Tokens_Min_Fields>
}
/** aggregate fields of "auth.refresh_tokens" */
export type Auth_Refresh_Tokens_Aggregate_FieldsCountArgs = {
columns?: Maybe<Array<Auth_Refresh_Tokens_Select_Column>>
distinct?: Maybe<Scalars['Boolean']>
}
/** aggregate max on columns */
export type Auth_Refresh_Tokens_Max_Fields = {
__typename?: 'auth_refresh_tokens_max_fields'
account_id?: Maybe<Scalars['uuid']>
created_at?: Maybe<Scalars['timestamptz']>
expires_at?: Maybe<Scalars['timestamptz']>
refresh_token?: Maybe<Scalars['uuid']>
}
/** aggregate min on columns */
export type Auth_Refresh_Tokens_Min_Fields = {
__typename?: 'auth_refresh_tokens_min_fields'
account_id?: Maybe<Scalars['uuid']>
created_at?: Maybe<Scalars['timestamptz']>
expires_at?: Maybe<Scalars['timestamptz']>
refresh_token?: Maybe<Scalars['uuid']>
}
/** response of any mutation on the table "auth.refresh_tokens" */
export type Auth_Refresh_Tokens_Mutation_Response = {
__typename?: 'auth_refresh_tokens_mutation_response'
/** number of rows affected by the mutation */
affected_rows: Scalars['Int']
/** data from the rows affected by the mutation */
returning: Array<Auth_Refresh_Tokens>
}
/** columns and relationships of "auth.roles" */
export type Auth_Roles = {
__typename?: 'auth_roles'
/** An array relationship */
account_roles: Array<Auth_Account_Roles>
/** An aggregate relationship */
account_roles_aggregate: Auth_Account_Roles_Aggregate
/** An array relationship */
accounts: Array<Auth_Accounts>
/** An aggregate relationship */
accounts_aggregate: Auth_Accounts_Aggregate
role: Scalars['String']
}
/** columns and relationships of "auth.roles" */
export type Auth_RolesAccount_RolesArgs = {
distinct_on?: Maybe<Array<Auth_Account_Roles_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Account_Roles_Order_By>>
where?: Maybe<Auth_Account_Roles_Bool_Exp>
}
/** columns and relationships of "auth.roles" */
export type Auth_RolesAccount_Roles_AggregateArgs = {
distinct_on?: Maybe<Array<Auth_Account_Roles_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Account_Roles_Order_By>>
where?: Maybe<Auth_Account_Roles_Bool_Exp>
}
/** columns and relationships of "auth.roles" */
export type Auth_RolesAccountsArgs = {
distinct_on?: Maybe<Array<Auth_Accounts_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Accounts_Order_By>>
where?: Maybe<Auth_Accounts_Bool_Exp>
}
/** columns and relationships of "auth.roles" */
export type Auth_RolesAccounts_AggregateArgs = {
distinct_on?: Maybe<Array<Auth_Accounts_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Accounts_Order_By>>
where?: Maybe<Auth_Accounts_Bool_Exp>
}
/** aggregated selection of "auth.roles" */
export type Auth_Roles_Aggregate = {
__typename?: 'auth_roles_aggregate'
aggregate?: Maybe<Auth_Roles_Aggregate_Fields>
nodes: Array<Auth_Roles>
}
/** aggregate fields of "auth.roles" */
export type Auth_Roles_Aggregate_Fields = {
__typename?: 'auth_roles_aggregate_fields'
count: Scalars['Int']
max?: Maybe<Auth_Roles_Max_Fields>
min?: Maybe<Auth_Roles_Min_Fields>
}
/** aggregate fields of "auth.roles" */
export type Auth_Roles_Aggregate_FieldsCountArgs = {
columns?: Maybe<Array<Auth_Roles_Select_Column>>
distinct?: Maybe<Scalars['Boolean']>
}
/** aggregate max on columns */
export type Auth_Roles_Max_Fields = {
__typename?: 'auth_roles_max_fields'
role?: Maybe<Scalars['String']>
}
/** aggregate min on columns */
export type Auth_Roles_Min_Fields = {
__typename?: 'auth_roles_min_fields'
role?: Maybe<Scalars['String']>
}
/** response of any mutation on the table "auth.roles" */
export type Auth_Roles_Mutation_Response = {
__typename?: 'auth_roles_mutation_response'
/** number of rows affected by the mutation */
affected_rows: Scalars['Int']
/** data from the rows affected by the mutation */
returning: Array<Auth_Roles>
}
/** mutation root */
export type Mutation_Root = {
__typename?: 'mutation_root'
/** delete data from the table: "auth.account_providers" */
delete_auth_account_providers?: Maybe<Auth_Account_Providers_Mutation_Response>
/** delete single row from the table: "auth.account_providers" */
delete_auth_account_providers_by_pk?: Maybe<Auth_Account_Providers>
/** delete data from the table: "auth.account_roles" */
delete_auth_account_roles?: Maybe<Auth_Account_Roles_Mutation_Response>
/** delete single row from the table: "auth.account_roles" */
delete_auth_account_roles_by_pk?: Maybe<Auth_Account_Roles>
/** delete data from the table: "auth.accounts" */
delete_auth_accounts?: Maybe<Auth_Accounts_Mutation_Response>
/** delete single row from the table: "auth.accounts" */
delete_auth_accounts_by_pk?: Maybe<Auth_Accounts>
/** delete data from the table: "auth.providers" */
delete_auth_providers?: Maybe<Auth_Providers_Mutation_Response>
/** delete single row from the table: "auth.providers" */
delete_auth_providers_by_pk?: Maybe<Auth_Providers>
/** delete data from the table: "auth.refresh_tokens" */
delete_auth_refresh_tokens?: Maybe<Auth_Refresh_Tokens_Mutation_Response>
/** delete single row from the table: "auth.refresh_tokens" */
delete_auth_refresh_tokens_by_pk?: Maybe<Auth_Refresh_Tokens>
/** delete data from the table: "auth.roles" */
delete_auth_roles?: Maybe<Auth_Roles_Mutation_Response>
/** delete single row from the table: "auth.roles" */
delete_auth_roles_by_pk?: Maybe<Auth_Roles>
/** delete data from the table: "users" */
delete_users?: Maybe<Users_Mutation_Response>
/** delete single row from the table: "users" */
delete_users_by_pk?: Maybe<Users>
/** insert data into the table: "auth.account_providers" */
insert_auth_account_providers?: Maybe<Auth_Account_Providers_Mutation_Response>
/** insert a single row into the table: "auth.account_providers" */
insert_auth_account_providers_one?: Maybe<Auth_Account_Providers>
/** insert data into the table: "auth.account_roles" */
insert_auth_account_roles?: Maybe<Auth_Account_Roles_Mutation_Response>
/** insert a single row into the table: "auth.account_roles" */
insert_auth_account_roles_one?: Maybe<Auth_Account_Roles>
/** insert data into the table: "auth.accounts" */
insert_auth_accounts?: Maybe<Auth_Accounts_Mutation_Response>
/** insert a single row into the table: "auth.accounts" */
insert_auth_accounts_one?: Maybe<Auth_Accounts>
/** insert data into the table: "auth.providers" */
insert_auth_providers?: Maybe<Auth_Providers_Mutation_Response>
/** insert a single row into the table: "auth.providers" */
insert_auth_providers_one?: Maybe<Auth_Providers>
/** insert data into the table: "auth.refresh_tokens" */
insert_auth_refresh_tokens?: Maybe<Auth_Refresh_Tokens_Mutation_Response>
/** insert a single row into the table: "auth.refresh_tokens" */
insert_auth_refresh_tokens_one?: Maybe<Auth_Refresh_Tokens>
/** insert data into the table: "auth.roles" */
insert_auth_roles?: Maybe<Auth_Roles_Mutation_Response>
/** insert a single row into the table: "auth.roles" */
insert_auth_roles_one?: Maybe<Auth_Roles>
/** insert data into the table: "users" */
insert_users?: Maybe<Users_Mutation_Response>
/** insert a single row into the table: "users" */
insert_users_one?: Maybe<Users>
/** update data of the table: "auth.account_providers" */
update_auth_account_providers?: Maybe<Auth_Account_Providers_Mutation_Response>
/** update single row of the table: "auth.account_providers" */
update_auth_account_providers_by_pk?: Maybe<Auth_Account_Providers>
/** update data of the table: "auth.account_roles" */
update_auth_account_roles?: Maybe<Auth_Account_Roles_Mutation_Response>
/** update single row of the table: "auth.account_roles" */
update_auth_account_roles_by_pk?: Maybe<Auth_Account_Roles>
/** update data of the table: "auth.accounts" */
update_auth_accounts?: Maybe<Auth_Accounts_Mutation_Response>
/** update single row of the table: "auth.accounts" */
update_auth_accounts_by_pk?: Maybe<Auth_Accounts>
/** update data of the table: "auth.providers" */
update_auth_providers?: Maybe<Auth_Providers_Mutation_Response>
/** update single row of the table: "auth.providers" */
update_auth_providers_by_pk?: Maybe<Auth_Providers>
/** update data of the table: "auth.refresh_tokens" */
update_auth_refresh_tokens?: Maybe<Auth_Refresh_Tokens_Mutation_Response>
/** update single row of the table: "auth.refresh_tokens" */
update_auth_refresh_tokens_by_pk?: Maybe<Auth_Refresh_Tokens>
/** update data of the table: "auth.roles" */
update_auth_roles?: Maybe<Auth_Roles_Mutation_Response>
/** update single row of the table: "auth.roles" */
update_auth_roles_by_pk?: Maybe<Auth_Roles>
/** update data of the table: "users" */
update_users?: Maybe<Users_Mutation_Response>
/** update single row of the table: "users" */
update_users_by_pk?: Maybe<Users>
}
/** mutation root */
export type Mutation_RootDelete_Auth_Account_ProvidersArgs = {
where: Auth_Account_Providers_Bool_Exp
}
/** mutation root */
export type Mutation_RootDelete_Auth_Account_Providers_By_PkArgs = {
id: Scalars['uuid']
}
/** mutation root */
export type Mutation_RootDelete_Auth_Account_RolesArgs = {
where: Auth_Account_Roles_Bool_Exp
}
/** mutation root */
export type Mutation_RootDelete_Auth_Account_Roles_By_PkArgs = {
id: Scalars['uuid']
}
/** mutation root */
export type Mutation_RootDelete_Auth_AccountsArgs = {
where: Auth_Accounts_Bool_Exp
}
/** mutation root */
export type Mutation_RootDelete_Auth_Accounts_By_PkArgs = {
id: Scalars['uuid']
}
/** mutation root */
export type Mutation_RootDelete_Auth_ProvidersArgs = {
where: Auth_Providers_Bool_Exp
}
/** mutation root */
export type Mutation_RootDelete_Auth_Providers_By_PkArgs = {
provider: Scalars['String']
}
/** mutation root */
export type Mutation_RootDelete_Auth_Refresh_TokensArgs = {
where: Auth_Refresh_Tokens_Bool_Exp
}
/** mutation root */
export type Mutation_RootDelete_Auth_Refresh_Tokens_By_PkArgs = {
refresh_token: Scalars['uuid']
}
/** mutation root */
export type Mutation_RootDelete_Auth_RolesArgs = {
where: Auth_Roles_Bool_Exp
}
/** mutation root */
export type Mutation_RootDelete_Auth_Roles_By_PkArgs = {
role: Scalars['String']
}
/** mutation root */
export type Mutation_RootDelete_UsersArgs = {
where: Users_Bool_Exp
}
/** mutation root */
export type Mutation_RootDelete_Users_By_PkArgs = {
id: Scalars['uuid']
}
/** mutation root */
export type Mutation_RootInsert_Auth_Account_ProvidersArgs = {
objects: Array<Auth_Account_Providers_Insert_Input>
on_conflict?: Maybe<Auth_Account_Providers_On_Conflict>
}
/** mutation root */
export type Mutation_RootInsert_Auth_Account_Providers_OneArgs = {
object: Auth_Account_Providers_Insert_Input
on_conflict?: Maybe<Auth_Account_Providers_On_Conflict>
}
/** mutation root */
export type Mutation_RootInsert_Auth_Account_RolesArgs = {
objects: Array<Auth_Account_Roles_Insert_Input>
on_conflict?: Maybe<Auth_Account_Roles_On_Conflict>
}
/** mutation root */
export type Mutation_RootInsert_Auth_Account_Roles_OneArgs = {
object: Auth_Account_Roles_Insert_Input
on_conflict?: Maybe<Auth_Account_Roles_On_Conflict>
}
/** mutation root */
export type Mutation_RootInsert_Auth_AccountsArgs = {
objects: Array<Auth_Accounts_Insert_Input>
on_conflict?: Maybe<Auth_Accounts_On_Conflict>
}
/** mutation root */
export type Mutation_RootInsert_Auth_Accounts_OneArgs = {
object: Auth_Accounts_Insert_Input
on_conflict?: Maybe<Auth_Accounts_On_Conflict>
}
/** mutation root */
export type Mutation_RootInsert_Auth_ProvidersArgs = {
objects: Array<Auth_Providers_Insert_Input>
on_conflict?: Maybe<Auth_Providers_On_Conflict>
}
/** mutation root */
export type Mutation_RootInsert_Auth_Providers_OneArgs = {
object: Auth_Providers_Insert_Input
on_conflict?: Maybe<Auth_Providers_On_Conflict>
}
/** mutation root */
export type Mutation_RootInsert_Auth_Refresh_TokensArgs = {
objects: Array<Auth_Refresh_Tokens_Insert_Input>
on_conflict?: Maybe<Auth_Refresh_Tokens_On_Conflict>
}
/** mutation root */
export type Mutation_RootInsert_Auth_Refresh_Tokens_OneArgs = {
object: Auth_Refresh_Tokens_Insert_Input
on_conflict?: Maybe<Auth_Refresh_Tokens_On_Conflict>
}
/** mutation root */
export type Mutation_RootInsert_Auth_RolesArgs = {
objects: Array<Auth_Roles_Insert_Input>
on_conflict?: Maybe<Auth_Roles_On_Conflict>
}
/** mutation root */
export type Mutation_RootInsert_Auth_Roles_OneArgs = {
object: Auth_Roles_Insert_Input
on_conflict?: Maybe<Auth_Roles_On_Conflict>
}
/** mutation root */
export type Mutation_RootInsert_UsersArgs = {
objects: Array<Users_Insert_Input>
on_conflict?: Maybe<Users_On_Conflict>
}
/** mutation root */
export type Mutation_RootInsert_Users_OneArgs = {
object: Users_Insert_Input
on_conflict?: Maybe<Users_On_Conflict>
}
/** mutation root */
export type Mutation_RootUpdate_Auth_Account_ProvidersArgs = {
_set?: Maybe<Auth_Account_Providers_Set_Input>
where: Auth_Account_Providers_Bool_Exp
}
/** mutation root */
export type Mutation_RootUpdate_Auth_Account_Providers_By_PkArgs = {
_set?: Maybe<Auth_Account_Providers_Set_Input>
pk_columns: Auth_Account_Providers_Pk_Columns_Input
}
/** mutation root */
export type Mutation_RootUpdate_Auth_Account_RolesArgs = {
_set?: Maybe<Auth_Account_Roles_Set_Input>
where: Auth_Account_Roles_Bool_Exp
}
/** mutation root */
export type Mutation_RootUpdate_Auth_Account_Roles_By_PkArgs = {
_set?: Maybe<Auth_Account_Roles_Set_Input>
pk_columns: Auth_Account_Roles_Pk_Columns_Input
}
/** mutation root */
export type Mutation_RootUpdate_Auth_AccountsArgs = {
_append?: Maybe<Auth_Accounts_Append_Input>
_delete_at_path?: Maybe<Auth_Accounts_Delete_At_Path_Input>
_delete_elem?: Maybe<Auth_Accounts_Delete_Elem_Input>
_delete_key?: Maybe<Auth_Accounts_Delete_Key_Input>
_prepend?: Maybe<Auth_Accounts_Prepend_Input>
_set?: Maybe<Auth_Accounts_Set_Input>
where: Auth_Accounts_Bool_Exp
}
/** mutation root */
export type Mutation_RootUpdate_Auth_Accounts_By_PkArgs = {
_append?: Maybe<Auth_Accounts_Append_Input>
_delete_at_path?: Maybe<Auth_Accounts_Delete_At_Path_Input>
_delete_elem?: Maybe<Auth_Accounts_Delete_Elem_Input>
_delete_key?: Maybe<Auth_Accounts_Delete_Key_Input>
_prepend?: Maybe<Auth_Accounts_Prepend_Input>
_set?: Maybe<Auth_Accounts_Set_Input>
pk_columns: Auth_Accounts_Pk_Columns_Input
}
/** mutation root */
export type Mutation_RootUpdate_Auth_ProvidersArgs = {
_set?: Maybe<Auth_Providers_Set_Input>
where: Auth_Providers_Bool_Exp
}
/** mutation root */
export type Mutation_RootUpdate_Auth_Providers_By_PkArgs = {
_set?: Maybe<Auth_Providers_Set_Input>
pk_columns: Auth_Providers_Pk_Columns_Input
}
/** mutation root */
export type Mutation_RootUpdate_Auth_Refresh_TokensArgs = {
_set?: Maybe<Auth_Refresh_Tokens_Set_Input>
where: Auth_Refresh_Tokens_Bool_Exp
}
/** mutation root */
export type Mutation_RootUpdate_Auth_Refresh_Tokens_By_PkArgs = {
_set?: Maybe<Auth_Refresh_Tokens_Set_Input>
pk_columns: Auth_Refresh_Tokens_Pk_Columns_Input
}
/** mutation root */
export type Mutation_RootUpdate_Auth_RolesArgs = {
_set?: Maybe<Auth_Roles_Set_Input>
where: Auth_Roles_Bool_Exp
}
/** mutation root */
export type Mutation_RootUpdate_Auth_Roles_By_PkArgs = {
_set?: Maybe<Auth_Roles_Set_Input>
pk_columns: Auth_Roles_Pk_Columns_Input
}
/** mutation root */
export type Mutation_RootUpdate_UsersArgs = {
_set?: Maybe<Users_Set_Input>
where: Users_Bool_Exp
}
/** mutation root */
export type Mutation_RootUpdate_Users_By_PkArgs = {
_set?: Maybe<Users_Set_Input>
pk_columns: Users_Pk_Columns_Input
}
export type Query_Root = {
__typename?: 'query_root'
/** fetch data from the table: "auth.account_providers" */
auth_account_providers: Array<Auth_Account_Providers>
/** fetch aggregated fields from the table: "auth.account_providers" */
auth_account_providers_aggregate: Auth_Account_Providers_Aggregate
/** fetch data from the table: "auth.account_providers" using primary key columns */
auth_account_providers_by_pk?: Maybe<Auth_Account_Providers>
/** fetch data from the table: "auth.account_roles" */
auth_account_roles: Array<Auth_Account_Roles>
/** fetch aggregated fields from the table: "auth.account_roles" */
auth_account_roles_aggregate: Auth_Account_Roles_Aggregate
/** fetch data from the table: "auth.account_roles" using primary key columns */
auth_account_roles_by_pk?: Maybe<Auth_Account_Roles>
/** fetch data from the table: "auth.accounts" */
auth_accounts: Array<Auth_Accounts>
/** fetch aggregated fields from the table: "auth.accounts" */
auth_accounts_aggregate: Auth_Accounts_Aggregate
/** fetch data from the table: "auth.accounts" using primary key columns */
auth_accounts_by_pk?: Maybe<Auth_Accounts>
/** fetch data from the table: "auth.providers" */
auth_providers: Array<Auth_Providers>
/** fetch aggregated fields from the table: "auth.providers" */
auth_providers_aggregate: Auth_Providers_Aggregate
/** fetch data from the table: "auth.providers" using primary key columns */
auth_providers_by_pk?: Maybe<Auth_Providers>
/** fetch data from the table: "auth.refresh_tokens" */
auth_refresh_tokens: Array<Auth_Refresh_Tokens>
/** fetch aggregated fields from the table: "auth.refresh_tokens" */
auth_refresh_tokens_aggregate: Auth_Refresh_Tokens_Aggregate
/** fetch data from the table: "auth.refresh_tokens" using primary key columns */
auth_refresh_tokens_by_pk?: Maybe<Auth_Refresh_Tokens>
/** fetch data from the table: "auth.roles" */
auth_roles: Array<Auth_Roles>
/** fetch aggregated fields from the table: "auth.roles" */
auth_roles_aggregate: Auth_Roles_Aggregate
/** fetch data from the table: "auth.roles" using primary key columns */
auth_roles_by_pk?: Maybe<Auth_Roles>
/** fetch data from the table: "users" */
users: Array<Users>
/** fetch aggregated fields from the table: "users" */
users_aggregate: Users_Aggregate
/** fetch data from the table: "users" using primary key columns */
users_by_pk?: Maybe<Users>
}
export type Query_RootAuth_Account_ProvidersArgs = {
distinct_on?: Maybe<Array<Auth_Account_Providers_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Account_Providers_Order_By>>
where?: Maybe<Auth_Account_Providers_Bool_Exp>
}
export type Query_RootAuth_Account_Providers_AggregateArgs = {
distinct_on?: Maybe<Array<Auth_Account_Providers_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Account_Providers_Order_By>>
where?: Maybe<Auth_Account_Providers_Bool_Exp>
}
export type Query_RootAuth_Account_Providers_By_PkArgs = {
id: Scalars['uuid']
}
export type Query_RootAuth_Account_RolesArgs = {
distinct_on?: Maybe<Array<Auth_Account_Roles_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Account_Roles_Order_By>>
where?: Maybe<Auth_Account_Roles_Bool_Exp>
}
export type Query_RootAuth_Account_Roles_AggregateArgs = {
distinct_on?: Maybe<Array<Auth_Account_Roles_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Account_Roles_Order_By>>
where?: Maybe<Auth_Account_Roles_Bool_Exp>
}
export type Query_RootAuth_Account_Roles_By_PkArgs = {
id: Scalars['uuid']
}
export type Query_RootAuth_AccountsArgs = {
distinct_on?: Maybe<Array<Auth_Accounts_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Accounts_Order_By>>
where?: Maybe<Auth_Accounts_Bool_Exp>
}
export type Query_RootAuth_Accounts_AggregateArgs = {
distinct_on?: Maybe<Array<Auth_Accounts_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Accounts_Order_By>>
where?: Maybe<Auth_Accounts_Bool_Exp>
}
export type Query_RootAuth_Accounts_By_PkArgs = {
id: Scalars['uuid']
}
export type Query_RootAuth_ProvidersArgs = {
distinct_on?: Maybe<Array<Auth_Providers_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Providers_Order_By>>
where?: Maybe<Auth_Providers_Bool_Exp>
}
export type Query_RootAuth_Providers_AggregateArgs = {
distinct_on?: Maybe<Array<Auth_Providers_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Providers_Order_By>>
where?: Maybe<Auth_Providers_Bool_Exp>
}
export type Query_RootAuth_Providers_By_PkArgs = {
provider: Scalars['String']
}
export type Query_RootAuth_Refresh_TokensArgs = {
distinct_on?: Maybe<Array<Auth_Refresh_Tokens_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Refresh_Tokens_Order_By>>
where?: Maybe<Auth_Refresh_Tokens_Bool_Exp>
}
export type Query_RootAuth_Refresh_Tokens_AggregateArgs = {
distinct_on?: Maybe<Array<Auth_Refresh_Tokens_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Refresh_Tokens_Order_By>>
where?: Maybe<Auth_Refresh_Tokens_Bool_Exp>
}
export type Query_RootAuth_Refresh_Tokens_By_PkArgs = {
refresh_token: Scalars['uuid']
}
export type Query_RootAuth_RolesArgs = {
distinct_on?: Maybe<Array<Auth_Roles_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Roles_Order_By>>
where?: Maybe<Auth_Roles_Bool_Exp>
}
export type Query_RootAuth_Roles_AggregateArgs = {
distinct_on?: Maybe<Array<Auth_Roles_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Roles_Order_By>>
where?: Maybe<Auth_Roles_Bool_Exp>
}
export type Query_RootAuth_Roles_By_PkArgs = {
role: Scalars['String']
}
export type Query_RootUsersArgs = {
distinct_on?: Maybe<Array<Users_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Users_Order_By>>
where?: Maybe<Users_Bool_Exp>
}
export type Query_RootUsers_AggregateArgs = {
distinct_on?: Maybe<Array<Users_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Users_Order_By>>
where?: Maybe<Users_Bool_Exp>
}
export type Query_RootUsers_By_PkArgs = {
id: Scalars['uuid']
}
export type Subscription_Root = {
__typename?: 'subscription_root'
/** fetch data from the table: "auth.account_providers" */
auth_account_providers: Array<Auth_Account_Providers>
/** fetch aggregated fields from the table: "auth.account_providers" */
auth_account_providers_aggregate: Auth_Account_Providers_Aggregate
/** fetch data from the table: "auth.account_providers" using primary key columns */
auth_account_providers_by_pk?: Maybe<Auth_Account_Providers>
/** fetch data from the table: "auth.account_roles" */
auth_account_roles: Array<Auth_Account_Roles>
/** fetch aggregated fields from the table: "auth.account_roles" */
auth_account_roles_aggregate: Auth_Account_Roles_Aggregate
/** fetch data from the table: "auth.account_roles" using primary key columns */
auth_account_roles_by_pk?: Maybe<Auth_Account_Roles>
/** fetch data from the table: "auth.accounts" */
auth_accounts: Array<Auth_Accounts>
/** fetch aggregated fields from the table: "auth.accounts" */
auth_accounts_aggregate: Auth_Accounts_Aggregate
/** fetch data from the table: "auth.accounts" using primary key columns */
auth_accounts_by_pk?: Maybe<Auth_Accounts>
/** fetch data from the table: "auth.providers" */
auth_providers: Array<Auth_Providers>
/** fetch aggregated fields from the table: "auth.providers" */
auth_providers_aggregate: Auth_Providers_Aggregate
/** fetch data from the table: "auth.providers" using primary key columns */
auth_providers_by_pk?: Maybe<Auth_Providers>
/** fetch data from the table: "auth.refresh_tokens" */
auth_refresh_tokens: Array<Auth_Refresh_Tokens>
/** fetch aggregated fields from the table: "auth.refresh_tokens" */
auth_refresh_tokens_aggregate: Auth_Refresh_Tokens_Aggregate
/** fetch data from the table: "auth.refresh_tokens" using primary key columns */
auth_refresh_tokens_by_pk?: Maybe<Auth_Refresh_Tokens>
/** fetch data from the table: "auth.roles" */
auth_roles: Array<Auth_Roles>
/** fetch aggregated fields from the table: "auth.roles" */
auth_roles_aggregate: Auth_Roles_Aggregate
/** fetch data from the table: "auth.roles" using primary key columns */
auth_roles_by_pk?: Maybe<Auth_Roles>
/** fetch data from the table: "users" */
users: Array<Users>
/** fetch aggregated fields from the table: "users" */
users_aggregate: Users_Aggregate
/** fetch data from the table: "users" using primary key columns */
users_by_pk?: Maybe<Users>
}
export type Subscription_RootAuth_Account_ProvidersArgs = {
distinct_on?: Maybe<Array<Auth_Account_Providers_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Account_Providers_Order_By>>
where?: Maybe<Auth_Account_Providers_Bool_Exp>
}
export type Subscription_RootAuth_Account_Providers_AggregateArgs = {
distinct_on?: Maybe<Array<Auth_Account_Providers_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Account_Providers_Order_By>>
where?: Maybe<Auth_Account_Providers_Bool_Exp>
}
export type Subscription_RootAuth_Account_Providers_By_PkArgs = {
id: Scalars['uuid']
}
export type Subscription_RootAuth_Account_RolesArgs = {
distinct_on?: Maybe<Array<Auth_Account_Roles_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Account_Roles_Order_By>>
where?: Maybe<Auth_Account_Roles_Bool_Exp>
}
export type Subscription_RootAuth_Account_Roles_AggregateArgs = {
distinct_on?: Maybe<Array<Auth_Account_Roles_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Account_Roles_Order_By>>
where?: Maybe<Auth_Account_Roles_Bool_Exp>
}
export type Subscription_RootAuth_Account_Roles_By_PkArgs = {
id: Scalars['uuid']
}
export type Subscription_RootAuth_AccountsArgs = {
distinct_on?: Maybe<Array<Auth_Accounts_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Accounts_Order_By>>
where?: Maybe<Auth_Accounts_Bool_Exp>
}
export type Subscription_RootAuth_Accounts_AggregateArgs = {
distinct_on?: Maybe<Array<Auth_Accounts_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Accounts_Order_By>>
where?: Maybe<Auth_Accounts_Bool_Exp>
}
export type Subscription_RootAuth_Accounts_By_PkArgs = {
id: Scalars['uuid']
}
export type Subscription_RootAuth_ProvidersArgs = {
distinct_on?: Maybe<Array<Auth_Providers_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Providers_Order_By>>
where?: Maybe<Auth_Providers_Bool_Exp>
}
export type Subscription_RootAuth_Providers_AggregateArgs = {
distinct_on?: Maybe<Array<Auth_Providers_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Providers_Order_By>>
where?: Maybe<Auth_Providers_Bool_Exp>
}
export type Subscription_RootAuth_Providers_By_PkArgs = {
provider: Scalars['String']
}
export type Subscription_RootAuth_Refresh_TokensArgs = {
distinct_on?: Maybe<Array<Auth_Refresh_Tokens_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Refresh_Tokens_Order_By>>
where?: Maybe<Auth_Refresh_Tokens_Bool_Exp>
}
export type Subscription_RootAuth_Refresh_Tokens_AggregateArgs = {
distinct_on?: Maybe<Array<Auth_Refresh_Tokens_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Refresh_Tokens_Order_By>>
where?: Maybe<Auth_Refresh_Tokens_Bool_Exp>
}
export type Subscription_RootAuth_Refresh_Tokens_By_PkArgs = {
refresh_token: Scalars['uuid']
}
export type Subscription_RootAuth_RolesArgs = {
distinct_on?: Maybe<Array<Auth_Roles_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Roles_Order_By>>
where?: Maybe<Auth_Roles_Bool_Exp>
}
export type Subscription_RootAuth_Roles_AggregateArgs = {
distinct_on?: Maybe<Array<Auth_Roles_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Auth_Roles_Order_By>>
where?: Maybe<Auth_Roles_Bool_Exp>
}
export type Subscription_RootAuth_Roles_By_PkArgs = {
role: Scalars['String']
}
export type Subscription_RootUsersArgs = {
distinct_on?: Maybe<Array<Users_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Users_Order_By>>
where?: Maybe<Users_Bool_Exp>
}
export type Subscription_RootUsers_AggregateArgs = {
distinct_on?: Maybe<Array<Users_Select_Column>>
limit?: Maybe<Scalars['Int']>
offset?: Maybe<Scalars['Int']>
order_by?: Maybe<Array<Users_Order_By>>
where?: Maybe<Users_Bool_Exp>
}
export type Subscription_RootUsers_By_PkArgs = {
id: Scalars['uuid']
}
/** columns and relationships of "users" */
export type Users = {
__typename?: 'users'
/** An object relationship */
account?: Maybe<Auth_Accounts>
avatar_url?: Maybe<Scalars['String']>
created_at: Scalars['timestamptz']
display_name?: Maybe<Scalars['String']>
id: Scalars['uuid']
updated_at: Scalars['timestamptz']
}
/** aggregated selection of "users" */
export type Users_Aggregate = {
__typename?: 'users_aggregate'
aggregate?: Maybe<Users_Aggregate_Fields>
nodes: Array<Users>
}
/** aggregate fields of "users" */
export type Users_Aggregate_Fields = {
__typename?: 'users_aggregate_fields'
count: Scalars['Int']
max?: Maybe<Users_Max_Fields>
min?: Maybe<Users_Min_Fields>
}
/** aggregate fields of "users" */
export type Users_Aggregate_FieldsCountArgs = {
columns?: Maybe<Array<Users_Select_Column>>
distinct?: Maybe<Scalars['Boolean']>
}
/** aggregate max on columns */
export type Users_Max_Fields = {
__typename?: 'users_max_fields'
avatar_url?: Maybe<Scalars['String']>
created_at?: Maybe<Scalars['timestamptz']>
display_name?: Maybe<Scalars['String']>
id?: Maybe<Scalars['uuid']>
updated_at?: Maybe<Scalars['timestamptz']>
}
/** aggregate min on columns */
export type Users_Min_Fields = {
__typename?: 'users_min_fields'
avatar_url?: Maybe<Scalars['String']>
created_at?: Maybe<Scalars['timestamptz']>
display_name?: Maybe<Scalars['String']>
id?: Maybe<Scalars['uuid']>
updated_at?: Maybe<Scalars['timestamptz']>
}
/** response of any mutation on the table "users" */
export type Users_Mutation_Response = {
__typename?: 'users_mutation_response'
/** number of rows affected by the mutation */
affected_rows: Scalars['Int']
/** data from the rows affected by the mutation */
returning: Array<Users>
}
/** unique or primary key constraints on table "auth.account_providers" */
export enum Auth_Account_Providers_Constraint {
/** unique or primary key constraint */
AccountProvidersAccountIdAuthProviderKey = 'account_providers_account_id_auth_provider_key',
/** unique or primary key constraint */
AccountProvidersAuthProviderAuthProviderUniqueIdKey = 'account_providers_auth_provider_auth_provider_unique_id_key',
/** unique or primary key constraint */
AccountProvidersPkey = 'account_providers_pkey',
}
/** select columns of table "auth.account_providers" */
export enum Auth_Account_Providers_Select_Column {
/** column name */
AccountId = 'account_id',
/** column name */
AuthProvider = 'auth_provider',
/** column name */
AuthProviderUniqueId = 'auth_provider_unique_id',
/** column name */
CreatedAt = 'created_at',
/** column name */
Id = 'id',
/** column name */
UpdatedAt = 'updated_at',
}
/** update columns of table "auth.account_providers" */
export enum Auth_Account_Providers_Update_Column {
/** column name */
AccountId = 'account_id',
/** column name */
AuthProvider = 'auth_provider',
/** column name */
AuthProviderUniqueId = 'auth_provider_unique_id',
/** column name */
CreatedAt = 'created_at',
/** column name */
Id = 'id',
/** column name */
UpdatedAt = 'updated_at',
}
/** unique or primary key constraints on table "auth.account_roles" */
export enum Auth_Account_Roles_Constraint {
/** unique or primary key constraint */
AccountRolesPkey = 'account_roles_pkey',
/** unique or primary key constraint */
UserRolesAccountIdRoleKey = 'user_roles_account_id_role_key',
}
/** select columns of table "auth.account_roles" */
export enum Auth_Account_Roles_Select_Column {
/** column name */
AccountId = 'account_id',
/** column name */
CreatedAt = 'created_at',
/** column name */
Id = 'id',
/** column name */
Role = 'role',
}
/** update columns of table "auth.account_roles" */
export enum Auth_Account_Roles_Update_Column {
/** column name */
AccountId = 'account_id',
/** column name */
CreatedAt = 'created_at',
/** column name */
Id = 'id',
/** column name */
Role = 'role',
}
/** unique or primary key constraints on table "auth.accounts" */
export enum Auth_Accounts_Constraint {
/** unique or primary key constraint */
AccountsEmailKey = 'accounts_email_key',
/** unique or primary key constraint */
AccountsNewEmailKey = 'accounts_new_email_key',
/** unique or primary key constraint */
AccountsPkey = 'accounts_pkey',
/** unique or primary key constraint */
AccountsUserIdKey = 'accounts_user_id_key',
}
/** select columns of table "auth.accounts" */
export enum Auth_Accounts_Select_Column {
/** column name */
Active = 'active',
/** column name */
CreatedAt = 'created_at',
/** column name */
CustomRegisterData = 'custom_register_data',
/** column name */
DefaultRole = 'default_role',
/** column name */
Email = 'email',
/** column name */
Id = 'id',
/** column name */
IsAnonymous = 'is_anonymous',
/** column name */
MfaEnabled = 'mfa_enabled',
/** column name */
NewEmail = 'new_email',
/** column name */
OtpSecret = 'otp_secret',
/** column name */
PasswordHash = 'password_hash',
/** column name */
Ticket = 'ticket',
/** column name */
TicketExpiresAt = 'ticket_expires_at',
/** column name */
UpdatedAt = 'updated_at',
/** column name */
UserId = 'user_id',
}
/** update columns of table "auth.accounts" */
export enum Auth_Accounts_Update_Column {
/** column name */
Active = 'active',
/** column name */
CreatedAt = 'created_at',
/** column name */
CustomRegisterData = 'custom_register_data',
/** column name */
DefaultRole = 'default_role',
/** column name */
Email = 'email',
/** column name */
Id = 'id',
/** column name */
IsAnonymous = 'is_anonymous',
/** column name */
MfaEnabled = 'mfa_enabled',
/** column name */
NewEmail = 'new_email',
/** column name */
OtpSecret = 'otp_secret',
/** column name */
PasswordHash = 'password_hash',
/** column name */
Ticket = 'ticket',
/** column name */
TicketExpiresAt = 'ticket_expires_at',
/** column name */
UpdatedAt = 'updated_at',
/** column name */
UserId = 'user_id',
}
/** unique or primary key constraints on table "auth.providers" */
export enum Auth_Providers_Constraint {
/** unique or primary key constraint */
ProvidersPkey = 'providers_pkey',
}
/** select columns of table "auth.providers" */
export enum Auth_Providers_Select_Column {
/** column name */
Provider = 'provider',
}
/** update columns of table "auth.providers" */
export enum Auth_Providers_Update_Column {
/** column name */
Provider = 'provider',
}
/** unique or primary key constraints on table "auth.refresh_tokens" */
export enum Auth_Refresh_Tokens_Constraint {
/** unique or primary key constraint */
RefreshTokensPkey = 'refresh_tokens_pkey',
}
/** select columns of table "auth.refresh_tokens" */
export enum Auth_Refresh_Tokens_Select_Column {
/** column name */
AccountId = 'account_id',
/** column name */
CreatedAt = 'created_at',
/** column name */
ExpiresAt = 'expires_at',
/** column name */
RefreshToken = 'refresh_token',
}
/** update columns of table "auth.refresh_tokens" */
export enum Auth_Refresh_Tokens_Update_Column {
/** column name */
AccountId = 'account_id',
/** column name */
CreatedAt = 'created_at',
/** column name */
ExpiresAt = 'expires_at',
/** column name */
RefreshToken = 'refresh_token',
}
/** unique or primary key constraints on table "auth.roles" */
export enum Auth_Roles_Constraint {
/** unique or primary key constraint */
RolesPkey = 'roles_pkey',
}
/** select columns of table "auth.roles" */
export enum Auth_Roles_Select_Column {
/** column name */
Role = 'role',
}
/** update columns of table "auth.roles" */
export enum Auth_Roles_Update_Column {
/** column name */
Role = 'role',
}
/** column ordering options */
export enum Order_By {
/** in ascending order, nulls last */
Asc = 'asc',
/** in ascending order, nulls first */
AscNullsFirst = 'asc_nulls_first',
/** in ascending order, nulls last */
AscNullsLast = 'asc_nulls_last',
/** in descending order, nulls first */
Desc = 'desc',
/** in descending order, nulls first */
DescNullsFirst = 'desc_nulls_first',
/** in descending order, nulls last */
DescNullsLast = 'desc_nulls_last',
}
/** unique or primary key constraints on table "users" */
export enum Users_Constraint {
/** unique or primary key constraint */
UsersPkey = 'users_pkey',
}
/** select columns of table "users" */
export enum Users_Select_Column {
/** column name */
AvatarUrl = 'avatar_url',
/** column name */
CreatedAt = 'created_at',
/** column name */
DisplayName = 'display_name',
/** column name */
Id = 'id',
/** column name */
UpdatedAt = 'updated_at',
}
/** update columns of table "users" */
export enum Users_Update_Column {
/** column name */
AvatarUrl = 'avatar_url',
/** column name */
CreatedAt = 'created_at',
/** column name */
DisplayName = 'display_name',
/** column name */
Id = 'id',
/** column name */
UpdatedAt = 'updated_at',
}
/** Boolean expression to compare columns of type "Boolean". All fields are combined with logical 'AND'. */
export type Boolean_Comparison_Exp = {
_eq?: Maybe<Scalars['Boolean']>
_gt?: Maybe<Scalars['Boolean']>
_gte?: Maybe<Scalars['Boolean']>
_in?: Maybe<Array<Scalars['Boolean']>>
_is_null?: Maybe<Scalars['Boolean']>
_lt?: Maybe<Scalars['Boolean']>
_lte?: Maybe<Scalars['Boolean']>
_neq?: Maybe<Scalars['Boolean']>
_nin?: Maybe<Array<Scalars['Boolean']>>
}
/** Boolean expression to compare columns of type "String". All fields are combined with logical 'AND'. */
export type String_Comparison_Exp = {
_eq?: Maybe<Scalars['String']>
_gt?: Maybe<Scalars['String']>
_gte?: Maybe<Scalars['String']>
/** does the column match the given case-insensitive pattern */
_ilike?: Maybe<Scalars['String']>
_in?: Maybe<Array<Scalars['String']>>
_is_null?: Maybe<Scalars['Boolean']>
/** does the column match the given pattern */
_like?: Maybe<Scalars['String']>
_lt?: Maybe<Scalars['String']>
_lte?: Maybe<Scalars['String']>
_neq?: Maybe<Scalars['String']>
/** does the column NOT match the given case-insensitive pattern */
_nilike?: Maybe<Scalars['String']>
_nin?: Maybe<Array<Scalars['String']>>
/** does the column NOT match the given pattern */
_nlike?: Maybe<Scalars['String']>
/** does the column NOT match the given SQL regular expression */
_nsimilar?: Maybe<Scalars['String']>
/** does the column match the given SQL regular expression */
_similar?: Maybe<Scalars['String']>
}
/** order by aggregate values of table "auth.account_providers" */
export type Auth_Account_Providers_Aggregate_Order_By = {
count?: Maybe<Order_By>
max?: Maybe<Auth_Account_Providers_Max_Order_By>
min?: Maybe<Auth_Account_Providers_Min_Order_By>
}
/** input type for inserting array relation for remote table "auth.account_providers" */
export type Auth_Account_Providers_Arr_Rel_Insert_Input = {
data: Array<Auth_Account_Providers_Insert_Input>
/** on conflict condition */
on_conflict?: Maybe<Auth_Account_Providers_On_Conflict>
}
/** Boolean expression to filter rows from the table "auth.account_providers". All fields are combined with a logical 'AND'. */
export type Auth_Account_Providers_Bool_Exp = {
_and?: Maybe<Array<Auth_Account_Providers_Bool_Exp>>
_not?: Maybe<Auth_Account_Providers_Bool_Exp>
_or?: Maybe<Array<Auth_Account_Providers_Bool_Exp>>
account?: Maybe<Auth_Accounts_Bool_Exp>
account_id?: Maybe<Uuid_Comparison_Exp>
auth_provider?: Maybe<String_Comparison_Exp>
auth_provider_unique_id?: Maybe<String_Comparison_Exp>
created_at?: Maybe<Timestamptz_Comparison_Exp>
id?: Maybe<Uuid_Comparison_Exp>
provider?: Maybe<Auth_Providers_Bool_Exp>
updated_at?: Maybe<Timestamptz_Comparison_Exp>
}
/** input type for inserting data into table "auth.account_providers" */
export type Auth_Account_Providers_Insert_Input = {
account?: Maybe<Auth_Accounts_Obj_Rel_Insert_Input>
account_id?: Maybe<Scalars['uuid']>
auth_provider?: Maybe<Scalars['String']>
auth_provider_unique_id?: Maybe<Scalars['String']>
created_at?: Maybe<Scalars['timestamptz']>
id?: Maybe<Scalars['uuid']>
provider?: Maybe<Auth_Providers_Obj_Rel_Insert_Input>
updated_at?: Maybe<Scalars['timestamptz']>
}
/** order by max() on columns of table "auth.account_providers" */
export type Auth_Account_Providers_Max_Order_By = {
account_id?: Maybe<Order_By>
auth_provider?: Maybe<Order_By>
auth_provider_unique_id?: Maybe<Order_By>
created_at?: Maybe<Order_By>
id?: Maybe<Order_By>
updated_at?: Maybe<Order_By>
}
/** order by min() on columns of table "auth.account_providers" */
export type Auth_Account_Providers_Min_Order_By = {
account_id?: Maybe<Order_By>
auth_provider?: Maybe<Order_By>
auth_provider_unique_id?: Maybe<Order_By>
created_at?: Maybe<Order_By>
id?: Maybe<Order_By>
updated_at?: Maybe<Order_By>
}
/** on conflict condition type for table "auth.account_providers" */
export type Auth_Account_Providers_On_Conflict = {
constraint: Auth_Account_Providers_Constraint
update_columns: Array<Auth_Account_Providers_Update_Column>
where?: Maybe<Auth_Account_Providers_Bool_Exp>
}
/** Ordering options when selecting data from "auth.account_providers". */
export type Auth_Account_Providers_Order_By = {
account?: Maybe<Auth_Accounts_Order_By>
account_id?: Maybe<Order_By>
auth_provider?: Maybe<Order_By>
auth_provider_unique_id?: Maybe<Order_By>
created_at?: Maybe<Order_By>
id?: Maybe<Order_By>
provider?: Maybe<Auth_Providers_Order_By>
updated_at?: Maybe<Order_By>
}
/** primary key columns input for table: auth_account_providers */
export type Auth_Account_Providers_Pk_Columns_Input = {
id: Scalars['uuid']
}
/** input type for updating data in table "auth.account_providers" */
export type Auth_Account_Providers_Set_Input = {
account_id?: Maybe<Scalars['uuid']>
auth_provider?: Maybe<Scalars['String']>
auth_provider_unique_id?: Maybe<Scalars['String']>
created_at?: Maybe<Scalars['timestamptz']>
id?: Maybe<Scalars['uuid']>
updated_at?: Maybe<Scalars['timestamptz']>
}
/** order by aggregate values of table "auth.account_roles" */
export type Auth_Account_Roles_Aggregate_Order_By = {
count?: Maybe<Order_By>
max?: Maybe<Auth_Account_Roles_Max_Order_By>
min?: Maybe<Auth_Account_Roles_Min_Order_By>
}
/** input type for inserting array relation for remote table "auth.account_roles" */
export type Auth_Account_Roles_Arr_Rel_Insert_Input = {
data: Array<Auth_Account_Roles_Insert_Input>
/** on conflict condition */
on_conflict?: Maybe<Auth_Account_Roles_On_Conflict>
}
/** Boolean expression to filter rows from the table "auth.account_roles". All fields are combined with a logical 'AND'. */
export type Auth_Account_Roles_Bool_Exp = {
_and?: Maybe<Array<Auth_Account_Roles_Bool_Exp>>
_not?: Maybe<Auth_Account_Roles_Bool_Exp>
_or?: Maybe<Array<Auth_Account_Roles_Bool_Exp>>
account?: Maybe<Auth_Accounts_Bool_Exp>
account_id?: Maybe<Uuid_Comparison_Exp>
created_at?: Maybe<Timestamptz_Comparison_Exp>
id?: Maybe<Uuid_Comparison_Exp>
role?: Maybe<String_Comparison_Exp>
roleByRole?: Maybe<Auth_Roles_Bool_Exp>
}
/** input type for inserting data into table "auth.account_roles" */
export type Auth_Account_Roles_Insert_Input = {
account?: Maybe<Auth_Accounts_Obj_Rel_Insert_Input>
account_id?: Maybe<Scalars['uuid']>
created_at?: Maybe<Scalars['timestamptz']>
id?: Maybe<Scalars['uuid']>
role?: Maybe<Scalars['String']>
roleByRole?: Maybe<Auth_Roles_Obj_Rel_Insert_Input>
}
/** order by max() on columns of table "auth.account_roles" */
export type Auth_Account_Roles_Max_Order_By = {
account_id?: Maybe<Order_By>
created_at?: Maybe<Order_By>
id?: Maybe<Order_By>
role?: Maybe<Order_By>
}
/** order by min() on columns of table "auth.account_roles" */
export type Auth_Account_Roles_Min_Order_By = {
account_id?: Maybe<Order_By>
created_at?: Maybe<Order_By>
id?: Maybe<Order_By>
role?: Maybe<Order_By>
}
/** on conflict condition type for table "auth.account_roles" */
export type Auth_Account_Roles_On_Conflict = {
constraint: Auth_Account_Roles_Constraint
update_columns: Array<Auth_Account_Roles_Update_Column>
where?: Maybe<Auth_Account_Roles_Bool_Exp>
}
/** Ordering options when selecting data from "auth.account_roles". */
export type Auth_Account_Roles_Order_By = {
account?: Maybe<Auth_Accounts_Order_By>
account_id?: Maybe<Order_By>
created_at?: Maybe<Order_By>
id?: Maybe<Order_By>
role?: Maybe<Order_By>
roleByRole?: Maybe<Auth_Roles_Order_By>
}
/** primary key columns input for table: auth_account_roles */
export type Auth_Account_Roles_Pk_Columns_Input = {
id: Scalars['uuid']
}
/** input type for updating data in table "auth.account_roles" */
export type Auth_Account_Roles_Set_Input = {
account_id?: Maybe<Scalars['uuid']>
created_at?: Maybe<Scalars['timestamptz']>
id?: Maybe<Scalars['uuid']>
role?: Maybe<Scalars['String']>
}
/** order by aggregate values of table "auth.accounts" */
export type Auth_Accounts_Aggregate_Order_By = {
count?: Maybe<Order_By>
max?: Maybe<Auth_Accounts_Max_Order_By>
min?: Maybe<Auth_Accounts_Min_Order_By>
}
/** append existing jsonb value of filtered columns with new jsonb value */
export type Auth_Accounts_Append_Input = {
custom_register_data?: Maybe<Scalars['jsonb']>
}
/** input type for inserting array relation for remote table "auth.accounts" */
export type Auth_Accounts_Arr_Rel_Insert_Input = {
data: Array<Auth_Accounts_Insert_Input>
/** on conflict condition */
on_conflict?: Maybe<Auth_Accounts_On_Conflict>
}
/** Boolean expression to filter rows from the table "auth.accounts". All fields are combined with a logical 'AND'. */
export type Auth_Accounts_Bool_Exp = {
_and?: Maybe<Array<Auth_Accounts_Bool_Exp>>
_not?: Maybe<Auth_Accounts_Bool_Exp>
_or?: Maybe<Array<Auth_Accounts_Bool_Exp>>
account_providers?: Maybe<Auth_Account_Providers_Bool_Exp>
account_roles?: Maybe<Auth_Account_Roles_Bool_Exp>
active?: Maybe<Boolean_Comparison_Exp>
created_at?: Maybe<Timestamptz_Comparison_Exp>
custom_register_data?: Maybe<Jsonb_Comparison_Exp>
default_role?: Maybe<String_Comparison_Exp>
email?: Maybe<Citext_Comparison_Exp>
id?: Maybe<Uuid_Comparison_Exp>
is_anonymous?: Maybe<Boolean_Comparison_Exp>
mfa_enabled?: Maybe<Boolean_Comparison_Exp>
new_email?: Maybe<Citext_Comparison_Exp>
otp_secret?: Maybe<String_Comparison_Exp>
password_hash?: Maybe<String_Comparison_Exp>
refresh_tokens?: Maybe<Auth_Refresh_Tokens_Bool_Exp>
role?: Maybe<Auth_Roles_Bool_Exp>
ticket?: Maybe<Uuid_Comparison_Exp>
ticket_expires_at?: Maybe<Timestamptz_Comparison_Exp>
updated_at?: Maybe<Timestamptz_Comparison_Exp>
user?: Maybe<Users_Bool_Exp>
user_id?: Maybe<Uuid_Comparison_Exp>
}
/** delete the field or element with specified path (for JSON arrays, negative integers count from the end) */
export type Auth_Accounts_Delete_At_Path_Input = {
custom_register_data?: Maybe<Array<Scalars['String']>>
}
/** delete the array element with specified index (negative integers count from the end). throws an error if top level container is not an array */
export type Auth_Accounts_Delete_Elem_Input = {
custom_register_data?: Maybe<Scalars['Int']>
}
/** delete key/value pair or string element. key/value pairs are matched based on their key value */
export type Auth_Accounts_Delete_Key_Input = {
custom_register_data?: Maybe<Scalars['String']>
}
/** input type for inserting data into table "auth.accounts" */
export type Auth_Accounts_Insert_Input = {
account_providers?: Maybe<Auth_Account_Providers_Arr_Rel_Insert_Input>
account_roles?: Maybe<Auth_Account_Roles_Arr_Rel_Insert_Input>
active?: Maybe<Scalars['Boolean']>
created_at?: Maybe<Scalars['timestamptz']>
custom_register_data?: Maybe<Scalars['jsonb']>
default_role?: Maybe<Scalars['String']>
email?: Maybe<Scalars['citext']>
id?: Maybe<Scalars['uuid']>
is_anonymous?: Maybe<Scalars['Boolean']>
mfa_enabled?: Maybe<Scalars['Boolean']>
new_email?: Maybe<Scalars['citext']>
otp_secret?: Maybe<Scalars['String']>
password_hash?: Maybe<Scalars['String']>
refresh_tokens?: Maybe<Auth_Refresh_Tokens_Arr_Rel_Insert_Input>
role?: Maybe<Auth_Roles_Obj_Rel_Insert_Input>
ticket?: Maybe<Scalars['uuid']>
ticket_expires_at?: Maybe<Scalars['timestamptz']>
updated_at?: Maybe<Scalars['timestamptz']>
user?: Maybe<Users_Obj_Rel_Insert_Input>
user_id?: Maybe<Scalars['uuid']>
}
/** order by max() on columns of table "auth.accounts" */
export type Auth_Accounts_Max_Order_By = {
created_at?: Maybe<Order_By>
default_role?: Maybe<Order_By>
email?: Maybe<Order_By>
id?: Maybe<Order_By>
new_email?: Maybe<Order_By>
otp_secret?: Maybe<Order_By>
password_hash?: Maybe<Order_By>
ticket?: Maybe<Order_By>
ticket_expires_at?: Maybe<Order_By>
updated_at?: Maybe<Order_By>
user_id?: Maybe<Order_By>
}
/** order by min() on columns of table "auth.accounts" */
export type Auth_Accounts_Min_Order_By = {
created_at?: Maybe<Order_By>
default_role?: Maybe<Order_By>
email?: Maybe<Order_By>
id?: Maybe<Order_By>
new_email?: Maybe<Order_By>
otp_secret?: Maybe<Order_By>
password_hash?: Maybe<Order_By>
ticket?: Maybe<Order_By>
ticket_expires_at?: Maybe<Order_By>
updated_at?: Maybe<Order_By>
user_id?: Maybe<Order_By>
}
/** input type for inserting object relation for remote table "auth.accounts" */
export type Auth_Accounts_Obj_Rel_Insert_Input = {
data: Auth_Accounts_Insert_Input
/** on conflict condition */
on_conflict?: Maybe<Auth_Accounts_On_Conflict>
}
/** on conflict condition type for table "auth.accounts" */
export type Auth_Accounts_On_Conflict = {
constraint: Auth_Accounts_Constraint
update_columns: Array<Auth_Accounts_Update_Column>
where?: Maybe<Auth_Accounts_Bool_Exp>
}
/** Ordering options when selecting data from "auth.accounts". */
export type Auth_Accounts_Order_By = {
account_providers_aggregate?: Maybe<Auth_Account_Providers_Aggregate_Order_By>
account_roles_aggregate?: Maybe<Auth_Account_Roles_Aggregate_Order_By>
active?: Maybe<Order_By>
created_at?: Maybe<Order_By>
custom_register_data?: Maybe<Order_By>
default_role?: Maybe<Order_By>
email?: Maybe<Order_By>
id?: Maybe<Order_By>
is_anonymous?: Maybe<Order_By>
mfa_enabled?: Maybe<Order_By>
new_email?: Maybe<Order_By>
otp_secret?: Maybe<Order_By>
password_hash?: Maybe<Order_By>
refresh_tokens_aggregate?: Maybe<Auth_Refresh_Tokens_Aggregate_Order_By>
role?: Maybe<Auth_Roles_Order_By>
ticket?: Maybe<Order_By>
ticket_expires_at?: Maybe<Order_By>
updated_at?: Maybe<Order_By>
user?: Maybe<Users_Order_By>
user_id?: Maybe<Order_By>
}
/** primary key columns input for table: auth_accounts */
export type Auth_Accounts_Pk_Columns_Input = {
id: Scalars['uuid']
}
/** prepend existing jsonb value of filtered columns with new jsonb value */
export type Auth_Accounts_Prepend_Input = {
custom_register_data?: Maybe<Scalars['jsonb']>
}
/** input type for updating data in table "auth.accounts" */
export type Auth_Accounts_Set_Input = {
active?: Maybe<Scalars['Boolean']>
created_at?: Maybe<Scalars['timestamptz']>
custom_register_data?: Maybe<Scalars['jsonb']>
default_role?: Maybe<Scalars['String']>
email?: Maybe<Scalars['citext']>
id?: Maybe<Scalars['uuid']>
is_anonymous?: Maybe<Scalars['Boolean']>
mfa_enabled?: Maybe<Scalars['Boolean']>
new_email?: Maybe<Scalars['citext']>
otp_secret?: Maybe<Scalars['String']>
password_hash?: Maybe<Scalars['String']>
ticket?: Maybe<Scalars['uuid']>
ticket_expires_at?: Maybe<Scalars['timestamptz']>
updated_at?: Maybe<Scalars['timestamptz']>
user_id?: Maybe<Scalars['uuid']>
}
/** Boolean expression to filter rows from the table "auth.providers". All fields are combined with a logical 'AND'. */
export type Auth_Providers_Bool_Exp = {
_and?: Maybe<Array<Auth_Providers_Bool_Exp>>
_not?: Maybe<Auth_Providers_Bool_Exp>
_or?: Maybe<Array<Auth_Providers_Bool_Exp>>
account_providers?: Maybe<Auth_Account_Providers_Bool_Exp>
provider?: Maybe<String_Comparison_Exp>
}
/** input type for inserting data into table "auth.providers" */
export type Auth_Providers_Insert_Input = {
account_providers?: Maybe<Auth_Account_Providers_Arr_Rel_Insert_Input>
provider?: Maybe<Scalars['String']>
}
/** input type for inserting object relation for remote table "auth.providers" */
export type Auth_Providers_Obj_Rel_Insert_Input = {
data: Auth_Providers_Insert_Input
/** on conflict condition */
on_conflict?: Maybe<Auth_Providers_On_Conflict>
}
/** on conflict condition type for table "auth.providers" */
export type Auth_Providers_On_Conflict = {
constraint: Auth_Providers_Constraint
update_columns: Array<Auth_Providers_Update_Column>
where?: Maybe<Auth_Providers_Bool_Exp>
}
/** Ordering options when selecting data from "auth.providers". */
export type Auth_Providers_Order_By = {
account_providers_aggregate?: Maybe<Auth_Account_Providers_Aggregate_Order_By>
provider?: Maybe<Order_By>
}
/** primary key columns input for table: auth_providers */
export type Auth_Providers_Pk_Columns_Input = {
provider: Scalars['String']
}
/** input type for updating data in table "auth.providers" */
export type Auth_Providers_Set_Input = {
provider?: Maybe<Scalars['String']>
}
/** order by aggregate values of table "auth.refresh_tokens" */
export type Auth_Refresh_Tokens_Aggregate_Order_By = {
count?: Maybe<Order_By>
max?: Maybe<Auth_Refresh_Tokens_Max_Order_By>
min?: Maybe<Auth_Refresh_Tokens_Min_Order_By>
}
/** input type for inserting array relation for remote table "auth.refresh_tokens" */
export type Auth_Refresh_Tokens_Arr_Rel_Insert_Input = {
data: Array<Auth_Refresh_Tokens_Insert_Input>
/** on conflict condition */
on_conflict?: Maybe<Auth_Refresh_Tokens_On_Conflict>
}
/** Boolean expression to filter rows from the table "auth.refresh_tokens". All fields are combined with a logical 'AND'. */
export type Auth_Refresh_Tokens_Bool_Exp = {
_and?: Maybe<Array<Auth_Refresh_Tokens_Bool_Exp>>
_not?: Maybe<Auth_Refresh_Tokens_Bool_Exp>
_or?: Maybe<Array<Auth_Refresh_Tokens_Bool_Exp>>
account?: Maybe<Auth_Accounts_Bool_Exp>
account_id?: Maybe<Uuid_Comparison_Exp>
created_at?: Maybe<Timestamptz_Comparison_Exp>
expires_at?: Maybe<Timestamptz_Comparison_Exp>
refresh_token?: Maybe<Uuid_Comparison_Exp>
}
/** input type for inserting data into table "auth.refresh_tokens" */
export type Auth_Refresh_Tokens_Insert_Input = {
account?: Maybe<Auth_Accounts_Obj_Rel_Insert_Input>
account_id?: Maybe<Scalars['uuid']>
created_at?: Maybe<Scalars['timestamptz']>
expires_at?: Maybe<Scalars['timestamptz']>
refresh_token?: Maybe<Scalars['uuid']>
}
/** order by max() on columns of table "auth.refresh_tokens" */
export type Auth_Refresh_Tokens_Max_Order_By = {
account_id?: Maybe<Order_By>
created_at?: Maybe<Order_By>
expires_at?: Maybe<Order_By>
refresh_token?: Maybe<Order_By>
}
/** order by min() on columns of table "auth.refresh_tokens" */
export type Auth_Refresh_Tokens_Min_Order_By = {
account_id?: Maybe<Order_By>
created_at?: Maybe<Order_By>
expires_at?: Maybe<Order_By>
refresh_token?: Maybe<Order_By>
}
/** on conflict condition type for table "auth.refresh_tokens" */
export type Auth_Refresh_Tokens_On_Conflict = {
constraint: Auth_Refresh_Tokens_Constraint
update_columns: Array<Auth_Refresh_Tokens_Update_Column>
where?: Maybe<Auth_Refresh_Tokens_Bool_Exp>
}
/** Ordering options when selecting data from "auth.refresh_tokens". */
export type Auth_Refresh_Tokens_Order_By = {
account?: Maybe<Auth_Accounts_Order_By>
account_id?: Maybe<Order_By>
created_at?: Maybe<Order_By>
expires_at?: Maybe<Order_By>
refresh_token?: Maybe<Order_By>
}
/** primary key columns input for table: auth_refresh_tokens */
export type Auth_Refresh_Tokens_Pk_Columns_Input = {
refresh_token: Scalars['uuid']
}
/** input type for updating data in table "auth.refresh_tokens" */
export type Auth_Refresh_Tokens_Set_Input = {
account_id?: Maybe<Scalars['uuid']>
created_at?: Maybe<Scalars['timestamptz']>
expires_at?: Maybe<Scalars['timestamptz']>
refresh_token?: Maybe<Scalars['uuid']>
}
/** Boolean expression to filter rows from the table "auth.roles". All fields are combined with a logical 'AND'. */
export type Auth_Roles_Bool_Exp = {
_and?: Maybe<Array<Auth_Roles_Bool_Exp>>
_not?: Maybe<Auth_Roles_Bool_Exp>
_or?: Maybe<Array<Auth_Roles_Bool_Exp>>
account_roles?: Maybe<Auth_Account_Roles_Bool_Exp>
accounts?: Maybe<Auth_Accounts_Bool_Exp>
role?: Maybe<String_Comparison_Exp>
}
/** input type for inserting data into table "auth.roles" */
export type Auth_Roles_Insert_Input = {
account_roles?: Maybe<Auth_Account_Roles_Arr_Rel_Insert_Input>
accounts?: Maybe<Auth_Accounts_Arr_Rel_Insert_Input>
role?: Maybe<Scalars['String']>
}
/** input type for inserting object relation for remote table "auth.roles" */
export type Auth_Roles_Obj_Rel_Insert_Input = {
data: Auth_Roles_Insert_Input
/** on conflict condition */
on_conflict?: Maybe<Auth_Roles_On_Conflict>
}
/** on conflict condition type for table "auth.roles" */
export type Auth_Roles_On_Conflict = {
constraint: Auth_Roles_Constraint
update_columns: Array<Auth_Roles_Update_Column>
where?: Maybe<Auth_Roles_Bool_Exp>
}
/** Ordering options when selecting data from "auth.roles". */
export type Auth_Roles_Order_By = {
account_roles_aggregate?: Maybe<Auth_Account_Roles_Aggregate_Order_By>
accounts_aggregate?: Maybe<Auth_Accounts_Aggregate_Order_By>
role?: Maybe<Order_By>
}
/** primary key columns input for table: auth_roles */
export type Auth_Roles_Pk_Columns_Input = {
role: Scalars['String']
}
/** input type for updating data in table "auth.roles" */
export type Auth_Roles_Set_Input = {
role?: Maybe<Scalars['String']>
}
/** Boolean expression to compare columns of type "citext". All fields are combined with logical 'AND'. */
export type Citext_Comparison_Exp = {
_eq?: Maybe<Scalars['citext']>
_gt?: Maybe<Scalars['citext']>
_gte?: Maybe<Scalars['citext']>
/** does the column match the given case-insensitive pattern */
_ilike?: Maybe<Scalars['citext']>
_in?: Maybe<Array<Scalars['citext']>>
_is_null?: Maybe<Scalars['Boolean']>
/** does the column match the given pattern */
_like?: Maybe<Scalars['citext']>
_lt?: Maybe<Scalars['citext']>
_lte?: Maybe<Scalars['citext']>
_neq?: Maybe<Scalars['citext']>
/** does the column NOT match the given case-insensitive pattern */
_nilike?: Maybe<Scalars['citext']>
_nin?: Maybe<Array<Scalars['citext']>>
/** does the column NOT match the given pattern */
_nlike?: Maybe<Scalars['citext']>
/** does the column NOT match the given SQL regular expression */
_nsimilar?: Maybe<Scalars['citext']>
/** does the column match the given SQL regular expression */
_similar?: Maybe<Scalars['citext']>
}
/** Boolean expression to compare columns of type "jsonb". All fields are combined with logical 'AND'. */
export type Jsonb_Comparison_Exp = {
/** is the column contained in the given json value */
_contained_in?: Maybe<Scalars['jsonb']>
/** does the column contain the given json value at the top level */
_contains?: Maybe<Scalars['jsonb']>
_eq?: Maybe<Scalars['jsonb']>
_gt?: Maybe<Scalars['jsonb']>
_gte?: Maybe<Scalars['jsonb']>
/** does the string exist as a top-level key in the column */
_has_key?: Maybe<Scalars['String']>
/** do all of these strings exist as top-level keys in the column */
_has_keys_all?: Maybe<Array<Scalars['String']>>
/** do any of these strings exist as top-level keys in the column */
_has_keys_any?: Maybe<Array<Scalars['String']>>
_in?: Maybe<Array<Scalars['jsonb']>>
_is_null?: Maybe<Scalars['Boolean']>
_lt?: Maybe<Scalars['jsonb']>
_lte?: Maybe<Scalars['jsonb']>
_neq?: Maybe<Scalars['jsonb']>
_nin?: Maybe<Array<Scalars['jsonb']>>
}
/** Boolean expression to compare columns of type "timestamptz". All fields are combined with logical 'AND'. */
export type Timestamptz_Comparison_Exp = {
_eq?: Maybe<Scalars['timestamptz']>
_gt?: Maybe<Scalars['timestamptz']>
_gte?: Maybe<Scalars['timestamptz']>
_in?: Maybe<Array<Scalars['timestamptz']>>
_is_null?: Maybe<Scalars['Boolean']>
_lt?: Maybe<Scalars['timestamptz']>
_lte?: Maybe<Scalars['timestamptz']>
_neq?: Maybe<Scalars['timestamptz']>
_nin?: Maybe<Array<Scalars['timestamptz']>>
}
/** Boolean expression to filter rows from the table "users". All fields are combined with a logical 'AND'. */
export type Users_Bool_Exp = {
_and?: Maybe<Array<Users_Bool_Exp>>
_not?: Maybe<Users_Bool_Exp>
_or?: Maybe<Array<Users_Bool_Exp>>
account?: Maybe<Auth_Accounts_Bool_Exp>
avatar_url?: Maybe<String_Comparison_Exp>
created_at?: Maybe<Timestamptz_Comparison_Exp>
display_name?: Maybe<String_Comparison_Exp>
id?: Maybe<Uuid_Comparison_Exp>
updated_at?: Maybe<Timestamptz_Comparison_Exp>
}
/** input type for inserting data into table "users" */
export type Users_Insert_Input = {
account?: Maybe<Auth_Accounts_Obj_Rel_Insert_Input>
avatar_url?: Maybe<Scalars['String']>
created_at?: Maybe<Scalars['timestamptz']>
display_name?: Maybe<Scalars['String']>
id?: Maybe<Scalars['uuid']>
updated_at?: Maybe<Scalars['timestamptz']>
}
/** input type for inserting object relation for remote table "users" */
export type Users_Obj_Rel_Insert_Input = {
data: Users_Insert_Input
/** on conflict condition */
on_conflict?: Maybe<Users_On_Conflict>
}
/** on conflict condition type for table "users" */
export type Users_On_Conflict = {
constraint: Users_Constraint
update_columns: Array<Users_Update_Column>
where?: Maybe<Users_Bool_Exp>
}
/** Ordering options when selecting data from "users". */
export type Users_Order_By = {
account?: Maybe<Auth_Accounts_Order_By>
avatar_url?: Maybe<Order_By>
created_at?: Maybe<Order_By>
display_name?: Maybe<Order_By>
id?: Maybe<Order_By>
updated_at?: Maybe<Order_By>
}
/** primary key columns input for table: users */
export type Users_Pk_Columns_Input = {
id: Scalars['uuid']
}
/** input type for updating data in table "users" */
export type Users_Set_Input = {
avatar_url?: Maybe<Scalars['String']>
created_at?: Maybe<Scalars['timestamptz']>
display_name?: Maybe<Scalars['String']>
id?: Maybe<Scalars['uuid']>
updated_at?: Maybe<Scalars['timestamptz']>
}
/** Boolean expression to compare columns of type "uuid". All fields are combined with logical 'AND'. */
export type Uuid_Comparison_Exp = {
_eq?: Maybe<Scalars['uuid']>
_gt?: Maybe<Scalars['uuid']>
_gte?: Maybe<Scalars['uuid']>
_in?: Maybe<Array<Scalars['uuid']>>
_is_null?: Maybe<Scalars['Boolean']>
_lt?: Maybe<Scalars['uuid']>
_lte?: Maybe<Scalars['uuid']>
_neq?: Maybe<Scalars['uuid']>
_nin?: Maybe<Array<Scalars['uuid']>>
}
export type GetUserByIdQueryVariables = Exact<{
id: Scalars['uuid']
}>
export type GetUserByIdQuery = { __typename?: 'query_root' } & {
user?: Maybe<
{ __typename?: 'users' } & Pick<Users, 'id'> & {
displayName: Users['display_name']
avatarUrl: Users['avatar_url']
} & { account?: Maybe<{ __typename?: 'auth_accounts' } & Pick<Auth_Accounts, 'email'>> }
>
} | the_stack |
import _ from 'lodash'
import { ElemID, CORE_ANNOTATIONS } from '@salto-io/adapter-api'
import { createMatchingObjectType } from '@salto-io/adapter-utils'
import { client as clientUtils, config as configUtils } from '@salto-io/adapter-components'
import { ZENDESK_SUPPORT } from './constants'
const { createClientConfigType } = clientUtils
const {
createUserFetchConfigType, createDucktypeAdapterApiConfigType, validateDuckTypeFetchConfig,
} = configUtils
export const DEFAULT_ID_FIELDS = ['name', 'id']
export const DEFAULT_FILENAME_FIELDS = ['name']
export const FIELDS_TO_OMIT: configUtils.FieldToOmitType[] = [
{ fieldName: 'created_at', fieldType: 'string' },
{ fieldName: 'updated_at', fieldType: 'string' },
{ fieldName: 'extended_input_schema' },
{ fieldName: 'extended_output_schema' },
{ fieldName: 'url', fieldType: 'string' },
{ fieldName: 'count', fieldType: 'number' },
]
export const CLIENT_CONFIG = 'client'
export const FETCH_CONFIG = 'fetch'
export const API_DEFINITIONS_CONFIG = 'apiDefinitions'
export type ZendeskClientConfig = clientUtils.ClientBaseConfig<clientUtils.ClientRateLimitConfig>
export type ZendeskFetchConfig = configUtils.UserFetchConfig
export type ZendeskApiConfig = configUtils.AdapterDuckTypeApiConfig
export type ZendeskConfig = {
[CLIENT_CONFIG]?: ZendeskClientConfig
[FETCH_CONFIG]: ZendeskFetchConfig
[API_DEFINITIONS_CONFIG]: ZendeskApiConfig
}
export const DEFAULT_TYPES: Record<string, configUtils.TypeDuckTypeConfig> = {
// types that should exist in workspace
group: {
transformation: {
sourceTypeName: 'groups__groups',
},
},
custom_role: {
transformation: {
sourceTypeName: 'custom_roles__custom_roles',
},
},
organization: {
transformation: {
sourceTypeName: 'organizations__organizations',
},
},
view: {
transformation: {
sourceTypeName: 'views__views',
idFields: ['title', 'id'],
fileNameFields: ['title'],
},
},
trigger: {
transformation: {
sourceTypeName: 'triggers__triggers',
idFields: ['title', 'id'],
fileNameFields: ['title'],
},
},
trigger_category: {
transformation: {
sourceTypeName: 'trigger_categories__trigger_categories',
idFields: ['name', 'id'],
fileNameFields: ['name'],
},
},
automation: {
transformation: {
sourceTypeName: 'automations__automations',
idFields: ['title', 'id'],
fileNameFields: ['title'],
},
},
sla_policy: {
transformation: {
sourceTypeName: 'sla_policies__sla_policies',
idFields: ['title', 'id'],
fileNameFields: ['title'],
},
},
sla_policy_definition: {
transformation: {
sourceTypeName: 'sla_policies_definitions__definitions',
},
},
target: {
transformation: {
sourceTypeName: 'targets__targets',
idFields: ['title', 'type'], // looks like title is unique so not adding id
},
},
macro: {
transformation: {
sourceTypeName: 'macros__macros',
idFields: ['title', 'id'],
fileNameFields: ['title'],
},
},
macro_action: {
transformation: {
sourceTypeName: 'macros_actions__actions',
},
},
macro_category: {
transformation: {
sourceTypeName: 'macros_categories__categories',
},
},
macro_definition: {
transformation: {
sourceTypeName: 'macros_definitions__definitions',
},
},
brand: {
transformation: {
sourceTypeName: 'brands__brands',
},
},
locale: {
transformation: {
sourceTypeName: 'locales__locales',
idFields: ['locale'],
fileNameFields: ['locale'],
},
},
business_hours_schedule: {
transformation: {
sourceTypeName: 'business_hours_schedules__schedules',
},
},
sharing_agreement: {
transformation: {
sourceTypeName: 'sharing_agreements__sharing_agreements',
},
},
recipient_address: {
transformation: {
sourceTypeName: 'recipient_addresses__recipient_addresses',
},
},
ticket_form: {
transformation: {
sourceTypeName: 'ticket_forms__ticket_forms',
},
},
ticket_field: {
transformation: {
sourceTypeName: 'ticket_fields__ticket_fields',
idFields: ['type', 'title', 'id'],
fileNameFields: ['type', 'title'],
standaloneFields: [{ fieldName: 'custom_field_options' }],
},
},
user_field: {
transformation: {
sourceTypeName: 'user_fields__user_fields',
idFields: ['key'],
standaloneFields: [{ fieldName: 'custom_field_options' }],
},
},
organization_field: {
transformation: {
sourceTypeName: 'organization_fields__organization_fields',
idFields: ['key'],
standaloneFields: [{ fieldName: 'custom_field_options' }],
},
},
routing_attribute: {
transformation: {
sourceTypeName: 'routing_attributes__attributes',
},
},
routing_attribute_definition: {
transformation: {
sourceTypeName: 'routing_attribute_definitions__definitions',
hasDynamicFields: true,
},
},
workspace: {
transformation: {
sourceTypeName: 'workspaces__workspaces',
idFields: ['title', 'id'],
fileNameFields: ['title'],
},
},
app_installation: {
transformation: {
sourceTypeName: 'app_installations__installations',
fieldsToOmit: [...FIELDS_TO_OMIT, { fieldName: 'updated', fieldType: 'string' }],
idFields: ['settings.name', 'id'],
fileNameFields: ['settings.name'],
},
},
app_owned: {
transformation: {
sourceTypeName: 'apps_owned__apps',
},
},
oauth_client: {
transformation: {
sourceTypeName: 'oauth_clients__clients',
},
},
oauth_global_client: {
transformation: {
sourceTypeName: 'oauth_global_clients__global_clients',
},
},
account_setting: {
transformation: {
sourceTypeName: 'account_settings__settings',
},
},
resource_collection: {
transformation: {
sourceTypeName: 'resource_collections__resource_collections',
},
},
monitored_twitter_handle: {
transformation: {
sourceTypeName: 'monitored_twitter_handles__monitored_twitter_handles',
},
},
// api types
groups: {
request: {
url: '/groups',
},
transformation: {
dataField: 'groups',
},
},
// eslint-disable-next-line camelcase
custom_roles: {
request: {
url: '/custom_roles',
},
transformation: {
dataField: 'custom_roles',
},
},
organizations: {
request: {
url: '/organizations',
},
transformation: {
dataField: 'organizations',
},
},
views: {
request: {
url: '/views',
},
transformation: {
dataField: 'views',
fileNameFields: ['title'],
},
},
triggers: {
request: {
url: '/triggers',
},
},
trigger_categories: {
request: {
url: '/trigger_categories',
paginationField: 'links.next',
},
transformation: {
dataField: 'trigger_categories',
},
},
automations: {
request: {
url: '/automations',
},
transformation: {
dataField: 'automations',
},
},
// eslint-disable-next-line camelcase
sla_policies: {
request: {
url: '/slas/policies',
},
},
// eslint-disable-next-line camelcase
sla_policies_definitions: {
request: {
url: '/slas/policies/definitions',
},
transformation: {
dataField: 'value',
},
},
targets: {
request: {
url: '/targets',
},
},
macros: {
request: {
url: '/macros',
},
transformation: {
dataField: 'macros',
},
},
// eslint-disable-next-line camelcase
macros_actions: {
request: {
url: '/macros/actions',
},
transformation: {
// no unique identifier for individual items
dataField: '.',
},
},
// eslint-disable-next-line camelcase
macro_categories: {
request: {
url: '/macros/categories',
},
},
// eslint-disable-next-line camelcase
macros_definitions: { // has some overlaps with macro_actions
request: {
url: '/macros/definitions',
},
},
brands: {
request: {
url: '/brands',
},
transformation: {
dataField: 'brands',
},
},
// eslint-disable-next-line camelcase
dynamic_content_item: {
request: {
url: '/dynamic_content/items',
},
transformation: {
dataField: '.',
},
},
locales: {
request: {
url: '/locales',
},
transformation: {
dataField: 'locales',
},
},
// eslint-disable-next-line camelcase
business_hours_schedules: {
request: {
url: '/business_hours/schedules',
},
},
// eslint-disable-next-line camelcase
sharing_agreements: {
request: {
url: '/sharing_agreements',
},
},
// eslint-disable-next-line camelcase
recipient_addresses: {
request: {
url: '/recipient_addresses',
},
transformation: {
dataField: 'recipient_addresses',
},
},
// eslint-disable-next-line camelcase
ticket_forms: {
// not always available
request: {
url: '/ticket_forms',
},
transformation: {
dataField: 'ticket_forms',
},
},
// eslint-disable-next-line camelcase
ticket_fields: {
request: {
url: '/ticket_fields',
},
transformation: {
dataField: 'ticket_fields',
fileNameFields: ['title'],
},
},
// eslint-disable-next-line camelcase
user_fields: {
request: {
url: '/user_fields',
},
},
// eslint-disable-next-line camelcase
organization_fields: {
request: {
url: '/organization_fields',
},
},
// eslint-disable-next-line camelcase
routing_attributes: {
request: {
url: '/routing/attributes',
},
},
// eslint-disable-next-line camelcase
routing_attribute_definitions: {
request: {
url: '/routing/attributes/definitions',
},
transformation: {
dataField: 'definitions',
},
},
workspaces: {
// not always available
request: {
url: '/workspaces',
},
},
// eslint-disable-next-line camelcase
app_installations: {
request: {
url: '/apps/installations',
},
},
// eslint-disable-next-line camelcase
apps_owned: {
request: {
url: '/apps/owned',
},
},
// eslint-disable-next-line camelcase
oauth_clients: {
request: {
url: '/oauth/clients',
},
},
// eslint-disable-next-line camelcase
oauth_global_clients: {
request: {
url: '/oauth/global_clients',
},
},
// eslint-disable-next-line camelcase
account_settings: {
request: {
url: '/account/settings',
},
transformation: {
dataField: 'settings',
},
},
// eslint-disable-next-line camelcase
resource_collections: {
request: {
url: '/resource_collections',
},
},
// eslint-disable-next-line camelcase
monitored_twitter_handles: {
request: {
url: '/channels/twitter/monitored_twitter_handles',
},
},
// not included yet: satisfaction_reason (returns 403), sunshine apis
}
export const configType = createMatchingObjectType<ZendeskConfig>({
elemID: new ElemID(ZENDESK_SUPPORT),
fields: {
[CLIENT_CONFIG]: {
refType: createClientConfigType(ZENDESK_SUPPORT),
},
[FETCH_CONFIG]: {
refType: createUserFetchConfigType(ZENDESK_SUPPORT),
annotations: {
_required: true,
[CORE_ANNOTATIONS.DEFAULT]: {
includeTypes: [
...Object.keys(_.pickBy(DEFAULT_TYPES, def => def.request !== undefined)),
].sort(),
},
},
},
[API_DEFINITIONS_CONFIG]: {
refType: createDucktypeAdapterApiConfigType({ adapter: ZENDESK_SUPPORT }),
annotations: {
_required: true,
[CORE_ANNOTATIONS.DEFAULT]: {
typeDefaults: {
request: {
paginationField: 'next_page',
},
transformation: {
idFields: DEFAULT_ID_FIELDS,
fileNameFields: DEFAULT_FILENAME_FIELDS,
fieldsToOmit: FIELDS_TO_OMIT,
},
},
types: DEFAULT_TYPES,
},
},
},
},
})
export type FilterContext = {
[FETCH_CONFIG]: ZendeskFetchConfig
[API_DEFINITIONS_CONFIG]: ZendeskApiConfig
}
export const validateFetchConfig = validateDuckTypeFetchConfig | the_stack |
import { ConnectionOptions as TlsConnectionOptions } from 'tls'
import { URL } from 'url'
import buffer from 'buffer'
import {
Transport,
UndiciConnection,
WeightedConnectionPool,
CloudConnectionPool,
Serializer,
Diagnostic,
errors,
BaseConnectionPool
} from '@elastic/transport'
import {
HttpAgentOptions,
UndiciAgentOptions,
agentFn,
nodeFilterFn,
nodeSelectorFn,
generateRequestIdFn,
BasicAuth,
ApiKeyAuth,
BearerAuth,
Context
} from '@elastic/transport/lib/types'
import BaseConnection, { prepareHeaders } from '@elastic/transport/lib/connection/BaseConnection'
import SniffingTransport from './sniffingTransport'
import Helpers from './helpers'
import API from './api'
const kChild = Symbol('elasticsearchjs-child')
const kInitialOptions = Symbol('elasticsearchjs-initial-options')
let clientVersion: string = require('../package.json').version // eslint-disable-line
/* istanbul ignore next */
if (clientVersion.includes('-')) {
// clean prerelease
clientVersion = clientVersion.slice(0, clientVersion.indexOf('-')) + 'p'
}
let transportVersion: string = require('@elastic/transport/package.json').version // eslint-disable-line
/* istanbul ignore next */
if (transportVersion.includes('-')) {
// clean prerelease
transportVersion = transportVersion.slice(0, transportVersion.indexOf('-')) + 'p'
}
const nodeVersion = process.versions.node
export interface NodeOptions {
url: URL
id?: string
agent?: HttpAgentOptions | UndiciAgentOptions
ssl?: TlsConnectionOptions
headers?: Record<string, any>
roles?: {
master: boolean
data: boolean
ingest: boolean
ml: boolean
}
}
export interface ClientOptions {
node?: string | string[] | NodeOptions | NodeOptions[]
nodes?: string | string[] | NodeOptions | NodeOptions[]
Connection?: typeof BaseConnection
ConnectionPool?: typeof BaseConnectionPool
Transport?: typeof Transport
Serializer?: typeof Serializer
maxRetries?: number
requestTimeout?: number
pingTimeout?: number
sniffInterval?: number | boolean
sniffOnStart?: boolean
sniffEndpoint?: string
sniffOnConnectionFault?: boolean
resurrectStrategy?: 'ping' | 'optimistic' | 'none'
compression?: boolean
tls?: TlsConnectionOptions
agent?: HttpAgentOptions | UndiciAgentOptions | agentFn | false
nodeFilter?: nodeFilterFn
nodeSelector?: nodeSelectorFn
headers?: Record<string, any>
opaqueIdPrefix?: string
generateRequestId?: generateRequestIdFn
name?: string | symbol
auth?: BasicAuth | ApiKeyAuth | BearerAuth
context?: Context
proxy?: string | URL
enableMetaHeader?: boolean
cloud?: {
id: string
}
disablePrototypePoisoningProtection?: boolean | 'proto' | 'constructor'
caFingerprint?: string
maxResponseSize?: number
maxCompressedResponseSize?: number
}
export default class Client extends API {
diagnostic: Diagnostic
name: string | symbol
connectionPool: BaseConnectionPool
transport: SniffingTransport
serializer: Serializer
helpers: Helpers
constructor (opts: ClientOptions) {
super()
// @ts-expect-error kChild symbol is for internal use only
if ((opts.cloud != null) && opts[kChild] === undefined) {
const { id } = opts.cloud
// the cloud id is `cluster-name:base64encodedurl`
// the url is a string divided by two '$', the first is the cloud url
// the second the elasticsearch instance, the third the kibana instance
const cloudUrls = Buffer.from(id.split(':')[1], 'base64').toString().split('$')
opts.node = `https://${cloudUrls[1]}.${cloudUrls[0]}`
// Cloud has better performances with compression enabled
// see https://github.com/elastic/elasticsearch-py/pull/704.
// So unless the user specifies otherwise, we enable compression.
if (opts.compression == null) opts.compression = true
if (opts.tls == null ||
(opts.tls != null && opts.tls.secureProtocol == null)) {
opts.tls = opts.tls ?? {}
opts.tls.secureProtocol = 'TLSv1_2_method'
}
}
if (opts.node == null && opts.nodes == null) {
throw new errors.ConfigurationError('Missing node(s) option')
}
// @ts-expect-error kChild symbol is for internal use only
if (opts[kChild] === undefined) {
const checkAuth = getAuth(opts.node ?? opts.nodes)
if ((checkAuth != null) && checkAuth.username !== '' && checkAuth.password !== '') {
opts.auth = Object.assign({}, opts.auth, { username: checkAuth.username, password: checkAuth.password })
}
}
const options: Required<ClientOptions> = Object.assign({}, {
Connection: UndiciConnection,
Transport: SniffingTransport,
Serializer,
ConnectionPool: (opts.cloud != null) ? CloudConnectionPool : WeightedConnectionPool,
maxRetries: 3,
requestTimeout: 30000,
pingTimeout: 3000,
sniffInterval: false,
sniffOnStart: false,
sniffEndpoint: '_nodes/_all/http',
sniffOnConnectionFault: false,
resurrectStrategy: 'ping',
compression: false,
tls: null,
caFingerprint: null,
agent: null,
headers: {},
nodeFilter: null,
generateRequestId: null,
name: 'elasticsearch-js',
auth: null,
opaqueIdPrefix: null,
context: null,
proxy: null,
enableMetaHeader: true,
maxResponseSize: null,
maxCompressedResponseSize: null
}, opts)
if (options.caFingerprint !== null && isHttpConnection(opts.node ?? opts.nodes)) {
throw new errors.ConfigurationError('You can\'t configure the caFingerprint with a http connection')
}
if (options.maxResponseSize !== null && options.maxResponseSize > buffer.constants.MAX_STRING_LENGTH) {
throw new errors.ConfigurationError(`The maxResponseSize cannot be bigger than ${buffer.constants.MAX_STRING_LENGTH}`)
}
if (options.maxCompressedResponseSize !== null && options.maxCompressedResponseSize > buffer.constants.MAX_LENGTH) {
throw new errors.ConfigurationError(`The maxCompressedResponseSize cannot be bigger than ${buffer.constants.MAX_LENGTH}`)
}
if (options.enableMetaHeader) {
options.headers['x-elastic-client-meta'] = `es=${clientVersion},js=${nodeVersion},t=${transportVersion},hc=${nodeVersion}`
}
this.name = options.name
// @ts-expect-error kInitialOptions symbol is for internal use only
this[kInitialOptions] = options
// @ts-expect-error kChild symbol is for internal use only
if (opts[kChild] !== undefined) {
// @ts-expect-error kChild symbol is for internal use only
this.serializer = opts[kChild].serializer
// @ts-expect-error kChild symbol is for internal use only
this.connectionPool = opts[kChild].connectionPool
// @ts-expect-error kChild symbol is for internal use only
this.diagnostic = opts[kChild].diagnostic
} else {
this.diagnostic = new Diagnostic()
this.serializer = new options.Serializer()
this.connectionPool = new options.ConnectionPool({
pingTimeout: options.pingTimeout,
resurrectStrategy: options.resurrectStrategy,
tls: options.tls,
agent: options.agent,
proxy: options.proxy,
Connection: options.Connection,
auth: options.auth,
diagnostic: this.diagnostic,
caFingerprint: options.caFingerprint
})
this.connectionPool.addConnection(options.node ?? options.nodes)
}
this.transport = new options.Transport({
diagnostic: this.diagnostic,
connectionPool: this.connectionPool,
serializer: this.serializer,
maxRetries: options.maxRetries,
requestTimeout: options.requestTimeout,
sniffInterval: options.sniffInterval,
sniffOnStart: options.sniffOnStart,
sniffOnConnectionFault: options.sniffOnConnectionFault,
sniffEndpoint: options.sniffEndpoint,
compression: options.compression,
headers: options.headers,
nodeFilter: options.nodeFilter,
nodeSelector: options.nodeSelector,
generateRequestId: options.generateRequestId,
name: options.name,
opaqueIdPrefix: options.opaqueIdPrefix,
context: options.context,
productCheck: 'Elasticsearch',
maxResponseSize: options.maxResponseSize,
maxCompressedResponseSize: options.maxCompressedResponseSize
})
this.helpers = new Helpers({
client: this,
metaHeader: options.enableMetaHeader
? `es=${clientVersion},js=${nodeVersion},t=${transportVersion},hc=${nodeVersion}`
: null,
maxRetries: options.maxRetries
})
}
child (opts: ClientOptions): Client {
// Merge the new options with the initial ones
// @ts-expect-error kChild symbol is for internal use only
const options: ClientOptions = Object.assign({}, this[kInitialOptions], opts)
// Pass to the child client the parent instances that cannot be overriden
// @ts-expect-error kInitialOptions symbol is for internal use only
options[kChild] = {
connectionPool: this.connectionPool,
serializer: this.serializer,
diagnostic: this.diagnostic,
initialOptions: options
}
/* istanbul ignore else */
if (options.auth !== undefined) {
options.headers = prepareHeaders(options.headers, options.auth)
}
return new Client(options)
}
async close (): Promise<void> {
return await this.connectionPool.empty()
}
}
function isHttpConnection (node?: string | string[] | NodeOptions | NodeOptions[]): boolean {
if (Array.isArray(node)) {
return node.some((n) => (typeof n === 'string' ? new URL(n).protocol : n.url.protocol) === 'http:')
} else {
if (node == null) return false
return (typeof node === 'string' ? new URL(node).protocol : node.url.protocol) === 'http:'
}
}
function getAuth (node?: string | string[] | NodeOptions | NodeOptions[]): { username: string, password: string } | null {
if (Array.isArray(node)) {
for (const url of node) {
const auth = getUsernameAndPassword(url)
if (auth != null && auth.username !== '' && auth.password !== '') {
return auth
}
}
return null
} else {
const auth = getUsernameAndPassword(node)
if (auth != null && auth.username !== '' && auth.password !== '') {
return auth
}
return null
}
function getUsernameAndPassword (node?: string | NodeOptions): { username: string, password: string } | null {
/* istanbul ignore else */
if (typeof node === 'string') {
const { username, password } = new URL(node)
return {
username: decodeURIComponent(username),
password: decodeURIComponent(password)
}
} else if (node != null && node.url instanceof URL) {
return {
username: decodeURIComponent(node.url.username),
password: decodeURIComponent(node.url.password)
}
} else {
return null
}
}
} | the_stack |
import { ColumnApi } from "../../../columns/columnApi";
import { ColumnModel } from "../../../columns/columnModel";
import { UserCompDetails, UserComponentFactory } from "../../../components/framework/userComponentFactory";
import { KeyCode } from '../../../constants/keyCode';
import { Autowired, PreDestroy } from "../../../context/context";
import { DragAndDropService, DragItem, DragSource, DragSourceType } from "../../../dragAndDrop/dragAndDropService";
import { Column } from "../../../entities/column";
import { Events } from "../../../eventKeys";
import { GridApi } from "../../../gridApi";
import { IMenuFactory } from "../../../interfaces/iMenuFactory";
import { Beans } from "../../../rendering/beans";
import { ColumnHoverService } from "../../../rendering/columnHoverService";
import { SetLeftFeature } from "../../../rendering/features/setLeftFeature";
import { SortController } from "../../../sortController";
import { ColumnSortState, getAriaSortState } from "../../../utils/aria";
import { ManagedFocusFeature } from "../../../widgets/managedFocusFeature";
import { ITooltipFeatureComp, ITooltipFeatureCtrl, TooltipFeature } from "../../../widgets/tooltipFeature";
import { HeaderRowCtrl } from "../../row/headerRowCtrl";
import { AbstractHeaderCellCtrl, IAbstractHeaderCellComp } from "../abstractCell/abstractHeaderCellCtrl";
import { CssClassApplier } from "../cssClassApplier";
import { HoverFeature } from "../hoverFeature";
import { HeaderComp, IHeader, IHeaderParams } from "./headerComp";
import { ResizeFeature } from "./resizeFeature";
import { SelectAllFeature } from "./selectAllFeature";
export interface IHeaderCellComp extends IAbstractHeaderCellComp, ITooltipFeatureComp {
setWidth(width: string): void;
addOrRemoveCssClass(cssClassName: string, on: boolean): void;
setAriaSort(sort: ColumnSortState | undefined): void;
setColId(id: string): void;
setAriaDescribedBy(id: string | undefined): void;
setUserCompDetails(compDetails: UserCompDetails): void;
getUserCompInstance(): IHeader | undefined;
}
export class HeaderCellCtrl extends AbstractHeaderCellCtrl {
@Autowired('columnModel') private columnModel: ColumnModel;
@Autowired('columnHoverService') private columnHoverService: ColumnHoverService;
@Autowired('beans') protected beans: Beans;
@Autowired('sortController') private sortController: SortController;
@Autowired('menuFactory') private menuFactory: IMenuFactory;
@Autowired('dragAndDropService') private dragAndDropService: DragAndDropService;
@Autowired('gridApi') private gridApi: GridApi;
@Autowired('columnApi') private columnApi: ColumnApi;
@Autowired('userComponentFactory') private userComponentFactory: UserComponentFactory;
private colDefVersion: number;
private comp: IHeaderCellComp;
private column: Column;
private refreshFunctions: (() => void)[] = [];
private selectAllFeature: SelectAllFeature;
private moveDragSource: DragSource | undefined;
private sortable: boolean | null | undefined;
private displayName: string | null;
private draggable: boolean;
private menuEnabled: boolean;
private dragSourceElement: HTMLElement | undefined;
private userCompDetails: UserCompDetails;
private userHeaderClasses: Set<string> = new Set();
constructor(column: Column, parentRowCtrl: HeaderRowCtrl) {
super(column, parentRowCtrl);
this.column = column;
}
public setComp(comp: IHeaderCellComp, eGui: HTMLElement, eResize: HTMLElement): void {
super.setGui(eGui);
this.comp = comp;
this.colDefVersion = this.columnModel.getColDefVersion();
this.updateState();
this.setupWidth();
this.setupMovingCss();
this.setupMenuClass();
this.setupSortableClass();
this.addColumnHoverListener();
this.setupFilterCss();
this.setupColId();
this.setupClassesFromColDef();
this.setupTooltip();
this.addActiveHeaderMouseListeners();
this.setupSelectAll();
this.setupUserComp();
this.createManagedBean(new ResizeFeature(this.getPinned(), this.column, eResize, comp, this));
this.createManagedBean(new HoverFeature([this.column], eGui));
this.createManagedBean(new SetLeftFeature(this.column, eGui, this.beans));
this.createManagedBean(new ManagedFocusFeature(
eGui,
{
shouldStopEventPropagation: e => this.shouldStopEventPropagation(e),
onTabKeyDown: ()=> null,
handleKeyDown: this.handleKeyDown.bind(this),
onFocusIn: this.onFocusIn.bind(this),
onFocusOut: this.onFocusOut.bind(this)
}
));
this.addManagedListener(this.eventService, Events.EVENT_NEW_COLUMNS_LOADED, this.onNewColumnsLoaded.bind(this));
this.addManagedListener(this.eventService, Events.EVENT_COLUMN_VALUE_CHANGED, this.onColumnValueChanged.bind(this));
this.addManagedListener(this.eventService, Events.EVENT_COLUMN_ROW_GROUP_CHANGED, this.onColumnRowGroupChanged.bind(this));
this.addManagedListener(this.eventService, Events.EVENT_COLUMN_PIVOT_CHANGED, this.onColumnPivotChanged.bind(this));
}
private setupUserComp(): void {
const compDetails = this.lookupUserCompDetails();
this.setCompDetails(compDetails);
}
private setCompDetails(compDetails: UserCompDetails): void {
this.userCompDetails = compDetails;
this.comp.setUserCompDetails(compDetails);
}
private lookupUserCompDetails(): UserCompDetails {
const params = this.createParams();
const colDef = this.column.getColDef();
return this.userComponentFactory.getHeaderCompDetails(colDef, params)!;
}
private createParams(): IHeaderParams {
const colDef = this.column.getColDef();
const params = {
column: this.column,
displayName: this.displayName,
enableSorting: colDef.sortable,
enableMenu: this.menuEnabled,
showColumnMenu: (source: HTMLElement) => {
this.gridApi.showColumnMenuAfterButtonClick(this.column, source);
},
progressSort: (multiSort?: boolean) => {
this.sortController.progressSort(this.column, !!multiSort, "uiColumnSorted");
},
setSort: (sort: string, multiSort?: boolean) => {
this.sortController.setSortForColumn(this.column, sort, !!multiSort, "uiColumnSorted");
},
api: this.gridApi,
columnApi: this.columnApi,
context: this.gridOptionsWrapper.getContext(),
eGridHeader: this.getGui()
} as IHeaderParams;
return params;
}
private setupSelectAll(): void {
this.selectAllFeature = this.createManagedBean(new SelectAllFeature(this.column));
this.selectAllFeature.setComp(this.comp);
}
public getSelectAllGui(): HTMLElement {
return this.selectAllFeature.getCheckboxGui();
}
protected handleKeyDown(e: KeyboardEvent): void {
if (e.keyCode === KeyCode.SPACE) {
this.selectAllFeature.onSpaceKeyPressed(e);
}
if (e.keyCode === KeyCode.ENTER) {
this.onEnterKeyPressed(e);
}
}
private onEnterKeyPressed(e: KeyboardEvent): void {
/// THIS IS BAD - we are assuming the header is not a user provided comp
const headerComp = this.comp.getUserCompInstance() as HeaderComp;
if (!headerComp) { return; }
if (e.ctrlKey || e.metaKey) {
if (this.menuEnabled && headerComp.showMenu) {
e.preventDefault();
headerComp.showMenu();
}
} else if (this.sortable) {
const multiSort = e.shiftKey;
this.sortController.progressSort(this.column, multiSort, "uiColumnSorted");
}
}
public isMenuEnabled(): boolean {
return this.menuEnabled;
}
protected onFocusIn(e: FocusEvent) {
if (!this.getGui().contains(e.relatedTarget as HTMLElement)) {
const rowIndex = this.getRowIndex();
this.focusService.setFocusedHeader(rowIndex, this.column);
}
this.setActiveHeader(true);
}
protected onFocusOut(e: FocusEvent) {
if (
this.getGui().contains(e.relatedTarget as HTMLElement)
) { return; }
this.setActiveHeader(false);
}
private setupTooltip(): void {
const tooltipCtrl: ITooltipFeatureCtrl = {
getColumn: ()=> this.column,
getColDef: ()=> this.column.getColDef(),
getGui: ()=> this.eGui,
getLocation: ()=> 'header',
getTooltipValue: () => {
const res = this.column.getColDef().headerTooltip;
return res;
},
};
const tooltipFeature = this.createManagedBean(new TooltipFeature(tooltipCtrl, this.beans));
tooltipFeature.setComp(this.comp);
this.refreshFunctions.push( ()=> tooltipFeature.refreshToolTip() );
}
private setupClassesFromColDef(): void {
const refreshHeaderClasses = () => {
const colDef = this.column.getColDef();
const goa = this.gridOptionsWrapper;
const classes = CssClassApplier.getHeaderClassesFromColDef(colDef, goa, this.column, null);
const oldClasses = this.userHeaderClasses;
this.userHeaderClasses = new Set(classes);
classes.forEach( c => {
if (oldClasses.has(c)) {
// class already added, no need to apply it, but remove from old set
oldClasses.delete(c);
} else {
// class new since last time, so apply it
this.comp.addOrRemoveCssClass(c, true);
}
});
// now old set only has classes that were applied last time, but not this time, so remove them
oldClasses.forEach(c => this.comp.addOrRemoveCssClass(c, false))
};
this.refreshFunctions.push(refreshHeaderClasses);
refreshHeaderClasses();
}
public getGui(): HTMLElement {
return this.eGui;
}
public setDragSource(eSource: HTMLElement | undefined): void {
this.dragSourceElement = eSource;
this.removeDragSource();
if (!eSource) { return; }
if (!this.draggable) { return; }
this.moveDragSource = {
type: DragSourceType.HeaderCell,
eElement: eSource,
defaultIconName: DragAndDropService.ICON_HIDE,
getDragItem: () => this.createDragItem(),
dragItemName: this.displayName,
onDragStarted: () => this.column.setMoving(true, "uiColumnMoved"),
onDragStopped: () => this.column.setMoving(false, "uiColumnMoved")
};
this.dragAndDropService.addDragSource(this.moveDragSource, true);
}
private createDragItem(): DragItem {
const visibleState: { [key: string]: boolean; } = {};
visibleState[this.column.getId()] = this.column.isVisible();
return {
columns: [this.column],
visibleState: visibleState
};
}
@PreDestroy
public removeDragSource(): void {
if (this.moveDragSource) {
this.dragAndDropService.removeDragSource(this.moveDragSource);
this.moveDragSource = undefined;
}
}
private onNewColumnsLoaded(): void {
const colDefVersionNow = this.columnModel.getColDefVersion();
if (colDefVersionNow != this.colDefVersion) {
this.colDefVersion = colDefVersionNow;
this.refresh();
}
}
private updateState(): void {
const colDef = this.column.getColDef();
this.menuEnabled = this.menuFactory.isMenuEnabled(this.column) && !colDef.suppressMenu;
this.sortable = colDef.sortable;
this.displayName = this.calculateDisplayName();
this.draggable = this.workOutDraggable();
}
public addRefreshFunction(func: ()=>void): void {
this.refreshFunctions.push(func);
}
private refresh(): void {
this.updateState();
this.refreshHeaderComp();
this.refreshFunctions.forEach(f => f());
}
private refreshHeaderComp(): void {
const newCompDetails = this.lookupUserCompDetails();
const compInstance = this.comp.getUserCompInstance();
// only try refresh if old comp exists adn it is the correct type
const attemptRefresh = compInstance!=null && this.userCompDetails.componentClass == newCompDetails.componentClass;
const headerCompRefreshed = attemptRefresh ? this.attemptHeaderCompRefresh(newCompDetails.params) : false;
if (headerCompRefreshed) {
// we do this as a refresh happens after colDefs change, and it's possible the column has had it's
// draggable property toggled. no need to call this if not refreshing, as setDragSource is done
// as part of appendHeaderComp
this.setDragSource(this.dragSourceElement);
} else {
this.setCompDetails(newCompDetails);
}
}
public attemptHeaderCompRefresh(params: IHeaderParams): boolean {
const headerComp = this.comp.getUserCompInstance();
if (!headerComp) { return false; }
// if no refresh method, then we want to replace the headerComp
if (!headerComp.refresh) { return false; }
const res = headerComp.refresh(params);
return res;
}
private calculateDisplayName(): string | null {
return this.columnModel.getDisplayNameForColumn(this.column, 'header', true);
}
private checkDisplayName(): void {
// display name can change if aggFunc different, eg sum(Gold) is now max(Gold)
if (this.displayName !== this.calculateDisplayName()) {
this.refresh();
}
}
private workOutDraggable(): boolean {
const colDef = this.column.getColDef();
const isSuppressMovableColumns = this.gridOptionsWrapper.isSuppressMovableColumns();
const colCanMove = !isSuppressMovableColumns && !colDef.suppressMovable && !colDef.lockPosition;
// we should still be allowed drag the column, even if it can't be moved, if the column
// can be dragged to a rowGroup or pivot drop zone
return !!colCanMove || !!colDef.enableRowGroup || !!colDef.enablePivot;
}
private onColumnRowGroupChanged(): void {
this.checkDisplayName();
}
private onColumnPivotChanged(): void {
this.checkDisplayName();
}
private onColumnValueChanged(): void {
this.checkDisplayName();
}
private setupWidth(): void {
const listener = () => {
this.comp.setWidth(this.column.getActualWidth() + 'px');
};
this.addManagedListener(this.column, Column.EVENT_WIDTH_CHANGED, listener);
listener();
}
private setupMovingCss(): void {
const listener = ()=> {
// this is what makes the header go dark when it is been moved (gives impression to
// user that the column was picked up).
this.comp.addOrRemoveCssClass('ag-header-cell-moving', this.column.isMoving());
};
this.addManagedListener(this.column, Column.EVENT_MOVING_CHANGED, listener);
listener();
}
private setupMenuClass(): void {
const listener = ()=> {
this.comp.addOrRemoveCssClass('ag-column-menu-visible', this.column.isMenuVisible());
};
this.addManagedListener(this.column, Column.EVENT_MENU_VISIBLE_CHANGED, listener);
listener();
}
private setupSortableClass(): void {
const updateSortableCssClass = () => {
this.comp.addOrRemoveCssClass('ag-header-cell-sortable', !!this.sortable);
};
const updateAriaSort = () => {
if (this.sortable) {
this.comp.setAriaSort(getAriaSortState(this.column));
} else {
this.comp.setAriaSort(undefined);
}
};
updateSortableCssClass();
updateAriaSort();
this.addRefreshFunction(updateSortableCssClass);
this.addRefreshFunction(updateAriaSort);
this.addManagedListener(this.column, Column.EVENT_SORT_CHANGED, updateAriaSort);
}
private addColumnHoverListener(): void {
const listener = ()=> {
if (!this.gridOptionsWrapper.isColumnHoverHighlight()) { return; }
const isHovered = this.columnHoverService.isHovered(this.column);
this.comp.addOrRemoveCssClass('ag-column-hover', isHovered);
};
this.addManagedListener(this.eventService, Events.EVENT_COLUMN_HOVER_CHANGED, listener);
listener();
}
private setupFilterCss(): void {
const listener = ()=> {
this.comp.addOrRemoveCssClass('ag-header-cell-filtered', this.column.isFilterActive());
};
this.addManagedListener(this.column, Column.EVENT_FILTER_ACTIVE_CHANGED, listener);
listener();
}
private setupColId(): void {
this.comp.setColId(this.column.getColId());
}
private addActiveHeaderMouseListeners(): void {
const listener = (e: MouseEvent) => this.setActiveHeader(e.type === 'mouseenter');
this.addManagedListener(this.getGui(), 'mouseenter', listener);
this.addManagedListener(this.getGui(), 'mouseleave', listener);
}
private setActiveHeader(active: boolean): void {
this.comp.addOrRemoveCssClass('ag-header-active', active);
}
} | the_stack |
import { browser, $, ExpectedConditions as EC } from 'protractor';
import { fakeServer } from './helpers/fake_server';
import {
expectCountElements,
waitForElement,
waitForSpinners
} from './helpers/browser_expectations';
describe('Admin pages', () => {
describe('User Management', () => {
beforeEach(() => {
fakeServer()
.get('/apis/iam/v2/introspect')
.many()
.reply(200, JSON.stringify(
{
endpoints: {
'/apis/iam/v2/users': {
get: true,
put: false,
post: true,
delete: false,
patch: false
}
}
}
));
fakeServer()
.get('/apis/iam/v2/users')
.many()
.reply(200, JSON.stringify(
{
users: [
{
id: 'admin',
name: 'Local Administrator',
membership_id: '38d792f7-85b4-4127-9c4e-110118e3cca4'
}
]
}
));
browser.waitForAngularEnabled(false);
browser.get('/settings/users');
});
it('displays heading', () => {
const heading = $('chef-heading');
browser.wait(EC.textToBePresentInElement(heading, 'Users'), 5000);
});
it('displays users table', () => {
expectCountElements('chef-table chef-thead chef-tr', 1);
// one row for the admin user in the table body
expectCountElements('chef-table chef-tbody chef-tr', 1);
});
it('displays create user button', () => {
const addButton = $('.page-body chef-button');
browser.wait(EC.textToBePresentInElement(addButton, 'Create User'), 5000);
});
it('displays the returned user info', () => {
const fullname = $('chef-table chef-tbody chef-tr chef-td:first-child a');
browser.wait(EC.textToBePresentInElement(fullname, 'Local Administrator'), 5000);
const username = $('chef-table chef-tbody chef-tr chef-td:nth-child(2)');
browser.wait(EC.textToBePresentInElement(username, 'admin'), 5000);
});
describe('control button', () => {
it('is displayed', () => {
waitForElement('chef-table chef-tbody chef-tr mat-select')
.then((e) => {
expect(e.isDisplayed()).toBeTruthy();
});
});
['Delete User'].forEach((item, index) => {
it(`when clicked, shows ${item}`, () => {
const menuTrigger = $('chef-table chef-tbody chef-tr mat-select .mat-select-trigger');
browser.wait(EC.elementToBeClickable(menuTrigger), 5000).then(() => {
menuTrigger.click().then(() => {
const dropDownOption = $(`.chef-control-menu mat-option:nth-child(${index + 1}`);
const dropDownOpened = () => dropDownOption.getText().then(val => val === item);
browser.wait(dropDownOpened, 100, 'Control options should render.');
});
});
});
});
});
});
describe('Policies list', () => {
beforeEach(() => {
fakeServer()
.get('/apis/iam/v2/introspect')
.many()
.reply(200, JSON.stringify(
{
endpoints: {
'/apis/iam/v2/policies': {
get: true,
put: false,
post: true,
delete: false,
patch: false
}
}
}
));
fakeServer()
.get('/apis/iam/v2/policies')
.many()
.reply(200, JSON.stringify(
{
policies: [
{
id: 'some-policy-id',
name: 'Some policy whose name does not start with A',
members: [],
type: 'CUSTOM',
statements: [
{ effect: 'ALLOW', role: 'some-role', resources: ['*'], projects: [] }
],
projects: []
},
{
id: 'chef-managed-administrator',
name: 'Administrator All Access',
members: ['team:local:admins'],
statements: [
{ effect: 'ALLOW', actions: ['*'], resources: ['*'], projects: [] }
],
type: 'CHEF_MANAGED',
projects: []
}
]
}
));
browser.waitForAngularEnabled(false);
browser.get('/settings/policies');
});
it('displays heading', () => {
waitForElement('chef-heading').then((heading) => {
expect(heading.getText()).toBe('Policies');
});
});
it('displays policy list component', () => {
waitForElement('app-policy-list').then((policyList) => {
expect(policyList).not.toBeNull();
});
});
describe('displays the alphabetically sorted policies', () => {
it('first policy', () => {
waitForElement('app-policy-list chef-table chef-tr:nth-child(1) chef-td:first-child a')
.then((name) => {
expect(name.getText()).toBe('Administrator All Access');
});
waitForElement('chef-table chef-tr:nth-child(1) chef-td:nth-child(2)')
.then((id) => {
expect(id.getText()).toBe('chef-managed-administrator');
});
waitForElement('chef-table chef-tr:nth-child(1) chef-td:nth-child(3)')
.then((policyType) => {
expect(policyType.getText()).toBe('Chef-managed');
});
waitForElement('app-policy-list chef-table chef-tr:nth-child(1) chef-td:nth-child(4)')
.then((members) => {
expect(members.getText()).toBe('In use');
});
});
it('second policy', () => {
waitForElement('app-policy-list chef-table chef-tr:nth-child(2) chef-td:first-child a')
.then(name => {
expect(name.getText()).toBe('Some policy whose name does not start with A');
});
waitForElement('chef-table chef-tr:nth-child(2) chef-td:nth-child(2)')
.then((id) => {
expect(id.getText()).toBe('some-policy-id');
});
waitForElement('chef-table chef-tr:nth-child(2) chef-td:nth-child(3)')
.then(policyType => {
expect(policyType.getText()).toBe('Custom');
});
waitForElement('app-policy-list chef-table chef-tr:nth-child(2) chef-td:nth-child(4)')
.then(members => {
expect(members.getText()).toBe('No members');
});
});
});
describe('control menu', () => {
it('is not displayed for chef-managed policies', () => {
// admin policy row
expect(
$('chef-table chef-tbody chef-tr:nth-child(1) mat-select')
.isPresent()).toBeFalsy();
});
it('is displayed for custom policies', () => {
// custom policy row
waitForElement('chef-table chef-tbody chef-tr:nth-child(2) mat-select')
.then(controlButton => {
expect(controlButton.isPresent()).toBeTruthy();
});
});
['Delete Policy'].forEach((item, index) => {
it(`when clicked, shows ${item}`, () => {
waitForElement(
'chef-table chef-tbody chef-tr:nth-child(2) mat-select .mat-select-trigger')
.then(controlButton => {
browser.wait(EC.elementToBeClickable(controlButton));
controlButton.click().then(() => {
const dropDownOption = $(`.chef-control-menu mat-option:nth-child(${index + 1}`);
const dropDownOpened = () => dropDownOption.getText()
.then(val => val === item);
browser.wait(dropDownOpened, 100, 'Control options should render.');
});
});
});
});
it('after delete clicked, policy removed from list once', () => {
fakeServer()
.delete('/apis/iam/v2/policies/some-policy-id')
.many()
.reply(200);
waitForElement('chef-table chef-tbody chef-tr:nth-child(2)')
.then(somePolicy => {
// open control menu
const controlButton = somePolicy.$('mat-select .mat-select-trigger');
browser.wait(EC.elementToBeClickable(controlButton));
controlButton.click().then(() => {
// select Delete Policy
const deleteOption = $('.chef-control-menu mat-option:nth-child(1)');
browser.wait(EC.visibilityOf(deleteOption), 5000, 'Delete option should render');
deleteOption.click();
const deleteModal = $('app-delete-object-modal');
browser.wait(EC.visibilityOf(deleteModal), 5000, 'Delete confirm modal should render');
// confirm
deleteModal.$('chef-button:first-child button').click();
browser.wait(EC.not(EC.presenceOf(somePolicy)), 5000, 'Deleted policy should be gone');
});
});
});
});
});
describe('Policy details', () => {
beforeEach(() => {
fakeServer()
.get('/apis/iam/v2/policies/some-test-policy')
.many()
.reply(200, JSON.stringify(
{
policy:
{
id: 'some-test-policy',
name: 'All access policy',
members: ['team:local:admins'],
type: 'CHEF_MANAGED',
statements: [
{ effect: 'ALLOW', role: 'some-role', resources: ['*'], projects: [] }
],
projects: []
}
}
));
browser.waitForAngularEnabled(false);
browser.get('/settings/policies/some-test-policy');
});
describe('policy details', () => {
it('displays heading', () => {
waitForElement('chef-heading').then(heading => {
expect(heading.getText()).toBe('All access policy');
});
});
it('displays the id in the header', () => {
waitForElement('header td:nth-child(1)').then(idHeader => {
expect(idHeader.getText()).toBe('some-test-policy');
});
});
it('displays the type in the header', () => {
waitForElement('header td:nth-child(2)').then(typeHeader => {
expect(typeHeader.getText()).toBe('Chef-managed');
});
});
it('renders the json', () => {
waitForElement('chef-snippet pre').then(policyJSON => {
expect(policyJSON).not.toBeNull();
});
});
});
});
describe('Roles list', () => {
beforeEach(() => {
fakeServer()
.get('/apis/iam/v2/introspect')
.many()
.reply(200, JSON.stringify(
{
endpoints: {
'/apis/iam/v2/roles': {
get: true,
put: false,
post: true,
delete: false,
patch: false
}
}
}
));
fakeServer()
.get('/apis/iam/v2/roles')
.many()
.reply(200, JSON.stringify(
{
roles: [
{
id: '514c7547-e858-4b3c-a48f-2448320aeea5',
name: 'Some role whose name does not start with A',
actions: [],
type: 'CUSTOM'
},
{
id: 'c4a60965-95f7-44f3-b21d-0b27e478c0cc',
name: 'Owner',
actions: ['secrets:*'],
type: 'CHEF_MANAGED'
}
]
}
));
browser.waitForAngularEnabled(false);
browser.get('/settings/roles');
});
it('displays heading', () => {
const heading = $('chef-heading');
expect(heading.getText()).toBe('Roles');
});
it('displays role list component', () => {
const rolesList = $('app-roles-list');
expect(rolesList).not.toBeNull();
});
describe('displays the alphabetically sorted first role with name and type', () => {
it('first role', () => {
const name = $('app-roles-list chef-table chef-tr:nth-child(1) chef-td:first-child a');
browser.wait(EC.textToBePresentInElement(name, 'Owner'));
const policyType = $('chef-table chef-tr:nth-child(1) chef-td:nth-child(3)');
browser.wait(EC.textToBePresentInElement(policyType, 'Chef-managed'));
});
it('second role', () => {
const name = $('app-roles-list chef-table chef-tr:nth-child(2) chef-td:first-child a');
browser.wait(EC.textToBePresentInElement(name,
'Some role whose name does not start with A'));
const policyType = $('chef-table chef-tr:nth-child(2) chef-td:nth-child(3)');
browser.wait(EC.textToBePresentInElement(policyType, 'Custom'));
});
});
});
describe('Role details', () => {
beforeEach(() => {
fakeServer()
.get('/apis/iam/v2/roles/some-test-role')
.many()
.reply(200, JSON.stringify(
{
role: {
id: 'some-test-role',
name: 'Owner',
actions: ['secrets:*', 'other:*'],
type: 'CHEF_MANAGED'
}
}
));
browser.waitForAngularEnabled(false);
browser.get('/settings/roles/some-test-role');
});
describe('Role details', () => {
it('displays heading', () => {
const heading = $('chef-heading');
expect(heading.getText()).toBe('Owner');
});
it('displays the id in the header', () => {
const idHeader = $('header td:nth-child(1)');
expect(idHeader.getText()).toBe('some-test-role');
});
it('displays the type in the header', () => {
const typeHeader = $('header td:nth-child(2)');
expect(typeHeader.getText()).toBe('Chef-managed');
});
it('renders the json', () => {
const rolesList = $('chef-snippet pre');
expect(rolesList).not.toBeNull();
});
});
});
describe('Projects list', () => {
beforeEach(() => {
fakeServer()
.get('/apis/iam/v2/introspect')
.any()
.reply(200, JSON.stringify(
{
endpoints: {
'/apis/iam/v2/projects': {
get: true,
put: false,
post: true,
delete: false,
patch: false
}
}
}
));
fakeServer()
.get('/apis/iam/v2/projects')
.any()
.reply(200, JSON.stringify(
{
projects: [
{
id: 'project-9',
name: 'Some project whose name does not start with A',
type: 'CUSTOM'
},
{
id: 'default',
name: 'Default Project',
type: 'CHEF_MANAGED'
},
{
id: 'project-19',
name: 'This is custom, and authz allows deletion',
type: 'CUSTOM'
}
]
}
));
// mock up app-authorized responses
[
['project-9', false],
['default', false],
['project-19', true]
].forEach(([id, deletable]) => {
const path = `/apis/iam/v2/projects/${id}`;
const endpoints = {
[path]: {
get: true,
put: false,
post: true,
delete: deletable,
patch: false
}
};
fakeServer()
.post('/apis/iam/v2/introspect', JSON.stringify(
{
path,
parameters: []
}
))
.any()
.reply(200, JSON.stringify({ endpoints }));
});
browser.waitForAngularEnabled(false);
browser.get('/settings/projects');
});
it('displays heading', () => {
const heading = $('chef-heading');
browser.wait(EC.visibilityOf(heading), 5000, 'chef-heading should render');
expect(heading.getText()).toBe('Projects');
});
it('displays project list component', () => {
const projectsList = $('app-project-list');
browser.wait(EC.visibilityOf(projectsList), 5000, 'project list should render');
expect(projectsList).not.toBeNull();
});
describe('displays the first project (cannot be deleted and is chef-managed)', () => {
it('shows name and id', () => {
const name = $(
'app-project-list chef-table chef-tbody chef-tr:nth-child(1) chef-td:nth-child(1) a');
browser.wait(EC.visibilityOf(name), 5000, 'first project should render');
expect(name.getText()).toBe('Default Project');
expect(name.getAttribute('href')).toMatch(/\/settings\/projects\/default$/);
const projectID = $(
'app-project-list chef-table chef-tbody chef-tr:nth-child(1) chef-td:nth-child(2)');
expect(projectID.getText()).toBe('default');
});
it('does not show the control button', () => {
const controlButton = $(
'app-project-list chef-table chef-tbody chef-tr:nth-child(1) ' +
'chef-td:nth-child(5) mat-select');
expect(controlButton.isPresent()).toEqual(false);
});
});
describe('displays the second project (cannot be deleted, custom)', () => {
it('shows name and id', () => {
const name = $(
'app-project-list chef-table chef-tbody chef-tr:nth-child(2) chef-td:nth-child(1) a');
browser.wait(EC.visibilityOf(name), 5000, 'second project should render');
expect(name.getText()).toBe('Some project whose name does not start with A');
expect(name.getAttribute('href')).toMatch(/\/settings\/projects\/project-9$/);
const projectID = $(
'app-project-list chef-table chef-tbody chef-tr:nth-child(2) chef-td:nth-child(2)');
expect(projectID.getText()).toBe('project-9');
});
it('does not show the control button', () => {
const controlButton = $(
'app-project-list chef-table chef-tbody chef-tr:nth-child(2) ' +
'chef-td:nth-child(5) mat-select');
expect(controlButton.isPresent()).toEqual(false);
});
});
describe('displays the third project (can be deleted, custom)', () => {
it('shows name and id', () => {
const name = $(
'app-project-list chef-table chef-tbody chef-tr:nth-child(3) chef-td:nth-child(1) a');
browser.wait(EC.visibilityOf(name), 5000, 'third project should render');
expect(name.getText()).toBe('This is custom, and authz allows deletion');
const projectID = $(
'app-project-list chef-table chef-tbody chef-tr:nth-child(3) chef-td:nth-child(2)');
expect(projectID.getText()).toBe('project-19');
});
it('shows the control button', () => {
waitForElement('app-project-list chef-table chef-tbody chef-tr:nth-child(3) ' +
'chef-td:nth-child(4) mat-select').then(controlButton => {
expect(controlButton.isPresent()).toBeTruthy();
['Delete Project'].forEach((item, index) => {
it(`when clicked, shows ${item}`, () => {
$('app-project-list chef-table chef-tbody chef-tr:nth-child(2) ' +
'chef-td:nth-child(3) mat-select .mat-select-trigger').
click();
const dropDownOption = $(`.chef-control-menu mat-option:nth-child(${index + 1})`);
const dropDownOpened = () => dropDownOption.getText().then(val => val === item);
browser.wait(dropDownOpened, 5000, 'Control options should render.');
});
});
});
});
it('after delete is clicked and if the backend call succeeds, ' +
'project is removed from list', () => {
fakeServer()
.delete('/apis/iam/v2/projects/project-19')
.min(1).max(1)
.reply(200);
waitForElement('app-project-list chef-table chef-tbody chef-tr:nth-child(3)')
.then(third => {
browser.wait(EC.presenceOf(third.$('mat-select'))).then(() => {
const controlButton = third.$('mat-select .mat-select-trigger');
browser.wait(EC.elementToBeClickable(controlButton));
controlButton.click().then(() => {
// select Delete Project
const deleteOption = $('.chef-control-menu mat-option:nth-child(1)');
browser.wait(EC.visibilityOf(deleteOption), 5000,
'Delete option should render');
deleteOption.click();
// confirm Delete in modal
const deleteModal = $('app-delete-object-modal');
browser.wait(EC.presenceOf(deleteModal), 5000,
'Delete confirm modal should appear');
// confirm
deleteModal.$('chef-button:first-child button').click();
browser.wait(EC.not(EC.presenceOf(third)), 5000, 'third row should disappear');
});
});
});
});
});
});
describe('Project details (custom)', () => {
beforeEach(() => {
fakeServer()
.get('/apis/iam/v2/projects/my-project')
.any()
.reply(200, JSON.stringify(
{
project: {
id: 'my-project',
name: 'My Project',
type: 'CUSTOM'
}
}
));
fakeServer()
.get('/apis/iam/v2/projects/my-project/rules')
.any()
.reply(200, JSON.stringify(
{
rules: [],
status: 'NO_RULES'
}
));
browser.waitForAngularEnabled(false);
browser.get('/settings/projects/my-project');
});
describe('project details', () => {
it('displays heading', () => {
waitForElement('chef-heading').then(heading => {
expect(heading.getText()).toBe('My Project');
});
});
it('displays the id in the header', () => {
waitForElement('header td:nth-child(1)').then(idHeader => {
expect(idHeader.getText()).toBe('my-project');
});
});
describe('before any typing occurs', () => {
it('displays the project name in the input and the save button is disabled', () => {
waitForSpinners().then(() => {
const detailsLink = $('#chef-option2');
detailsLink.click().then(() => {
const projectNameInput = $('app-project-details section form chef-form-field input');
expect(projectNameInput.getAttribute('value')).toBe('My Project');
const projectSaveButton = $('app-project-details section #button-bar button');
expect(projectSaveButton.getAttribute('disabled')).toBe('true');
});
});
});
});
describe('when the input value is changed to something new and saved', () => {
beforeEach(() => {
fakeServer()
.put('/apis/iam/v2/projects/my-project',
JSON.stringify({ name: 'My Project Changed' }))
.many()
.reply(200, JSON.stringify(
{
project: {
id: 'my-project',
name: 'My Project Changed',
type: 'CUSTOM'
}
}
));
browser.waitForAngularEnabled(false);
browser.get('/settings/projects/my-project');
});
it('enables the save button, updates the project, and notes the save, ' +
'and then removes note once more typing occurs', () => {
waitForSpinners().then(() => {
const detailsLink = $('#chef-option2');
detailsLink.click().then(() => {
const projectSaveButton = $('app-project-details section #button-bar button');
const projectNameInput = $(
'app-project-details section form chef-form-field input');
expect(projectSaveButton.getAttribute('disabled')).toBe('true');
browser.wait(EC.elementToBeClickable(projectNameInput), 5000).then(() => {
expect(projectNameInput.getAttribute('disabled')).toBeNull();
projectNameInput.sendKeys(' Changed');
expect(projectNameInput.getAttribute('value')).toBe('My Project Changed');
expect(projectSaveButton.getAttribute('disabled')).toBeNull();
// Save the project
$('app-project-details section #button-bar chef-button').click();
const heading = $('chef-heading');
browser.wait(EC.textToBePresentInElement(heading, 'My Project Changed'), 5000);
expect(heading.getText()).toBe('My Project Changed');
expect(projectSaveButton.getAttribute('disabled')).toBe('true');
expect($('app-project-details section #button-bar #saved-note').getText())
.toBe('All changes saved.');
browser.wait(EC.elementToBeClickable(projectNameInput), 5000);
// Type once more
projectNameInput.sendKeys(' Once More');
expect(projectSaveButton.getAttribute('disabled')).toBeNull();
// Removed save note
expect($('app-project-details section #button-bar #saved-note').
isPresent()).toBeFalsy();
});
});
});
});
});
});
});
}); | the_stack |
import {ControllableChar} from "./ControllableChar";
import {GoldenSun} from "./GoldenSun";
import {Map as GameMap} from "./Map";
import * as numbers from "./magic_numbers";
import {range_360, base_actions, get_direction_mask, directions, get_tile_position} from "./utils";
import * as turf from "@turf/turf";
import {LocationKey} from "./tile_events/TileEvent";
/**
* This class manages collision between the main concepts of the engine:
* map, hero, npcs and interactable objects.
*/
export class Collision {
private static readonly SPEED_LIMIT_TO_STOP = 13;
private static readonly SPEED_LIMIT_TO_STOP_WORLD_MAP = 9;
private static readonly MINIMAL_SLOPE = 0.1;
/** This variable converts from normal_angle region (floor((angle-15)/30)) to in-game rotation. */
private static readonly ROTATION_NORMAL = [
directions.right, //345-15 degrees
directions.up_right, //15-45 degrees
directions.up_right, //45-75 degrees
directions.up, //75-105 degrees
directions.up_left, //105-135 degrees
directions.up_left, //135-165 degrees
directions.left, //165-195 degrees
directions.down_left, //195-225 degrees
directions.down_left, //225-255 degrees
directions.down, //255-285 degrees
directions.down_right, //285-315 degrees
directions.down_right, //315-345 degrees
];
private game: Phaser.Game;
private data: GoldenSun;
private _hero_collision_group: Phaser.Physics.P2.CollisionGroup;
private _dynamic_events_collision_group: Phaser.Physics.P2.CollisionGroup;
private _map_collision_group: Phaser.Physics.P2.CollisionGroup;
private _npc_collision_groups: {[layer_index: number]: Phaser.Physics.P2.CollisionGroup};
private _interactable_objs_collision_groups: {[layer_index: number]: Phaser.Physics.P2.CollisionGroup};
private max_layers_created: number;
constructor(game: Phaser.Game, data: GoldenSun) {
this.game = game;
this.data = data;
this.config_world();
this._hero_collision_group = this.game.physics.p2.createCollisionGroup();
this._dynamic_events_collision_group = this.game.physics.p2.createCollisionGroup();
this._map_collision_group = game.physics.p2.createCollisionGroup();
this._npc_collision_groups = {};
this._interactable_objs_collision_groups = {};
this.max_layers_created = 0;
}
get hero_collision_group() {
return this._hero_collision_group;
}
get dynamic_events_collision_group() {
return this._dynamic_events_collision_group;
}
get map_collision_group() {
return this._map_collision_group;
}
get npc_collision_groups() {
return this._npc_collision_groups;
}
get interactable_objs_collision_groups() {
return this._interactable_objs_collision_groups;
}
/**
* Configs the world physics attributes.
*/
private config_world() {
this.game.physics.startSystem(Phaser.Physics.P2JS);
this.game.physics.p2.setImpactEvents(true);
this.game.physics.p2.world.defaultContactMaterial.restitution = 0;
this.game.physics.p2.world.defaultContactMaterial.relaxation = 8;
this.game.physics.p2.world.defaultContactMaterial.friction = 0;
this.game.physics.p2.world.defaultContactMaterial.contactSkinSize = 1e-3;
this.game.physics.p2.world.defaultContactMaterial.stiffness = 1e8;
this.game.physics.p2.world.applyDamping = false;
this.game.physics.p2.world.applyGravity = false;
this.game.physics.p2.world.applySpringForces = false;
this.game.physics.p2.restitution = 0;
}
/**
* Creates npcs and interactable objects collision groups.
* @param map the current map.
*/
config_collision_groups(map: GameMap) {
//p2 has a limit number of collision groups that can be created. Then, NPCs and I. Objs. groups will be created on demand.
for (let layer_index = this.max_layers_created; layer_index < map.collision_layers_number; ++layer_index) {
this._npc_collision_groups[layer_index] = this.game.physics.p2.createCollisionGroup();
this._interactable_objs_collision_groups[layer_index] = this.game.physics.p2.createCollisionGroup();
}
this.max_layers_created = Math.max(this.max_layers_created, map.collision_layers_number);
}
/**
* Disables collision between hero and npcs.
* @param collision_layer if given, disables only on this layer.
*/
disable_npc_collision(collision_layer?: number) {
if (collision_layer !== undefined && collision_layer in this._npc_collision_groups) {
this.data.hero.sprite.body.removeCollisionGroup(this._npc_collision_groups[collision_layer], true);
} else {
for (let collision_layer in this._npc_collision_groups) {
this.data.hero.sprite.body.removeCollisionGroup(this._npc_collision_groups[collision_layer], true);
}
}
}
/**
* Enables collision between hero and npcs.
* @param collision_layer if given, enables only on this layer.
*/
enable_npc_collision(collision_layer?: number) {
if (collision_layer !== undefined && collision_layer in this._npc_collision_groups) {
this.data.hero.sprite.body.collides(this._npc_collision_groups[collision_layer]);
} else {
for (let collision_layer in this._npc_collision_groups) {
this.data.hero.sprite.body.collides(this._npc_collision_groups[collision_layer]);
}
}
}
/**
* Disables collision between hero and map.
* @param sensor_method if true, disables collision by only setting the map shapes as a sensor.
*/
disable_map_collision(sensor_method = false) {
if (sensor_method) {
this.data.map.collision_sprite.body.data.shapes.forEach(shape => (shape.sensor = true));
} else {
this.data.hero.sprite.body.removeCollisionGroup(this.data.collision._map_collision_group);
this.data.map.collision_sprite.body.removeCollisionGroup(this.data.collision._hero_collision_group);
}
}
/**
* Enables collision between hero and map.
* @param sensor_method if true, enables collision by only setting the map shapes as not a sensor.
*/
enable_map_collision(sensor_method = false) {
if (sensor_method) {
this.data.map.collision_sprite.body.data.shapes.forEach(shape => (shape.sensor = false));
} else {
this.data.hero.sprite.body.collides(this.data.collision._map_collision_group);
this.data.map.collision_sprite.body.collides(this.data.collision._hero_collision_group);
}
}
/**
* Configs collisions between hero, map, npcs and interactable objects.
* @param collision_layer the current collision layer.
*/
config_collisions(collision_layer: number) {
this.data.hero.sprite.body.collides(this._map_collision_group);
this.data.map.collision_sprite.body.collides(this._hero_collision_group);
this.data.hero.sprite.body.collides(this._dynamic_events_collision_group);
this.disable_npc_collision();
this.enable_npc_collision(collision_layer);
for (let collide_index in this._interactable_objs_collision_groups) {
this.data.hero.sprite.body.removeCollisionGroup(
this._interactable_objs_collision_groups[collide_index],
true
);
}
if (collision_layer in this._interactable_objs_collision_groups) {
this.data.hero.sprite.body.collides(this._interactable_objs_collision_groups[collision_layer]);
}
}
/**
* Changes the map body according to a given collision layer index.
* @param new_collision_layer_index Target collision layer.
*/
change_map_body(new_collision_layer_index: number) {
if (this.data.map.collision_layer === new_collision_layer_index) {
return;
}
this.data.map.config_body(new_collision_layer_index);
this.data.hero.set_collision_layer(new_collision_layer_index);
this.config_collision_groups(this.data.map);
this.config_collisions(new_collision_layer_index);
this.data.map.config_layers(true);
}
/**
* This function checks whether is necessary to stop when colliding or change the char
* direction in order to adapt its movement to the collision slope.
*/
check_char_collision(char: ControllableChar) {
let normals = [];
for (let i = 0; i < this.game.physics.p2.world.narrowphase.contactEquations.length; ++i) {
const contact = this.game.physics.p2.world.narrowphase.contactEquations[i];
if (contact.bodyA === char.sprite.body.data) {
//check if char collided with something
normals.push(contact.normalA); //collision normals (one normal for each contact point)
}
char.check_interactable_objects(contact);
}
//normals having length, means that a collision is happening
char.colliding_directions_mask = normals.reduce((acc, normal) => {
const angle = range_360(Math.atan2(-normal[1], -normal[0]));
const direction = (1 + Math.floor((angle - numbers.degree45_half) / numbers.degree45)) & 7;
return acc | get_direction_mask(direction);
}, 0);
if (normals.length && char.in_movement()) {
const speed_limit = this.data.map.is_world_map
? Collision.SPEED_LIMIT_TO_STOP_WORLD_MAP
: Collision.SPEED_LIMIT_TO_STOP;
//speeds below SPEED_LIMIT_TO_STOP are not considered
if (
Math.abs(char.sprite.body.velocity.x) < speed_limit &&
Math.abs(char.sprite.body.velocity.y) < speed_limit
) {
//a contact point direction is the opposite direction of the contact normal vector
const contact_point_direction_angles = new Array(normals.length);
normals.forEach((normal, index) => {
const abs_normal_x = Math.abs(normal[0]);
const abs_normal_y = Math.abs(normal[1]);
//slopes outside the MINIMAL_SLOPE range will be desconsidered
if (abs_normal_x < Collision.MINIMAL_SLOPE) normal[0] = 0;
if (abs_normal_y < Collision.MINIMAL_SLOPE) normal[1] = 0;
if (abs_normal_x > 1 - Collision.MINIMAL_SLOPE) normal[0] = Math.sign(normal[0]);
if (abs_normal_y > 1 - Collision.MINIMAL_SLOPE) normal[1] = Math.sign(normal[1]);
//storing the angle as if it is in the 1st quadrant
contact_point_direction_angles[index] = range_360(Math.atan2(normal[1], -normal[0]));
});
//storing the angle as if it is in the 1st quadrant
const desired_direction_angle = range_360(Math.atan2(-char.temp_speed.y, char.temp_speed.x));
contact_point_direction_angles.forEach(direction => {
//check if the desired direction is going towards at least one contact direction with a error margin of 30 degrees
if (
direction >= desired_direction_angle - numbers.degree15 &&
direction <= desired_direction_angle + numbers.degree15
) {
//if true, it means that the char is going the in the direction of the collision obejct, then it must stop
char.set_temporary_speed(0, 0);
return;
}
});
char.stop_by_colliding = true;
char.force_direction = false;
} else if (char.current_action !== base_actions.CLIMB && char.current_action !== base_actions.ROPE) {
char.stop_by_colliding = false;
if (normals.length === 1) {
//Everything inside this if is to deal with direction changing when colliding.
//Finds which 30 degree sector the normal angle lies within, and converts to a direction.
const normal = normals[0];
const wall_direction =
Collision.ROTATION_NORMAL[
(range_360(Math.atan2(normal[1], -normal[0]) + numbers.degree15) / numbers.degree30) | 0
];
const relative_direction = (char.required_direction - wall_direction) & 7;
//if player's direction is within 1 of wall_direction
if (relative_direction === 1 || relative_direction === 7) {
char.force_direction = true;
const direction = (wall_direction + (relative_direction << 1)) & 7;
if ((direction & 1) === 1) {
//adapting the velocity to the contact slope
const going_up = (direction >> 1) & 2;
const is_ccw = going_up ? normal[0] >= 0 : normal[0] < 0;
//rotates normal vector 90deg
char.force_diagonal_speed.x = is_ccw ? normal[1] : -normal[1];
char.force_diagonal_speed.y = is_ccw ? -normal[0] : normal[0];
}
char.set_direction(direction);
} else {
char.force_direction = false;
}
} else {
char.force_direction = false;
}
} else {
char.stop_by_colliding = false;
}
} else {
char.stop_by_colliding = false;
char.force_direction = false;
}
}
/**
* Given a surface range, loop over the tiles in this range and find the intersection polygons for each tile.
* @param map the current map object.
* @param min_x the min x range in px.
* @param max_x the max x range in px.
* @param min_y the min y range in px.
* @param max_y the max y range in px.
* @param polygon The polygon. The first and last positions are equivalent, and they MUST contain identical values.
* @returns Returns a JS Map where its key is a location key and its value is the list of polygons for this location key.
*/
static get_polygon_tile_intersection(
map: GameMap,
min_x: number,
max_x: number,
min_y: number,
max_y: number,
polygon?: number[][]
) {
let turf_poly;
if (polygon === undefined) {
turf_poly = turf.polygon([
[
[min_x, min_y],
[max_x, min_y],
[max_x, max_y],
[min_x, max_y],
[min_x, min_y],
],
]);
} else {
turf_poly = turf.polygon([polygon]);
}
min_x = min_x - (min_x % map.tile_width);
max_x = max_x + map.tile_width - (max_x % map.tile_width);
min_y = min_y - (min_y % map.tile_height);
max_y = max_y + map.tile_height - (max_y % map.tile_height);
const intersections = new Map<number, number[][][]>();
for (let x = min_x; x < max_x; x += map.tile_width) {
for (let y = min_y; y < max_y; y += map.tile_height) {
const this_max_x = x + map.tile_width;
const this_max_y = y + map.tile_height;
const turf_tile_poly = turf.polygon([
[
[x, y],
[this_max_x, y],
[this_max_x, this_max_y],
[x, this_max_y],
[x, y],
],
]);
const intersection_poly = turf.intersect(turf_poly, turf_tile_poly);
if (intersection_poly) {
const tile_x = get_tile_position(x, map.tile_width);
const tile_y = get_tile_position(y, map.tile_height);
const location_key = LocationKey.get_key(tile_x, tile_y);
intersections.set(location_key, intersection_poly.geometry.coordinates as any);
}
}
}
return intersections;
}
} | the_stack |
import { FocusKeyManager } from '@angular/cdk/a11y';
import { SelectionModel } from '@angular/cdk/collections';
import {
AfterContentInit,
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChildren,
ElementRef,
EventEmitter,
Input,
NgZone,
OnDestroy,
OnInit,
Output,
QueryList,
ViewEncapsulation,
} from '@angular/core';
import { KEYS } from '@terminus/ngx-tools/keycodes';
import { untilComponentDestroyed } from '@terminus/ngx-tools/utilities';
import {
merge,
Observable,
} from 'rxjs';
import { startWith } from 'rxjs/operators';
import {
TsChipComponent,
TsChipEvent,
TsChipSelectionChange,
} from './chip.component';
// Increasing integer for generating unique ids for chip-collection components.
// @internal
let nextUniqueId = 0;
/**
* Possible orientations for {@link TsChipCollectionComponent}
*/
export type TsChipCollectionOrientation
= 'horizontal'
| 'vertical'
;
/**
* Change event object that is emitted when the chip collection value has changed.
*/
export class TsChipCollectionChange {
constructor(
// Chip collection that emitted the event
public source: TsChipCollectionComponent,
// Value of the chip collection when the event was emitted
public value: string[],
) { }
}
/**
* Component that is used to group {@link TsChipComponent} instances
*
* @example
* <ts-chip-collection
* [allowMultipleSelections]="true"
* aria-orientation="vertical"
* [isDisabled]="false"
* [isReadonly]="false"
* [isRemovable]="true"
* [isSelectable]="false"
* [orientation]="horizontal"
* [tabIndex]="1"
* [value]="myValue"
* (collectionChange)="collectionChange($event)"
* (removed)="chipRemoved($event)"
* (tabUpdateFocus)="tabFocusUpdated()"
* ></ts-chip-collection>
*
* <example-url>https://getterminus.github.io/ui-demos-release/components/chip</example-url>
*/
@Component({
selector: 'ts-chip-collection',
templateUrl: './chip-collection.component.html',
styleUrls: ['./chip-collection.component.scss'],
host: {
'class': 'ts-chip-collection',
'[class.ts-chip-collection--disabled]': 'isDisabled',
'[class.ts-chip-collection--vertical]': 'orientation === "vertical"',
'[class.ts-chip-collection--selectable]': 'isSelectable',
'[attr.tabindex]': 'isDisabled ? null : tabIndex',
'[attr.aria-describedby]': 'ariaDescribedby || null',
'[attr.aria-disabled]': 'isDisabled',
'[attr.aria-multiselectable]': 'allowMultipleSelections',
'[attr.aria-orientation]': 'ariaOrientation',
'[attr.aria-readonly]': 'isReadonly',
'[attr.aria-required]': 'false',
'[attr.aria-selectable]': 'isSelectable',
'[attr.role]': 'role',
'(focus)': 'focus()',
'(blur)': 'blur()',
'(keydown)': 'keydown($event)',
'[id]': 'id',
},
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
exportAs: 'tsChipCollection',
})
export class TsChipCollectionComponent implements OnInit, AfterViewInit, AfterContentInit, OnDestroy {
/**
* Uid of the chip collection
*/
protected uid = `ts-chip-collection-${nextUniqueId++}`;
/**
* The aria-describedby attribute on the chip collection for improved a11y.
*
* @internal
*/
public ariaDescribedby!: string;
/**
* User defined tab index.
*
* When it is not null, use user defined tab index. Otherwise use _tabIndex
*
* @internal
*/
public _userTabIndex: number | null = null;
/**
* When a chip is destroyed, we store the index of the destroyed chip until the chips
* query list notifies about the update. This is necessary because we cannot determine an
* appropriate chip that should receive focus until the array of chips updated completely.
*
* @internal
*/
public lastDestroyedChipIndex: number | null = null;
/**
* The FocusKeyManager which handles focus.
*
* @internal
*/
public keyManager!: FocusKeyManager<TsChipComponent>;
/**
* Manage selections
*
* @internal
*/
public selectionModel!: SelectionModel<TsChipComponent>;
/**
* Function when touched
*
* @internal
*/
public onTouched = () => { };
/**
* Function when changed
*
* @internal
*/
public onChange: (value: string[]) => void = () => { };
/**
* Combined stream of all of the child chips' selection change events.
*
* @internal
*/
public get chipSelectionChanges(): Observable<TsChipSelectionChange> {
// eslint-disable-next-line deprecation/deprecation
return merge(...this.chips.map(chip => chip.selectionChange));
}
/**
* Combined stream of all of the child chips' focus change events.
*
* @internal
*/
public get chipFocusChanges(): Observable<TsChipEvent> {
// eslint-disable-next-line deprecation/deprecation
return merge(...this.chips.map(chip => chip.onFocus));
}
/**
* Combined stream of all of the child chips' blur change events.
*
* @internal
*/
public get chipBlurChanges(): Observable<TsChipEvent> {
// eslint-disable-next-line deprecation/deprecation
return merge(...this.chips.map(chip => chip.blurred));
}
/**
* Combined stream of all of the child chips' remove change events.
*
* @internal
*/
public get chipDestroyChanges(): Observable<TsChipEvent> {
// eslint-disable-next-line deprecation/deprecation
return merge(...this.chips.map(chip => chip.destroyed));
}
/**
* Determine whether there is at least one chip in collection.
*/
public get empty(): boolean {
return this.chips && this.chips.length === 0;
}
/**
* Whether any chips has focus
*/
public get focused(): boolean {
return this.chips.some(chip => chip.hasFocus);
}
/**
* The ARIA role applied to the chip list
*/
public get role(): string | null {
return this._role;
}
private _role: string | null = null;
/**
* The chip components contained within this chip collection.
*/
@ContentChildren(TsChipComponent)
public chips!: QueryList<TsChipComponent>;
/**
* Whether the user should be allowed to select multiple chips.
*
* @param value
*/
@Input()
public set allowMultipleSelections(value: boolean) {
this._allowMultipleSelections = value;
this.syncChipsState();
}
public get allowMultipleSelections(): boolean {
return this._allowMultipleSelections;
}
private _allowMultipleSelections = false;
/**
* Orientation of the chip collection.
*/
@Input('aria-orientation')
public ariaOrientation: 'horizontal' | 'vertical' = 'horizontal';
/**
* Set and get chip collection id
*
* @param value
*/
@Input()
public set id(value: string) {
this._id = value || this.uid;
}
public get id(): string {
return this._id;
}
private _id: string = this.uid;
/**
* Get and set disable state
*
* @param value
*/
@Input()
public set isDisabled(value: boolean) {
this._disabled = value;
this.syncChipsState();
}
public get isDisabled(): boolean {
return this._disabled;
}
private _disabled = false;
/**
* Get and set readonly state
*
* @param value
*/
@Input()
public set isReadonly(value: boolean) {
this._readonly = value;
}
public get isReadonly(): boolean {
return this._readonly;
}
private _readonly = false;
/**
* Whether or not this chip collection is selectable. When a chip collection is not selectable,
* all the chips are not selectable.
*
* @param value
*/
@Input()
public set isSelectable(value: boolean) {
this._selectable = value;
this.syncChipsState();
}
public get isSelectable(): boolean {
return this._selectable;
}
private _selectable = true;
/**
* Orientation of the chip - either horizontal or vertical. Default to horizontal.
*/
@Input()
public orientation: TsChipCollectionOrientation = 'horizontal';
/**
* Set and get tabindex
*
* @param value
*/
@Input()
public set tabIndex(value: number) {
this._userTabIndex = value;
this._tabIndex = value;
}
public get tabIndex(): number {
return this._tabIndex;
}
private _tabIndex = 0;
/**
* Set and get chip collection value
*
* @param value
*/
@Input()
public set value(value: string[]) {
this._value = value;
}
public get value(): string[] {
return this._value;
}
private _value = [''];
/**
* Event emitted when the chip collection value has been changed by the user.
*/
@Output()
public readonly collectionChange = new EventEmitter<TsChipCollectionChange>();
/**
* Emitted when a chip is to be removed.
*/
@Output()
public readonly removed = new EventEmitter<TsChipEvent>();
/**
* Emitted when tab pressed with chip focused
*/
@Output()
public readonly tabUpdateFocus = new EventEmitter<void>();
constructor(
protected elementRef: ElementRef<HTMLElement>,
private changeDetectorRef: ChangeDetectorRef,
public zone: NgZone,
) {
zone.runOutsideAngular(() => {
this._role = this.empty ? null : 'listbox';
});
}
/**
* Initialize the selection model
*/
public ngOnInit(): void {
this.selectionModel = new SelectionModel<TsChipComponent>(this.allowMultipleSelections, undefined, false);
}
/**
* Initialize the key manager and listen for chip changes
*/
public ngAfterViewInit(): void {
this.keyManager = new FocusKeyManager<TsChipComponent>(this.chips)
.withWrap()
.withVerticalOrientation()
.withHorizontalOrientation('ltr');
this.keyManager.tabOut.pipe(untilComponentDestroyed(this)).subscribe(() => {
this.tabUpdateFocus.emit();
});
// When the collection changes, re-subscribe
// eslint-disable-next-line deprecation/deprecation
this.chips.changes.pipe(startWith<void, null>(null), untilComponentDestroyed(this)).subscribe(() => {
if (this.isDisabled || this.isReadonly) {
// Since this happens after the content has been checked, we need to defer it to the next tick.
Promise.resolve().then(() => {
this.syncChipsState();
});
}
this.resetChips();
// Check to see if we need to update our tab index
Promise.resolve().then(() => {
this.updateTabIndex();
});
// Check to see if we have a destroyed chip and need to refocus
this.updateFocusForDestroyedChips();
this.propagateChanges();
});
}
/**
* Trigger an initial sync after the content has loaded
*/
public ngAfterContentInit(): void {
Promise.resolve().then(() => {
this.syncChipsState();
});
}
/**
* Needed for untilComponentDestroyed
*/
public ngOnDestroy() { }
/**
* When blurred, mark the field as touched when focus moved outside the chip collection.
*/
public blur(): void {
// istanbul ignore else
if (!this.focused) {
this.keyManager.setActiveItem(-1);
}
}
/**
* Focuses the first non-disabled chip in this chip collection, or the associated input when there are no eligible chips.
*/
public focus(): void {
if (this.isDisabled) {
return;
}
// istanbul ignore else
if (this.chips.length > 0) {
this.keyManager.setFirstItemActive();
}
}
/**
* Pass events to the keyboard manager.
*
* @internal
*
* @param event - They KeyboardEvent
*/
public keydown(event: KeyboardEvent): void {
event.stopPropagation();
const target = event.target as HTMLElement;
const keyCode = event.code;
// If they are on an empty input and hit backspace, focus the last chip
if (keyCode === KEYS.BACKSPACE.code && TsChipCollectionComponent.isInputEmpty(target)) {
this.keyManager.setLastItemActive();
event.preventDefault();
} else if (target && target.classList.contains('ts-chip')) {
if (keyCode === KEYS.HOME.code) {
this.keyManager.setFirstItemActive();
event.preventDefault();
} else if (keyCode === KEYS.END.code) {
this.keyManager.setLastItemActive();
event.preventDefault();
} if (this.allowMultipleSelections && keyCode === KEYS.A.code && event.ctrlKey) {
// Select all with CTRL+A
const hasDeselectedChips = this.chips.some(chip => !chip.isDisabled && !chip.selected);
this.chips.forEach(chip => {
// istanbul ignore else
if (!chip.isDisabled) {
hasDeselectedChips ? chip.select() : chip.deselect();
}
});
event.preventDefault();
} else {
this.keyManager.onKeydown(event);
}
}
}
/**
* Utility to for whether input field is empty
*
* @param element - An HTMLElement
* @returns boolean
*/
private static isInputEmpty(element: HTMLElement): boolean {
if (element && element.nodeName.toLowerCase() === 'input') {
const input = element as HTMLInputElement;
return !input.value;
}
return false;
}
/**
* Check the tab index as you should not be allowed to focus an empty list.
*
* @internal
*/
private updateTabIndex(): void {
// If we have 0 chips, we should not allow keyboard focus
this.tabIndex = this._userTabIndex || (this.chips.length === 0 ? -1 : 0);
}
/**
* If the amount of chips changed, we need to update the key manager state and focus the next closest chip.
*/
private updateFocusForDestroyedChips(): void {
// Move focus to the closest chip. If no other chips remain, focus the chip-collection itself.
if (this.lastDestroyedChipIndex !== null) {
if (this.chips.length) {
const newChipIndex = Math.min(this.lastDestroyedChipIndex, this.chips.length - 1);
this.keyManager.setActiveItem(newChipIndex);
} else {
this.focus();
}
}
this.lastDestroyedChipIndex = null;
}
/**
* Emits change event to set the model value.
*/
private propagateChanges(): void {
const valueToEmit = this.chips.map(chip => chip.value || '');
this._value = valueToEmit;
this.collectionChange.emit(new TsChipCollectionChange(this, valueToEmit));
this.onChange(valueToEmit);
this.changeDetectorRef.markForCheck();
}
/**
* Utility to ensure all indexes are valid.
*
* @param index - The index to be checked.
* @returns True if the index is valid for our collection of chips.
*/
private isValidIndex(index: number): boolean {
return index >= 0 && index < this.chips.length;
}
/**
* Reset all the chips subscription
*/
private resetChips(): void {
this.listenToChipsFocus();
this.listenToChipsSelection();
this.listenToChipsRemoved();
}
/**
* Listens to user-generated selection events on each chip.
*/
private listenToChipsSelection(): void {
this.chipSelectionChanges.pipe(untilComponentDestroyed(this)).subscribe(event => {
event.source.selected
? this.selectionModel.select(event.source)
: this.selectionModel.deselect(event.source);
// For single selection chip collection, make sure the deselected value is unselected.
if (!this.allowMultipleSelections) {
this.chips.forEach(chip => {
if (!this.selectionModel.isSelected(chip) && chip.selected) {
chip.deselect();
}
});
}
});
}
/**
* Listens to user-generated selection events on each chip.
*/
private listenToChipsFocus(): void {
this.chipFocusChanges.pipe(untilComponentDestroyed(this)).subscribe(event => {
const chipIndex: number = this.chips.toArray().indexOf(event.chip);
// istanbul ignore else
if (this.isValidIndex(chipIndex)) {
this.keyManager.updateActiveItem(chipIndex);
}
});
this.chipBlurChanges.pipe(untilComponentDestroyed(this)).subscribe(() => {
this.blur();
});
}
/**
* Listens to remove events on each chip.
*/
private listenToChipsRemoved(): void {
this.chipDestroyChanges.pipe(untilComponentDestroyed(this)).subscribe(event => {
const chip = event.chip;
const chipIndex = this.chips.toArray().indexOf(event.chip);
// In case the chip that will be removed is currently focused, we temporarily store the index in order to be able to determine an
// appropriate sibling chip that will receive focus.
// istanbul ignore else
if (this.isValidIndex(chipIndex) && chip.hasFocus) {
this.lastDestroyedChipIndex = chipIndex;
}
this.removed.emit(new TsChipEvent(chip));
});
}
/**
* Syncs the collection's state with the individual chips.
*/
private syncChipsState(): void {
// istanbul ignore else
if (this.chips && this.chips.length) {
this.chips.forEach(chip => {
chip.allowMultiple = this.allowMultipleSelections;
chip.chipCollectionMultiple = this.allowMultipleSelections;
chip.isDisabled = this.isDisabled;
chip.chipCollectionRemovable = !this.isReadonly && !this.isDisabled;
chip.isSelectable = this.isSelectable;
});
}
}
} | the_stack |
import * as jsStyles from './NewTaskStyles';
import * as moment from 'moment';
import * as React from 'react';
import styles from './NewTask.module.scss';
import {
ActionButton,
CommandButton,
DatePicker,
DayOfWeek,
DefaultButton,
Dialog,
DialogFooter,
DialogType,
Dropdown,
FirstWeekOfYear,
Icon,
IContextualMenu,
IContextualMenuItem,
IconType,
IDatePickerStrings,
IDropdownOption,
IDropdownProps,
IIconProps,
ITextFieldProps,
MessageBar,
MessageBarType,
PrimaryButton,
Spinner,
SpinnerType,
Stack,
TextField,
Facepile,
OverflowButtonType,
PersonaSize,
IFacepilePersona,
} from 'office-ui-fabric-react';
import { Assigns } from './../Assigns/Assigns';
import { CommunicationColors } from '@uifabric/fluent-theme/lib/fluent/FluentColors';
import { DefaultPalette, FontSizes, FontWeights } from 'office-ui-fabric-react/lib/Styling';
import { INewTaskProps } from './INewTaskProps';
import { INewTaskState } from './INewTaskState';
import { IPlannerBucket } from '../../../../services/IPlannerBucket';
import { IPlannerPlanExtended } from '../../../../services/IPlannerPlanExtended';
import { IUser } from '../../../../services/IUser';
import { PeoplePicker, PrincipalType } from '@pnp/spfx-controls-react/lib/PeoplePicker';
import { IPlannerPlan } from '../../../../services/IPlannerPlan';
import { IMember } from '../../../../services/IGroupMembers';
import { AssignMode } from '../Assigns/EAssignMode';
const DayPickerStrings: IDatePickerStrings = {
months: [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
],
shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
shortDays: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
goToToday: 'Go to today',
prevMonthAriaLabel: 'Go to previous month',
nextMonthAriaLabel: 'Go to next month',
prevYearAriaLabel: 'Go to previous year',
nextYearAriaLabel: 'Go to next year',
closeButtonAriaLabel: 'Close date picker'
};
const textFieldStylesdatePicker: ITextFieldProps = {
style: { display: 'flex', justifyContent: 'flex-start', marginLeft: 15 },
iconProps: { style: { left: 0 } }
};
const addFriendIcon: IIconProps = { iconName: 'AddFriend', style: { marginLeft: 0, paddingLeft: 0 } };
const taskBoardIcon: IIconProps = {iconName: 'Taskboard', style: { left: 5, marginLeft: 0, paddingLeft: 0 }};
/**
* New task
*/
export class NewTask extends React.Component<INewTaskProps, INewTaskState> {
private _PlansDropDownOption: IDropdownOption[] = [];
private _assigns: IMember[] = [];
private _userPlans:IPlannerPlanExtended[]=[];
constructor(props: INewTaskProps) {
super(props);
this.state = {
hideDialog: !this.props.displayDialog,
hasError: false,
errorMessage: '',
planSelectedKey: '',
taskName: '',
disableAdd: true,
selectedBucket: undefined,
buckets: [],
isLoading: true,
addAssigns: false,
dueDate: '',
calloutTarget: undefined,
assignments: undefined,
};
}
/**
* Components did mount
*/
public async componentDidMount(): Promise<void> {
this._getUserPlans();
}
/**
* Gets people picker items
* @param users
*/
private _getPeoplePickerItems = (users: any[]) => {
// this._selectedUsers = users;
}
/**
* Closes dialog
* @param [ev]
*/
private _closeDialog = (ev?: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
this.setState({ hideDialog: true });
this.props.onDismiss(false);
}
/**
* Determines whether add task on
*/
private _onAddTask = async (ev?: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
try {
let taskInfo:string[] = [];
let assignments:object = {};
taskInfo['planId'] = this.state.planSelectedKey;
taskInfo['title'] = this.state.taskName;
taskInfo['bucketId'] = this.state.selectedBucket.key;
if (this.state.dueDate !== undefined){
taskInfo['dueDate'] = this.state.dueDate;
}
for ( const user of this._assigns){
assignments[user.id] = {"@odata.type": "#microsoft.graph.plannerAssignment", "orderHint": " !"};
}
taskInfo['assignments'] = assignments;
const addTaskResult = await this.props.spservice.addTask(taskInfo);
this.setState({ hideDialog: true });
this.props.onDismiss(true);
} catch (error) {
this.setState({hasError:true, errorMessage: error.message, disableAdd: true});
}
}
/**
* Get planner buckets of new task
*/
private _getPlannerBuckets = async (planId: string): Promise<IContextualMenuItem[]> => {
try {
const plannerBuckets: IPlannerBucket[] = await this.props.spservice.getPlanBuckets(String(planId));
let bucketsMenu: IContextualMenuItem[] = [];
for (const bucket of plannerBuckets) {
bucketsMenu.push({
key: bucket.id,
name: bucket.name,
onClick: () => {
this.setState({ selectedBucket: {key: bucket.id, name: bucket.name} });
}
});
}
return bucketsMenu;
} catch (error) {
Promise.reject(error);
}
};
/**
* Gets user plans
*/
private _getUserPlans = async () => {
try {
this._userPlans = await this.props.spservice.getUserPlans();
if (this._userPlans.length > 0) {
for (const plan of this._userPlans) {
this._PlansDropDownOption.push({ key: String(plan.id), text: plan.title, data: { image: plan.planPhoto, groupId: plan.owner} });
}
// Get Planner Buckets
const bucketsMenu = await this._getPlannerBuckets(String(this._PlansDropDownOption[0].key));
this.setState({
buckets: bucketsMenu,
selectedBucket: {key : bucketsMenu[0].key , name: bucketsMenu[0].name},
planSelectedKey: this._PlansDropDownOption[0].key,
isLoading: false,
hasError: false,
errorMessage: ''
});
}
} catch (error) {
this.setState({ hasError: true, errorMessage: error.message });
}
};
/**
* Determines whether render option on
*/
private _onRenderOption = (option: IDropdownOption): JSX.Element => {
return (
<div className={styles.selectPlanContainer}>
{option.data && option.data.image && (
<Icon
style={{ marginRight: '8px' }}
imageProps={{ src: option.data.image, style: { width: 22, height: 22 } }}
iconType={IconType.Image}
aria-hidden='true'
/>
)}
<span>{option.text}</span>
</div>
);
}
/**
* Determines whether render title on
*/
private _onRenderTitle = (options: IDropdownOption[]): JSX.Element => {
const option = options[0];
return (
<div className={styles.selectPlanContainer}>
{option.data && option.data.image && (
<Icon
style={{ marginRight: '8px' }}
imageProps={{ src: option.data.image, style: { width: 22, height: 22 } }}
iconType={IconType.Image}
aria-hidden='true'
/>
)}
<span>{option.text}</span>
</div>
);
};
/**
* Determines whether render placeholder on
*/
private _onRenderPlaceholder = (props: IDropdownProps): JSX.Element => {
return (
<div className={styles.selectPlanContainer}>
<Icon styles={{ root: { marginRight: '8px', fontSize: 20 } }} iconName={'plannerLogo'} aria-hidden='true' />
<span>{props.placeholder}</span>
</div>
);
};
/**
* Determines whether change plan on
*/
private _onChangePlan = async (event: React.FormEvent<HTMLDivElement>, plan: IDropdownOption) => {
// Get Planner Buckets
const bucketsMenu = await this._getPlannerBuckets(String(plan.key));
this._assigns = [];
this.setState({ buckets: bucketsMenu, selectedBucket: {key: bucketsMenu[0].key, name:bucketsMenu[0].name}, planSelectedKey: plan.key,assignments:[]});
}
/**
* Validate task name of new task
*/
private _validateTaskName = (value: string): string => {
if (value.trim().length > 0) {
this.setState({ taskName: value, disableAdd: false });
return '';
} else {
this.setState({ taskName: value, disableAdd: true });
return 'Plase enter task name';
}
}
private async _getAssignments(assignments: IMember[]): Promise<IFacepilePersona[]> {
let personas: IFacepilePersona[] = [];
for (const user of assignments) {
try {
// const userInfo = await this.props.spservice.getUser(user.id);
const userPhoto = await this.props.spservice.getUserPhoto(user.userPrincipalName);
personas.push({
style: { paddingRight: 5 },
personaName: user.displayName,
imageUrl: userPhoto
});
} catch (error) {
throw new Error(error);
}
}
return personas;
}
private _onCalloutDismiss = async (assigns:IMember[]):Promise<void> => {
this._assigns = assigns;
const personas = await this._getAssignments(assigns);
this.setState({ addAssigns: false , assignments: personas});
}
/**
* Determines whether assign on
*/
private _onAssign = (ev: React.MouseEvent<HTMLAnchorElement | HTMLButtonElement |HTMLDivElement>) : void => {
this.setState({addAssigns: !this.state.addAssigns, calloutTarget: ev.currentTarget});
}
/**
* Determines whether select due date on
*/
private _onSelectDueDate = (date:Date) => {
this.setState({dueDate: moment(date).format('L')});
}
/**
* Renders new task
* @returns render
*/
public render(): React.ReactElement<INewTaskProps> {
const hideDialog: boolean = this.state.hideDialog;
return (
<div>
<Dialog
hidden={hideDialog}
onDismiss={this._closeDialog}
minWidth={400}
maxWidth={400}
dialogContentProps={{
type: DialogType.normal,
title: 'Add Task'
}}
modalProps={{
isBlocking: false,
styles: jsStyles.modalStyles,
}}>
{this.state.isLoading ? (
<Spinner type={SpinnerType.normal} label='loading...' />
) : (
<>
<Stack gap='10'>
{this.state.hasError ? (
<MessageBar messageBarType={MessageBarType.error}>{this.state.errorMessage}</MessageBar>
) : (
<>
<Dropdown
placeholder='Select an Plan'
title='Select an Plan'
label=''
ariaLabel='Select an Plan'
onRenderPlaceholder={this._onRenderPlaceholder}
onRenderTitle={this._onRenderTitle}
onRenderOption={this._onRenderOption}
options={this._PlansDropDownOption}
selectedKey={this.state.planSelectedKey}
onChange={this._onChangePlan}
/>
<TextField
title='task name'
styles={jsStyles.textFieldStylesTaskName}
borderless={true}
placeholder='Please enter task name'
required
onGetErrorMessage={this._validateTaskName}
validateOnLoad={false}
value={this.state.taskName}
/>
<Stack gap='0'>
<CommandButton
id='ContextualMenuButton1'
text={this.state.selectedBucket.name}
title='select bucket'
style={{ backgroundColor: 'white', paddingLeft: 0, color: '#666666' }}
checked={true}
width='30'
split={false}
iconProps={taskBoardIcon}
menuIconProps={{ iconName: '' }}
menuProps={{
shouldFocusOnMount: true,
items: this.state.buckets
}}
/>
<DatePicker
title='Select due date'
textField={textFieldStylesdatePicker}
firstDayOfWeek={DayOfWeek.Sunday}
strings={DayPickerStrings}
showWeekNumbers={true}
firstWeekOfYear={1}
showGoToToday={true}
showMonthPickerAsOverlay={true}
borderless={true}
placeholder='Set due date'
ariaLabel='Set due date'
onSelectDate={this._onSelectDueDate}
value={this.state.dueDate !== '' ? moment(this.state.dueDate).toDate():undefined}
/>
<Stack horizontal horizontalAlign='start' styles={jsStyles.stackStyles} >
<ActionButton
iconProps={addFriendIcon}
checked={true}
styles={jsStyles.addMemberButton}
text={ this.state.assignments && this.state.assignments.length > 0 ? '': 'Assign'}
title='Assign task'
onClick={this._onAssign}
/>
{
<div onClick={this._onAssign} style={{cursor:'pointer', width:'100%'}}>
<Facepile
personaSize={PersonaSize.size32}
personas={this.state.assignments}
maxDisplayablePersonas={5}
overflowButtonType={OverflowButtonType.descriptive}
overflowButtonProps={{
ariaLabel: 'More users',
styles: { root: { cursor: 'default' } }
}}
showAddButton={false}
/>
</div>
}
</Stack>
</Stack>
</>
)}
</Stack>
<DialogFooter>
<PrimaryButton onClick={this._onAddTask} text='Add' disabled={this.state.disableAdd} />
<DefaultButton onClick={this._closeDialog} text='Cancel' />
</DialogFooter>
</>
)}
</Dialog>
{this.state.addAssigns && (
<Assigns
onDismiss={this._onCalloutDismiss}
task={undefined}
plannerPlan={this._userPlans.filter((plan) => { return plan.id === this.state.planSelectedKey;})[0]}
spservice={this.props.spservice}
assigns={this._assigns}
AssignMode={AssignMode.Add}
/>
)}
</div>
);
}
} | the_stack |
import { Expr, query as q } from 'faunadb';
import { TS_2500_YEARS } from '~/consts';
import { action } from '~/factory/api/action';
import { ContextNoLogNoAnnotation, ContextProp } from '~/factory/constructors/context';
import { ThrowError } from '~/factory/constructors/error';
import { MethodDispatch, Query } from '~/factory/constructors/method';
import { ResultData } from '~/factory/constructors/result';
import { BiotaFunctionName } from '~/factory/constructors/udfunction';
import * as helpers from '~/helpers';
import { FactoryContext } from '~/types/factory/factory.context';
import { FactoryDocument } from '~/types/factory/factory.document';
import { Pagination } from '../constructors/pagination';
// tslint:disable-next-line: only-arrow-functions
export const document: FactoryContext<FactoryDocument> = function (context, options): FactoryDocument {
const { prefix = 'Document' } = options || {};
// tslint:disable-next-line: only-arrow-functions
return (collection = null, id = null) => {
const ref = q.If(q.IsString(id), q.Ref(q.Collection(collection), id), q.Collection(collection));
const refExists = (refExpr: Expr) => {
return q.If(q.Not(q.Exists(q.Var('ref'))), ThrowError(q.Var('ctx'), "Reference doesn't exists", { ref: refExpr }), true);
};
return {
history(pagination = {}) {
const inputs = { ref, pagination };
// ----
const query = Query(
{
refExists: refExists(q.Var('ref')),
doc: q.Paginate(q.Events(q.Var('ref')), Pagination(q.Var('pagination'))),
},
q.Var('doc'),
);
// ----
const offline = `factory.${prefix.toLowerCase()}.history`;
const online = { name: BiotaFunctionName(`${prefix}History`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
get() {
const inputs = { ref };
// ----
const query = Query(
{
refExists: refExists(q.Var('ref')),
check: q.If(q.Not(q.Exists(q.Var('ref'))), ThrowError(q.Var('ctx'), "Reference doesn't exists", { ref: q.Var('ref') }), true),
doc: q.Get(q.Var('ref')),
},
q.Var('doc'),
);
// ----
const offline = `factory.${prefix.toLowerCase()}.get`;
const online = { name: BiotaFunctionName(`${prefix}Get`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
insert(data) {
const inputs = { ref, data };
// ----
const query = Query(
{
refExists: refExists(q.Var('ref')),
annotated: ResultData(document(q.Var('ctx'))(q.Var('ref')).annotate('insert', q.Var('data'))),
doc: q.Create(q.Var('ref'), { data: q.Var('annotated') }),
action: action(q.Var('ctx'))('insert', q.Var('doc')).log(),
},
q.Var('doc'),
q.Var('action'),
);
// ----
const offline = `factory.${prefix.toLowerCase()}.insert`;
const online = { name: BiotaFunctionName(`${prefix}Insert`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
update(data) {
const inputs = { ref, data };
// ----
const query = Query(
{
refExists: refExists(q.Var('ref')),
annotated: ResultData(document(q.Var('ctx'))().annotate('update', q.Var('data'))),
doc: q.Update(q.Var('ref'), { data: q.Var('annotated') }),
action: action(q.Var('ctx'))('update', q.Var('doc')).log(),
},
q.Var('doc'),
q.Var('action'),
);
// ----
const offline = `factory.${prefix.toLowerCase()}.update`;
const online = { name: BiotaFunctionName(`${prefix}Update`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
upsert(data) {
const inputs = { ref, data };
// ----
const query = Query(
{
refExists: refExists(q.Var('ref')),
doc: q.If(
q.Exists(q.Var('ref')),
ResultData(document(q.Var('ctx'))(q.Var('ref')).update(q.Var('data'))),
ResultData(document(q.Var('ctx'))(q.Var('ref')).insert(q.Var('data'))),
),
},
q.Var('doc'),
// already logging actions: update or insert
);
// ----
const offline = `factory.${prefix.toLowerCase()}.upsert`;
const online = { name: BiotaFunctionName(`${prefix}Upsert`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
replace(data) {
const inputs = { ref, data };
// ----
const query = Query(
{
refExists: refExists(q.Var('ref')),
current_doc: ResultData(document(q.Var('ctx'))(q.Var('ref')).get()),
annotated: ResultData(
document(q.Var('ctx'))().annotate(
'replace',
q.Merge(q.Var('data'), {
_auth: q.Select('_auth', q.Var('current_doc'), {}),
_membership: q.Select('_membership', q.Var('current_doc'), {}),
_validity: q.Select('_validity', q.Var('current_doc'), {}),
_activity: q.Select('_activity', q.Var('current_doc'), {}),
}),
),
),
doc: q.Replace(q.Var('ref'), { data: q.Var('annotated') }),
action: action(q.Var('ctx'))('replace', q.Var('doc')).log(),
},
q.Var('doc'),
q.Var('action'),
);
// ----
const offline = `factory.${prefix.toLowerCase()}.replace`;
const online = { name: BiotaFunctionName(`${prefix}Replace`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
repsert(data) {
const inputs = { ref, data };
// ----
const query = Query(
{
refExists: refExists(q.Var('ref')),
doc: q.If(
q.Exists(q.Var('ref')),
ResultData(document(q.Var('ctx'))(q.Var('ref')).replace(q.Var('data'))),
ResultData(document(q.Var('ctx'))(q.Var('ref')).insert(q.Var('data'))),
),
},
q.Var('doc'),
// already logging actions: replace or insert
);
// ----
const offline = `factory.${prefix.toLowerCase()}.repsert`;
const online = { name: BiotaFunctionName(`${prefix}Repsert`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
delete() {
// alias
const inputs = { ref };
// ----
const query = Query(
{
refExists: refExists(q.Var('ref')),
doc: ResultData(document(q.Var('ctx'))(q.Var('ref')).validity.delete()),
},
q.Var('doc'),
);
// ----
const offline = `factory.${prefix.toLowerCase()}.delete`;
const online = { name: BiotaFunctionName(`${prefix}Delete`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
restore() {
// alias
const inputs = { ref };
// ----
const query = Query(
{
refExists: refExists(q.Var('ref')),
doc: ResultData(document(q.Var('ctx'))(q.Var('ref')).validity.restore()),
},
q.Var('doc'),
);
// ----
const offline = `factory.${prefix.toLowerCase()}.restore`;
const online = { name: BiotaFunctionName(`${prefix}Restore`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
forget() {
const inputs = { ref };
// ----
const query = Query(
{
refExists: refExists(q.Var('ref')),
annotated: ResultData(document(q.Var('ctx'))().annotate('forget')),
annotated_doc: ResultData(document(ContextNoLogNoAnnotation(q.Var('ctx')))(q.Var('ref')).upsert(q.Var('annotated'))),
action: action(q.Var('ctx'))('forget', q.Var('ref')).log(),
doc: q.Delete(q.Var('ref')),
},
q.Var('doc'),
q.Var('action'),
);
// ----
const offline = `factory.${prefix.toLowerCase()}.forget`;
const online = { name: BiotaFunctionName(`${prefix}Restore`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
remember() {
const inputs = { ref };
// ----
const query = Query(
{
lastEvents: q.Select('data', q.Paginate(q.Events(q.Var('ref')), { size: 1, events: true, before: null }), []),
deleteEvent: q.Select(0, q.Var('lastEvents'), null),
isDeleteEvent: q.Equals(q.Select('action', q.Var('deleteEvent'), null), 'delete'),
checkDeleteEvent: q.If(
q.Var('isDeleteEvent'),
true,
ThrowError(q.Var('ctx'), "Reference hasn't been deleted", { ref: q.Var('ref') }),
),
previousState: q.Get(ref, q.Subtract(q.Select('ts', q.Var('deleteEvent'), 0), 1)),
annotated: ResultData(document(q.Var('ctx'))().annotate('remember', q.Select('data', q.Var('previousState'), {}))),
doc: q.Insert(q.Var('ref'), q.Now(), 'update', { data: q.Var('annotated') }),
action: action(q.Var('ctx'))('remember', q.Var('ref')).log(),
},
q.Var('doc'),
q.Var('action'),
);
// ----
const offline = `factory.${prefix.toLowerCase()}.remember`;
const online = { name: BiotaFunctionName(`${prefix}Remember`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
drop() {
const inputs = { ref };
// ----
const query = Query(
{
refExists: refExists(q.Var('ref')),
doc: q.If(q.Exists(q.Var('ref')), document(q.Var('ctx'))(q.Var('ref')).forget(), false),
},
q.Var('doc'),
);
// ----
const offline = `factory.${prefix.toLowerCase()}.drop`;
const online = { name: BiotaFunctionName(`${prefix}Clean`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
expireAt(at) {
// alias
const inputs = { ref, at };
// ----
const query = Query(
{
refExists: refExists(q.Var('ref')),
doc: ResultData(document(q.Var('ctx'))(q.Var('ref')).validity.expire(q.Var('at'))),
},
q.Var('doc'),
);
// ----
const offline = `factory.${prefix.toLowerCase()}.expireAt`;
const online = { name: BiotaFunctionName(`${prefix}ExpireAt`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
expireIn(delay) {
// alias
const inputs = { ref, delay };
// ----
const query = Query(
{
refExists: refExists(q.Var('ref')),
doc: ResultData(
document(q.Var('ctx'))(q.Var('ref')).validity.expire(q.TimeAdd(q.Now(), q.ToNumber(q.Var('delay')), 'milliseconds')),
),
},
q.Var('doc'),
);
// ----
const offline = `factory.${prefix.toLowerCase()}.expireIn`;
const online = { name: BiotaFunctionName(`${prefix}ExpireIn`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
expireNow() {
// alias
const inputs = { ref };
// ----
const query = Query(
{
refExists: refExists(q.Var('ref')),
doc: ResultData(document(q.Var('ctx'))(q.Var('ref')).validity.expire(q.Now())),
},
q.Var('doc'),
);
// ----
const offline = `factory.${prefix.toLowerCase()}.expireNow`;
const online = { name: BiotaFunctionName(`${prefix}ExpireNow`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
membership: {
role(roleOrRef) {
const roleRef = q.If(q.IsRole(roleOrRef), roleOrRef, q.Role(roleOrRef));
return {
distinct() {
const inputs = { ref, roleRef };
// ----
const query = Query(
{
refExists: refExists(q.Var('ref')),
doc: q.Distinct(q.Union(q.Select(helpers.path('_membership.roles'), q.Get(q.Var('ref')), []), [q.Var('roleRef')])),
},
q.Var('doc'),
);
// ----
const offline = `factory.${prefix.toLowerCase()}.membership.role.distinct`;
const online = { name: BiotaFunctionName(`${prefix}MembershipRoleDistinct`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
difference() {
const inputs = { ref, roleRef };
// ----
const query = Query(
{
refExists: refExists(q.Var('ref')),
doc: q.Difference(q.Select(helpers.path('_membership.roles'), q.Get(q.Var('ref')), []), [q.Var('roleRef')]),
},
q.Var('doc'),
);
// ----
const offline = `factory.${prefix.toLowerCase()}.membership.role.difference`;
const online = { name: BiotaFunctionName(`${prefix}MembershipRoleDifference`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
set() {
const inputs = { ref, roleRef };
// ----
const query = Query(
{
refExists: refExists(q.Var('ref')),
annotated: ResultData(
document(q.Var('ctx'))().annotate('roles_change', {
_membership: {
roles: ResultData(document(q.Var('ctx'))(q.Var('ref')).membership.role(q.Var('roleRef')).distinct()),
},
}),
),
doc: ResultData(document(ContextNoLogNoAnnotation(q.Var('ctx')))(q.Var('ref')).upsert(q.Var('annotated'))),
action: action(q.Var('ctx'))('roles_change', q.Var('ref')).log(),
},
q.Var('doc'),
q.Var('action'),
);
// ----
const offline = `factory.${prefix.toLowerCase()}.membership.role.set`;
const online = { name: BiotaFunctionName(`${prefix}MembershipRoleSet`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
remove() {
const inputs = { ref, roleRef };
// ----
const query = Query(
{
refExists: refExists(q.Var('ref')),
annotated: ResultData(
document(q.Var('ctx'))().annotate('roles_change', {
_membership: {
roles: ResultData(document(q.Var('ctx'))(q.Var('ref')).membership.role(q.Var('roleRef')).difference()),
},
}),
),
doc: ResultData(document(ContextNoLogNoAnnotation(q.Var('ctx')))(q.Var('ref')).upsert(q.Var('annotated'))),
action: action(q.Var('ctx'))('roles_change', q.Var('ref')).log(),
},
q.Var('doc'),
q.Var('action'),
);
// ----
const offline = `factory.${prefix.toLowerCase()}.membership.role.remove`;
const online = { name: BiotaFunctionName(`${prefix}MembershipRoleRemove`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
};
},
owner: {
// tslint:disable-next-line: no-shadowed-variable
set(user) {
const inputs = { ref, user };
// ----
const query = Query(
{
refExists: refExists(q.Var('ref')),
annotated: ResultData(
document(q.Var('ctx'))().annotate('owner_change', {
_membership: {
owner: q.Var('user'),
},
}),
),
doc: q.If(
q.IsDoc(q.Var('user')),
ResultData(document(ContextNoLogNoAnnotation(q.Var('ctx')))(q.Var('ref')).upsert(q.Var('annotated'))),
ThrowError(q.Var('ctx'), "User isn't a document reference", { user: q.Var('user') }),
),
action: action(q.Var('ctx'))('owner_change', q.Var('ref')).log(),
},
q.Var('doc'),
q.Var('action'),
);
// ----
const offline = `factory.${prefix.toLowerCase()}.membership.owner.set`;
const online = { name: BiotaFunctionName(`${prefix}MembershipOwnerSet`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
remove() {
const inputs = { ref };
// ----
const query = Query(
{
refExists: refExists(q.Var('ref')),
annotated: ResultData(
document(q.Var('ctx'))().annotate('owner_change', {
_membership: {
owner: null,
},
}),
),
doc: ResultData(document(ContextNoLogNoAnnotation(q.Var('ctx')))(q.Var('ref')).upsert(q.Var('annotated'))),
action: action(q.Var('ctx'))('owner_change', q.Var('ref')).log(),
},
q.Var('doc'),
q.Var('action'),
);
// ----
const offline = `factory.${prefix.toLowerCase()}.membership.owner.remove`;
const online = { name: BiotaFunctionName(`${prefix}MembershipOwnerRemove`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
},
assignee(assignee) {
const assigneeRef = q.If(q.IsDoc(assignee), assignee, null);
return {
distinct() {
const inputs = { ref, assigneeRef };
// ----
const query = Query(
{
refExists: refExists(q.Var('ref')),
doc: q.Distinct(
q.Union(q.Select(helpers.path('_membership.assignees'), q.Get(q.Var('ref')), []), [q.Var('assigneeRef')]),
),
},
q.Var('doc'),
);
// ----
const offline = `factory.${prefix.toLowerCase()}.membership.assignee.distinct`;
const online = { name: BiotaFunctionName(`${prefix}MembershipAssigneeDistinct`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
difference() {
const inputs = { ref, assigneeRef };
// ----
const query = Query(
{
refExists: refExists(q.Var('ref')),
doc: q.Difference(q.Select(helpers.path('_membership.assignees'), q.Get(q.Var('ref')), []), [q.Var('assigneeRef')]),
},
q.Var('doc'),
);
// ----
const offline = `factory.${prefix.toLowerCase()}.membership.assignee.difference`;
const online = { name: BiotaFunctionName(`${prefix}MembershipAssigneeDifference`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
set() {
const inputs = { ref, assigneeRef };
// ----
const query = Query(
{
refExists: refExists(q.Var('ref')),
annotated: ResultData(
document(q.Var('ctx'))().annotate('assignees_change', {
_membership: {
assignees: ResultData(document(q.Var('ctx'))(q.Var('ref')).membership.role(q.Var('assigneeRef')).distinct()),
},
}),
),
doc: ResultData(document(ContextNoLogNoAnnotation(q.Var('ctx')))(q.Var('ref')).upsert(q.Var('annotated'))),
action: action(q.Var('ctx'))('assignees_change', q.Var('ref')).log(),
},
q.Var('doc'),
q.Var('action'),
);
// ----
const offline = `factory.${prefix.toLowerCase()}.membership.assignee.set`;
const online = { name: BiotaFunctionName(`${prefix}MembershipAssigneeSet`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
remove() {
const inputs = { ref, assigneeRef };
// ----
const query = Query(
{
refExists: refExists(q.Var('ref')),
annotated: ResultData(
document(q.Var('ctx'))().annotate('assignees_change', {
_membership: {
assignees: ResultData(document(q.Var('ctx'))(q.Var('ref')).membership.role(q.Var('assigneeRef')).difference()),
},
}),
),
doc: ResultData(document(ContextNoLogNoAnnotation(q.Var('ctx')))(q.Var('ref')).upsert(q.Var('annotated'))),
action: action(q.Var('ctx'))('assignees_change', q.Var('ref')).log(),
},
q.Var('doc'),
q.Var('action'),
);
// ----
const offline = `factory.${prefix.toLowerCase()}.membership.assignee.remove`;
const online = { name: BiotaFunctionName(`${prefix}MembershipAssigneeRemove`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
};
},
},
validity: {
delete() {
const inputs = { ref };
// ----
const query = Query(
{
refExists: refExists(q.Var('ref')),
annotated: ResultData(
document(q.Var('ctx'))().annotate('delete', {
_validity: {
deleted: true,
},
}),
),
doc: ResultData(document(ContextNoLogNoAnnotation(q.Var('ctx')))(q.Var('ref')).upsert(q.Var('annotated'))),
action: action(q.Var('ctx'))('delete', q.Var('doc')).log(),
},
q.Var('doc'),
q.Var('action'),
);
// ----
const offline = `factory.${prefix.toLowerCase()}.validity.delete`;
const online = { name: BiotaFunctionName(`${prefix}ValidityDelete`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
expire(at) {
const inputs = { ref, at };
// ----
const query = Query(
{
refExists: refExists(q.Var('ref')),
annotated: ResultData(
document(q.Var('ctx'))().annotate('expire', {
_validity: {
expires_at: q.Var('at'),
},
}),
),
doc: q.If(
q.IsTimestamp(q.Var('ctx')),
ResultData(document(ContextNoLogNoAnnotation(q.Var('ctx')))(q.Var('ref')).upsert(q.Var('annotated'))),
ThrowError(q.Var('ctx'), "[at] isn't a valid time", { at: q.Var('ctx') }),
),
action: action(q.Var('ctx'))('expire', q.Var('doc')).log(),
},
q.Var('doc'),
q.Var('action'),
);
// ----
const offline = `factory.${prefix.toLowerCase()}.validity.expire`;
const online = { name: BiotaFunctionName(`${prefix}ValidityExpire`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
restore() {
const inputs = { ref };
// ----
const query = Query(
{
refExists: refExists(q.Var('ref')),
doc: q.Let(
{
current_doc: q.Get(q.Var('ref')),
isDeleted: q.Select(helpers.path('_validity.deleted'), q.Var('current_doc'), false),
isExpired: q.GTE(q.Select(helpers.path('_validity.expires_at'), q.Var('current_doc'), q.ToTime(TS_2500_YEARS)), q.Now()),
},
q.Let(
{
annotated: ResultData(
document(q.Var('ctx'))().annotate('restore', {
_validity: {
deleted: false,
expires_at: null,
},
}),
),
doc: ResultData(document(ContextNoLogNoAnnotation(q.Var('ctx')))(q.Var('ref')).upsert(q.Var('annotated'))),
},
q.Var('doc'),
),
),
action: action(q.Var('ctx'))('restore', q.Var('doc')).log(),
},
q.Var('doc'),
q.Var('action'),
);
// ----
const offline = `factory.${prefix.toLowerCase()}.validity.restore`;
const online = { name: BiotaFunctionName(`${prefix}ValidityRestore`), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
},
annotate(actionName = null, data = {}) {
const inputs = { actionName, data };
// ----
const query = Query(
{
doc: q.If(
ContextProp(q.Var('ctx'), 'annotateDocuments'),
q.Let(
{
activity: {
insert: { inserted_by: ContextProp(q.Var('ctx'), 'identity'), inserted_at: q.Now() },
update: { updated_by: ContextProp(q.Var('ctx'), 'identity'), updated_at: q.Now() },
replace: { replaced_by: ContextProp(q.Var('ctx'), 'identity'), replaced_at: q.Now() },
delete: { deleted_by: ContextProp(q.Var('ctx'), 'identity'), deleted_at: q.Now() },
forget: { forgotten_by: ContextProp(q.Var('ctx'), 'identity'), forgotten_at: q.Now() },
restore: { restored_by: ContextProp(q.Var('ctx'), 'identity'), restored_at: q.Now() },
remember: { remembered_by: ContextProp(q.Var('ctx'), 'identity'), remembered_at: q.Now() },
expire: { expiration_changed_by: ContextProp(q.Var('ctx'), 'identity'), expiration_changed_at: q.Now() },
credentials_change: { credentials_changed_by: ContextProp(q.Var('ctx'), 'identity'), credentials_changed_at: q.Now() },
auth_email_change: { auth_email_changed_by: ContextProp(q.Var('ctx'), 'identity'), auth_email_changed_at: q.Now() },
auth_accounts_change: {
auth_accounts_changed_by: ContextProp(q.Var('ctx'), 'identity'),
auth_accounts_changed_at: q.Now(),
},
roles_change: { roles_changed_by: ContextProp(q.Var('ctx'), 'identity'), roles_changed_at: q.Now() },
owner_change: { owner_changed_by: ContextProp(q.Var('ctx'), 'identity'), owner_changed_at: q.Now() },
assignees_change: { assignees_changed_by: ContextProp(q.Var('ctx'), 'identity'), assignees_changed_at: q.Now() },
},
_activity: q.Select(q.Var('actionName'), q.Var('activity'), {}),
data_activity: q.Select('_activity', q.Var('data'), {}),
merged_activity: q.Merge(q.Var('data_activity'), q.Var('_activity')),
},
q.If(
q.IsObject(q.Var('_activity')),
q.Merge(q.Var('data'), { _activity: q.Var('merged_activity') }),
ThrowError(q.Var('ctx'), "This action event doesn't exist", { name: q.Var('actionName') }),
),
),
q.Var('data'),
),
},
q.Var('doc'),
);
// ----
const offline = `factory.${prefix.toLowerCase()}.annotate`;
const online = { name: BiotaFunctionName('DocumentAnnotate'), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
};
};
}; | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.