text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import React from 'react';
import { runInAction } from 'mobx';
import * as POOL from 'types/generated/trader_pb';
import { grpc } from '@improbable-eng/grpc-web';
import { fireEvent, waitFor } from '@testing-library/react';
import Big from 'big.js';
import { formatSats } from 'util/formatters';
import { b64, hex } from 'util/strings';
import { renderWithProviders, throwGrpcError } from 'util/tests';
import {
poolDepositAccount,
poolInitAccount,
poolQuoteAccount,
sampleApiResponses,
} from 'util/tests/sampleData';
import { createStore, Store } from 'store';
import {
DEFAULT_CONF_TARGET,
DEFAULT_EXPIRE_BLOCKS,
} from 'store/views/fundNewAccountView';
import AccountSection from 'components/pool/AccountSection';
const grpcMock = grpc as jest.Mocked<typeof grpc>;
describe('AccountSection', () => {
let store: Store;
beforeEach(async () => {
store = createStore();
await store.channelStore.fetchChannels();
await store.nodeStore.fetchBalances();
await store.accountStore.fetchAccounts();
await store.orderStore.fetchOrders();
});
const render = () => {
return renderWithProviders(<AccountSection />, store);
};
it('should display channel notice', () => {
// remove all accounts to display the FundNewAccountForm
runInAction(() => {
store.accountStore.accounts.clear();
store.accountStore.activeTraderKey = '';
store.channelStore.channels.clear();
});
const { getByText } = render();
expect(getByText('Welcome to Pool')).toBeInTheDocument();
expect(getByText(/Your node must already have open channels/)).toBeInTheDocument();
});
it('should validate fund new account form', () => {
// remove all accounts to display the FundNewAccountForm
runInAction(() => {
store.accountStore.accounts.clear();
store.accountStore.activeTraderKey = '';
});
const { getByText, changeInput } = render();
expect(getByText('Welcome to Pool')).toBeInTheDocument();
fireEvent.click(getByText('Open an Account'));
expect(getByText('Fund Account')).toBeInTheDocument();
// should show amount errors
changeInput('Amount', '1');
expect(getByText('must be greater than 100000 sats')).toBeInTheDocument();
changeInput('Amount', '200000000');
expect(getByText('must be less than wallet balance')).toBeInTheDocument();
// should show expire blocks errors
changeInput('Expires In', '10');
expect(getByText('must be greater than 144 blocks')).toBeInTheDocument();
changeInput('Expires In', '1000000');
expect(getByText('must be less than 52560 blocks')).toBeInTheDocument();
// should show conf target errors
changeInput('Confirmation Target', '1');
expect(getByText('must be greater than 1 block')).toBeInTheDocument();
});
it('should fund a new account', async () => {
runInAction(() => {
store.accountStore.accounts.clear();
store.accountStore.activeTraderKey = '';
});
const { getByText, queryAllByText, changeInput } = render();
expect(getByText('Welcome to Pool')).toBeInTheDocument();
fireEvent.click(getByText('Open an Account'));
expect(getByText('Fund Account')).toBeInTheDocument();
changeInput('Amount', '25000000');
changeInput('Expires In', '2016');
changeInput('Confirmation Target', '3');
fireEvent.click(getByText('Fund'));
// wait until the confirm view is displayed
await waitFor(() => {
expect(getByText('Current Account Balance')).toBeInTheDocument();
});
// check confirmation values
expect(getByText('0 sats')).toBeInTheDocument();
expect(getByText('2016 blocks')).toBeInTheDocument();
expect(getByText('3 blocks')).toBeInTheDocument();
expect(
getByText(formatSats(Big(poolQuoteAccount.minerFeeTotal))),
).toBeInTheDocument();
expect(queryAllByText('25,000,000 sats')).toHaveLength(2);
expect(store.accountStore.activeTraderKey).toBe('');
fireEvent.click(getByText('Confirm'));
// wait until the summary view is displayed
await waitFor(() => {
expect(getByText('Account')).toBeInTheDocument();
});
expect(store.accountStore.activeTraderKey).toBe(hex(poolInitAccount.traderKey));
expect(+store.fundNewAccountView.amount).toBe(0);
expect(store.fundNewAccountView.confTarget).toBe(DEFAULT_CONF_TARGET);
expect(store.fundNewAccountView.expireBlocks).toBe(DEFAULT_EXPIRE_BLOCKS);
});
it('should handle errors funding a new account', async () => {
runInAction(() => {
store.accountStore.accounts.clear();
store.accountStore.activeTraderKey = '';
});
const { getByText, changeInput } = render();
expect(getByText('Welcome to Pool')).toBeInTheDocument();
fireEvent.click(getByText('Open an Account'));
expect(getByText('Fund Account')).toBeInTheDocument();
changeInput('Amount', '25000000');
changeInput('Expires In', '2016');
changeInput('Confirmation Target', '3');
// throw a GRPC error when getting the account quote
throwGrpcError('quote-err', 'QuoteAccount');
fireEvent.click(getByText('Fund'));
// should show error toast
await waitFor(() => {
expect(getByText('Unable to estimate miner fee')).toBeInTheDocument();
expect(getByText('quote-err')).toBeInTheDocument();
});
// the error won't be thrown this time
fireEvent.click(getByText('Fund'));
// wait until the confirm view is displayed
await waitFor(() => {
expect(getByText('Current Account Balance')).toBeInTheDocument();
});
throwGrpcError('init-err', 'InitAccount');
fireEvent.click(getByText('Confirm'));
// should show error toast
await waitFor(() => {
expect(getByText('Unable to create the account')).toBeInTheDocument();
expect(getByText('init-err')).toBeInTheDocument();
});
});
it('should validate fund existing account form', () => {
const { getByText, changeInput } = render();
expect(getByText('Fund Account')).toBeInTheDocument();
fireEvent.click(getByText('Fund Account'));
// should show amount errors
changeInput('Amount', store.nodeStore.wallet.walletBalance.plus(100).toString());
expect(getByText('must be less than wallet balance')).toBeInTheDocument();
});
it('should fund an existing account', async () => {
const { getByText, changeInput } = render();
expect(getByText('Fund Account')).toBeInTheDocument();
fireEvent.click(getByText('Fund Account'));
const amount = 25000000;
changeInput('Amount', amount.toString());
changeInput('Fee', '100');
fireEvent.click(getByText('Fund'));
// wait until the confirm view is displayed
await waitFor(() => {
expect(getByText('Current Account Balance')).toBeInTheDocument();
});
// check confirmation values
const currentBalance = store.accountStore.activeAccount.availableBalance;
expect(getByText(formatSats(currentBalance))).toBeInTheDocument();
expect(getByText('25,000,000 sats')).toBeInTheDocument();
expect(getByText('100 sats/vByte')).toBeInTheDocument();
expect(getByText(formatSats(currentBalance.add(amount)))).toBeInTheDocument();
fireEvent.click(getByText('Confirm'));
// wait until the summary view is displayed
await waitFor(() => {
expect(getByText('Account')).toBeInTheDocument();
});
expect(store.accountStore.activeAccount.totalBalance.toString()).toBe(
poolDepositAccount.account.value,
);
expect(store.fundAccountView.amount).toBe(0);
expect(store.fundAccountView.satsPerVbyte).toBe(0);
});
it('should handle errors funding an existing account', async () => {
const { getByText, changeInput } = render();
expect(getByText('Fund Account')).toBeInTheDocument();
fireEvent.click(getByText('Fund Account'));
changeInput('Amount', '25000000');
changeInput('Fee', '100');
fireEvent.click(getByText('Fund'));
throwGrpcError('test-err');
fireEvent.click(getByText('Confirm'));
// should show error toast
await waitFor(() => {
expect(getByText('Unable to deposit funds')).toBeInTheDocument();
expect(getByText('test-err')).toBeInTheDocument();
});
// should remain on the same view
expect(getByText('Confirm')).toBeInTheDocument();
});
it('should return account expiration estimates', async () => {
const { getByText, queryByText } = render();
const expectExpires = (blocksTilExpire: number, expected: string) => {
runInAction(() => {
const currHeight = store.nodeStore.blockHeight;
store.accountStore.activeAccount.expirationHeight = currHeight + blocksTilExpire;
});
if (expected) {
expect(getByText(`Expires in ${expected}`)).toBeInTheDocument();
} else {
expect(queryByText(/Expires in/)).not.toBeInTheDocument();
}
};
expectExpires(0, '');
expectExpires(100, '~16 hours');
expectExpires(288, '~2 days');
expectExpires(2016, '~2 weeks');
expectExpires(4032, '~4 weeks');
expectExpires(4320, '~30 days');
expectExpires(8064, '~1.9 months');
expectExpires(8640, '~60 days');
runInAction(() => {
store.accountStore.activeAccount.state = POOL.AccountState.EXPIRED;
});
expectExpires(100, '');
});
it('should display warning when account is near expiration', () => {
runInAction(() => {
const currHeight = store.nodeStore.blockHeight;
store.accountStore.activeAccount.expirationHeight = currHeight + 144 * 2;
});
const { getByText } = render();
expect(getByText('Expires in ~2 days')).toBeInTheDocument();
expect(getByText(/Orders will no longer be matched/)).toBeInTheDocument();
expect(getByText('Close')).toBeInTheDocument();
});
it('should close an expired account', async () => {
// set the account as expired
runInAction(() => {
store.accountStore.activeAccount.state = POOL.AccountState.EXPIRED;
});
const { getByText, changeInput } = render();
expect(getByText('Close')).toBeInTheDocument();
fireEvent.click(getByText('Close'));
changeInput('Destination Address', 'abc123');
changeInput('Fee', '10');
fireEvent.click(getByText('Close Account', { selector: 'button' }));
// check confirmation values
expect(getByText('abc123')).toBeInTheDocument();
expect(getByText('10 sats/vByte')).toBeInTheDocument();
// capture the request that is sent to the API
let req: POOL.CloseAccountRequest.AsObject;
grpcMock.unary.mockImplementation((desc, props) => {
if (desc.methodName === 'CloseAccount') {
req = props.request.toObject() as any;
}
const path = `${desc.service.serviceName}.${desc.methodName}`;
const toObject = () => sampleApiResponses[path];
// return a response by calling the onEnd function
props.onEnd({
status: grpc.Code.OK,
// the message returned should have a toObject function
message: { toObject } as any,
} as any);
return undefined as any;
});
fireEvent.click(getByText('Confirm'));
// wait until the confirm view is displayed
await waitFor(() => {
expect(req).toBeDefined();
expect(getByText('Account')).toBeInTheDocument();
});
expect(req!.traderKey).toBe(b64(store.accountStore.activeAccount.traderKey));
expect(req!.outputWithFee?.feeRateSatPerKw).toBe('2500');
expect(req!.outputWithFee?.address).toBe('abc123');
});
it('should renew an expired account', async () => {
// set the account to expire in less than 3 days
runInAction(() => {
const currHeight = store.nodeStore.blockHeight;
store.accountStore.activeAccount.expirationHeight = currHeight + 144 * 2;
});
const { getByText, changeInput } = render();
expect(getByText('Renew Account')).toBeInTheDocument();
fireEvent.click(getByText('Renew Account'));
changeInput('New Expiration', '2016');
changeInput('Fee Rate', '125');
fireEvent.click(getByText('Renew'));
// check confirmation values
expect(getByText('288 blocks')).toBeInTheDocument();
expect(getByText('~2 days')).toBeInTheDocument();
expect(getByText('2016 blocks')).toBeInTheDocument();
expect(getByText('~2 weeks')).toBeInTheDocument();
expect(getByText('125 sats/vByte')).toBeInTheDocument();
// capture the request that is sent to the API
let req: POOL.RenewAccountRequest.AsObject;
grpcMock.unary.mockImplementation((desc, props) => {
if (desc.methodName === 'RenewAccount') {
req = props.request.toObject() as any;
}
const path = `${desc.service.serviceName}.${desc.methodName}`;
const toObject = () => sampleApiResponses[path];
// return a response by calling the onEnd function
props.onEnd({
status: grpc.Code.OK,
// the message returned should have a toObject function
message: { toObject } as any,
} as any);
return undefined as any;
});
fireEvent.click(getByText('Confirm'));
// wait until the account view is displayed
await waitFor(() => {
expect(req).toBeDefined();
expect(getByText('Account')).toBeInTheDocument();
});
expect(req!.accountKey).toBe(b64(store.accountStore.activeAccount.traderKey));
expect(req!.feeRateSatPerKw).toBe('31250');
expect(req!.relativeExpiry).toBe(2016);
});
}); | the_stack |
import { EventEmitter, NO_ERRORS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { InteractionAttributesExtractorService } from 'interactions/interaction-attributes-extractor.service';
import { CurrentInteractionService } from 'pages/exploration-player-page/services/current-interaction.service';
import { InteractiveGraphInput } from './oppia-interactive-graph-input.component';
import { TranslateModule } from '@ngx-translate/core';
import { PlayerPositionService } from 'pages/exploration-player-page/services/player-position.service';
import { I18nLanguageCodeService } from 'services/i18n-language-code.service';
describe('InteractiveGraphInput', () => {
let component: InteractiveGraphInput;
let playerPositionService: PlayerPositionService;
let mockNewCardAvailableEmitter = new EventEmitter();
let fixture: ComponentFixture<InteractiveGraphInput>;
let currentInteractionService: CurrentInteractionService;
let i18nLanguageCodeService: I18nLanguageCodeService;
class mockInteractionAttributesExtractorService {
getValuesFromAttributes(interactionId, attributes) {
return {
graph: {
value: JSON.parse(attributes.graphWithValue)
},
canAddVertex: {
value: JSON.parse(attributes.canAddVertexWithValue)
},
canDeleteVertex: {
value: JSON.parse(attributes.canDeleteVertexWithValue)
},
canEditVertexLabel: {
value: JSON.parse(attributes.canMoveVertexWithValue)
},
canMoveVertex: {
value: JSON.parse(attributes.canEditVertexLabelWithValue)
},
canAddEdge: {
value: JSON.parse(attributes.canAddEdgeWithValue)
},
canDeleteEdge: {
value: JSON.parse(attributes.canDeleteEdgeWithValue)
},
canEditEdgeWeight: {
value: JSON.parse(attributes.canEditEdgeWeightWithValue)
}
};
}
}
let mockCurrentInteractionService = {
updateViewWithNewAnswer: () => {},
onSubmit: (answer, rulesService) => {},
registerCurrentInteraction: (submitAnswerFn, validateExpressionFn) => {
submitAnswerFn();
validateExpressionFn();
}
};
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot({
useDefaultLang: true,
isolate: false,
extend: false,
defaultLanguage: 'en'
})
],
declarations: [InteractiveGraphInput],
providers: [
{
provide: InteractionAttributesExtractorService,
useClass: mockInteractionAttributesExtractorService
},
{
provide: CurrentInteractionService,
useValue: mockCurrentInteractionService
}
],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
}));
beforeEach(() => {
currentInteractionService = TestBed.inject(CurrentInteractionService);
playerPositionService = TestBed.get(PlayerPositionService);
fixture = TestBed.createComponent(InteractiveGraphInput);
component = fixture.componentInstance;
i18nLanguageCodeService = TestBed.inject(I18nLanguageCodeService);
spyOn(i18nLanguageCodeService, 'isCurrentLanguageRTL').and.returnValue(
true);
component.graphWithValue = '{' +
' "isWeighted": false,' +
' "edges": [' +
' {' +
' "src": 0,' +
' "dst": 1,' +
' "weight": 1' +
' },' +
' {' +
' "src": 1,' +
' "dst": 2,' +
' "weight": 1' +
' }' +
' ],' +
' "isDirected": false,' +
' "vertices": [' +
' {' +
' "x": 150,' +
' "y": 50,' +
' "label": ""' +
' },' +
' {' +
' "x": 200,' +
' "y": 50,' +
' "label": ""' +
' },' +
' {' +
' "x": 150,' +
' "y": 100,' +
' "label": ""' +
' }' +
' ],' +
' "isLabeled": false' +
'}';
component.canAddVertexWithValue = 'true';
component.canDeleteVertexWithValue = 'true';
component.canMoveVertexWithValue = 'true';
component.canEditVertexLabelWithValue = 'true';
component.canAddEdgeWithValue = 'true';
component.canDeleteEdgeWithValue = 'true';
component.canEditEdgeWeightWithValue = 'true';
});
afterEach(() => {
component.ngOnDestroy();
});
it('should initialise component when user saves interaction', () => {
spyOn(component.componentSubscriptions, 'add');
spyOn(component, 'resetGraph').and.callThrough();
spyOn(currentInteractionService, 'registerCurrentInteraction')
.and.callThrough();
component.lastAnswer = null;
component.ngOnInit();
expect(component.componentSubscriptions.add).toHaveBeenCalled();
expect(component.errorMessage).toBe('');
expect(component.interactionIsActive).toBe(true);
expect(component.graph).toEqual({
isWeighted: false,
edges: [
{
src: 0,
dst: 1,
weight: 1
},
{
src: 1,
dst: 2,
weight: 1
}
],
isDirected: false,
vertices: [
{
x: 150,
y: 50,
label: ''
},
{
x: 200,
y: 50,
label: ''
},
{
x: 150,
y: 100,
label: ''
}
],
isLabeled: false
});
expect(component.resetGraph).toHaveBeenCalled();
expect(component.canAddVertex).toBe(true);
expect(component.canDeleteVertex).toBe(true);
expect(component.canEditVertexLabel).toBe(true);
expect(component.canMoveVertex).toBe(true);
expect(component.canAddEdge).toBe(true);
expect(component.canDeleteEdge).toBe(true);
expect(component.canEditEdgeWeight).toBe(true);
});
it('should initialise customization options as false if interaction is not' +
' active when component is initialised', () => {
component.lastAnswer = {
isWeighted: false,
edges: [
{
src: 0,
dst: 1,
weight: 1
},
{
src: 1,
dst: 2,
weight: 1
}
],
isDirected: false,
vertices: [
{
x: 250,
y: 50,
label: ''
},
{
x: 230,
y: 50,
label: ''
},
{
x: 350,
y: 100,
label: ''
}
],
isLabeled: false
};
component.ngOnInit();
expect(component.canAddVertex).toBe(false);
expect(component.canDeleteVertex).toBe(false);
expect(component.canEditVertexLabel).toBe(false);
expect(component.canMoveVertex).toBe(false);
expect(component.canAddEdge).toBe(false);
expect(component.canDeleteEdge).toBe(false);
expect(component.canEditEdgeWeight).toBe(false);
});
it('should get RTL language status correctly', () => {
expect(component.isLanguageRTL()).toEqual(true);
});
it('should set the last answer given by the user as the graph when the' +
' interaction is not longer active in the exploration player', () => {
component.lastAnswer = {
isWeighted: false,
edges: [
{
src: 0,
dst: 1,
weight: 1
},
{
src: 1,
dst: 2,
weight: 1
}
],
isDirected: false,
vertices: [
{
x: 250,
y: 50,
label: ''
},
{
x: 230,
y: 50,
label: ''
},
{
x: 350,
y: 100,
label: ''
}
],
isLabeled: false
};
component.graphWithValue = 'null';
component.ngOnInit();
component.graph = {
isWeighted: false,
edges: [
{
src: 0,
dst: 1,
weight: 1
},
{
src: 1,
dst: 2,
weight: 1
}
],
isDirected: false,
vertices: [
{
x: 250,
y: 50,
label: ''
},
{
x: 230,
y: 50,
label: ''
},
{
x: 350,
y: 100,
label: ''
}
],
isLabeled: false
};
});
it('should display error message to user if the graph is invalid', () => {
component.graphWithValue = 'null';
component.errorMessage = '';
component.resetGraph();
expect(component.errorMessage)
.toBe('I18N_INTERACTIONS_GRAPH_ERROR_INVALID');
});
it('should return true when a valid graph is passed', () => {
component.graph = {
isWeighted: false,
edges: [
{
src: 0,
dst: 1,
weight: 1
},
{
src: 1,
dst: 2,
weight: 1
}
],
isDirected: false,
vertices: [
{
x: 250,
y: 50,
label: ''
},
{
x: 230,
y: 50,
label: ''
},
{
x: 350,
y: 100,
label: ''
}
],
isLabeled: false
};
expect(component.validityCheckFn()).toBe(true);
});
it('should return false when a invalid graph is passed', () => {
component.graph = null;
expect(component.validityCheckFn()).toBe(false);
});
it('should set all customization options to false when a new card is' +
' displayed', () => {
spyOnProperty(playerPositionService, 'onNewCardAvailable').and.returnValue(
mockNewCardAvailableEmitter);
component.ngOnInit();
component.interactionIsActive = true;
component.canAddVertex = true;
component.canDeleteVertex = true;
component.canEditVertexLabel = true;
component.canMoveVertex = true;
component.canAddEdge = true;
component.canDeleteEdge = true;
component.canEditEdgeWeight = true;
mockNewCardAvailableEmitter.emit();
expect(component.canAddVertex).toBe(false);
expect(component.canDeleteVertex).toBe(false);
expect(component.canEditVertexLabel).toBe(false);
expect(component.canMoveVertex).toBe(false);
expect(component.canAddEdge).toBe(false);
expect(component.canDeleteEdge).toBe(false);
expect(component.canEditEdgeWeight).toBe(false);
});
}); | the_stack |
import { GlobalProps } from 'ojs/ojvcomponent';
import { ComponentChildren } from 'preact';
import { DataProvider } from '../ojdataprovider';
import Converter = require('../ojconverter');
import { dvtBaseComponent, dvtBaseComponentEventMap, dvtBaseComponentSettableProperties } from '../ojdvt-base';
import { JetElement, JetSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..';
export interface ojChart<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> extends dvtBaseComponent<ojChartSettableProperties<K, D, I, C>> {
animationOnDataChange?: 'auto' | 'slideToLeft' | 'slideToRight' | 'none';
animationOnDisplay?: 'auto' | 'alphaFade' | 'zoom' | 'none';
as?: string;
coordinateSystem?: 'polar' | 'cartesian';
data: DataProvider<K, D> | null;
dataCursor?: 'off' | 'on' | 'auto';
dataCursorBehavior?: 'smooth' | 'snap' | 'auto';
dataCursorPosition?: ojChart.DataCursorPosition;
dataLabel?: ((context: ojChart.DataLabelContext<K, D, I>) => (string[] | string | number[] | number));
dnd?: {
drag?: ojChart.DndDragConfigs<K, D, I>;
drop?: ojChart.DndDropConfigs;
};
dragMode?: 'pan' | 'zoom' | 'select' | 'off' | 'user';
drilling?: 'on' | 'seriesOnly' | 'groupsOnly' | 'off';
groupComparator?: ((context1: ojChart.GroupTemplateContext<D>, context2: ojChart.GroupTemplateContext<D>) => number);
hiddenCategories?: string[];
hideAndShowBehavior?: 'withRescale' | 'withoutRescale' | 'none';
highlightMatch?: 'any' | 'all';
highlightedCategories?: string[];
hoverBehavior?: 'dim' | 'none';
initialZooming?: 'first' | 'last' | 'none';
legend?: ojChart.Legend;
multiSeriesDrilling?: 'on' | 'off';
orientation?: 'horizontal' | 'vertical';
otherThreshold?: number;
overview?: ojChart.Overview<C>;
pieCenter?: ojChart.PieCenter;
plotArea?: ojChart.PlotArea;
polarGridShape?: 'polygon' | 'circle';
selection?: K[];
selectionMode?: 'none' | 'single' | 'multiple';
seriesComparator?: ((context1: ojChart.SeriesTemplateContext<D>, context2: ojChart.SeriesTemplateContext<D>) => number);
sorting?: 'ascending' | 'descending' | 'off';
splitDualY?: 'on' | 'off' | 'auto';
splitterPosition?: number;
stack?: 'on' | 'off';
stackLabel?: 'on' | 'off';
stackLabelProvider?: ((context: ojChart.StackLabelContext<K, D, I>) => (string));
styleDefaults?: ojChart.StyleDefaults;
timeAxisType?: 'enabled' | 'mixedFrequency' | 'skipGaps' | 'disabled' | 'auto';
tooltip?: {
renderer: dvtBaseComponent.PreventableDOMRendererFunction<ojChart.TooltipContext<K, D, I>>;
};
touchResponse?: 'touchStart' | 'auto';
type?: ojChart.ChartType;
valueFormats?: ojChart.ValueFormats;
xAxis?: ojChart.XAxis;
y2Axis?: ojChart.Y2Axis;
yAxis?: ojChart.YAxis;
zoomAndScroll?: 'delayedScrollOnly' | 'liveScrollOnly' | 'delayed' | 'live' | 'off';
zoomDirection?: 'x' | 'y' | 'auto';
translations: {
componentName?: string;
labelAndValue?: string;
labelClearSelection?: string;
labelClose?: string;
labelCountWithTotal?: string;
labelDataVisualization?: string;
labelDate?: string;
labelDefaultGroupName?: string;
labelGroup?: string;
labelHigh?: string;
labelInvalidData?: string;
labelLow?: string;
labelNoData?: string;
labelOpen?: string;
labelOther?: string;
labelPercentage?: string;
labelQ1?: string;
labelQ2?: string;
labelQ3?: string;
labelSeries?: string;
labelTargetValue?: string;
labelValue?: string;
labelVolume?: string;
labelX?: string;
labelY?: string;
labelZ?: string;
stateCollapsed?: string;
stateDrillable?: string;
stateExpanded?: string;
stateHidden?: string;
stateIsolated?: string;
stateMaximized?: string;
stateMinimized?: string;
stateSelected?: string;
stateUnselected?: string;
stateVisible?: string;
tooltipPan?: string;
tooltipSelect?: string;
tooltipZoom?: string;
};
addEventListener<T extends keyof ojChartEventMap<K, D, I, C>>(type: T, listener: (this: HTMLElement, ev: ojChartEventMap<K, D, I, C>[T]) => any, options?: (boolean |
AddEventListenerOptions)): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void;
getProperty<T extends keyof ojChartSettableProperties<K, D, I, C>>(property: T): ojChart<K, D, I, C>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojChartSettableProperties<K, D, I, C>>(property: T, value: ojChartSettableProperties<K, D, I, C>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojChartSettableProperties<K, D, I, C>>): void;
setProperties(properties: ojChartSettablePropertiesLenient<K, D, I, C>): void;
getContextByNode(node: Element): ojChart.PieCenterLabelContext | ojChart.LegendItemContext | ojChart.ReferenceObject | ojChart.GroupContext | ojChart.AxisTitleContext | ojChart.ItemContext |
ojChart.SeriesContext;
getLegend(): {
bounds: {
x: number;
y: number;
width: number;
height: number;
};
};
getPlotArea(): {
bounds: {
x: number;
y: number;
width: number;
height: number;
};
};
getValuesAt(x: number, y: number): {
x: number | string | null;
y: number | null;
y2: number | null;
};
getXAxis(): {
bounds: {
x: number;
y: number;
width: number;
height: number;
};
getPreferredSize(width: number, height: number): {
width: number;
height: number;
};
};
getY2Axis(): {
bounds: {
x: number;
y: number;
width: number;
height: number;
};
getPreferredSize(width: number, height: number): {
width: number;
height: number;
};
};
getYAxis(): {
bounds: {
x: number;
y: number;
width: number;
height: number;
};
getPreferredSize(width: number, height: number): {
width: number;
height: number;
};
};
}
export namespace ojChart {
interface ojDrill<K, D, I extends Array<Item<any, null>> | number[] | null> extends CustomEvent<{
data: Item<K, I> | number | null;
group: string;
groupData: Group[] | null;
id: string;
itemData: D;
series: string;
seriesData: Series<K, I> | null;
[propName: string]: any;
}> {
}
interface ojGroupDrill<K, D, I extends Array<Item<any, null>> | number[] | null> extends CustomEvent<{
group: string | string[];
groupData: Group[];
id: string;
items: Array<DrillItem<K, D, I>>;
[propName: string]: any;
}> {
}
interface ojItemDrill<K, D, I extends Array<Item<any, null>> | number[] | null> extends CustomEvent<{
data: Item<K, I> | number;
group: string | string[];
groupData: Group[];
id: string;
itemData: D;
series: string;
seriesData: Series<K, I>;
[propName: string]: any;
}> {
}
interface ojMultiSeriesDrill<K, D, I extends Array<Item<any, null>> | number[] | null> extends CustomEvent<{
items: Array<DrillItem<K, D, I>>;
series: string[];
seriesData: Series<K, I>;
[propName: string]: any;
}> {
}
interface ojSelectInput<K, D, I extends Array<Item<any, null>> | number[] | null> extends CustomEvent<{
endGroup: string;
items: string[];
selectionData: Array<{
data: Item<K, I> | number;
groupData: Group[];
itemData: D;
seriesData: Series<K, I>;
}>;
startGroup: string;
xMax: number;
xMin: number;
yMax: number;
yMin: number;
[propName: string]: any;
}> {
}
interface ojSeriesDrill<K, D, I extends Array<Item<any, null>> | number[] | null> extends CustomEvent<{
id: string;
items: Array<DrillItem<K, D, I>>;
series: string;
seriesData: Series<K, I>;
[propName: string]: any;
}> {
}
interface ojViewportChange extends CustomEvent<{
endGroup: string;
startGroup: string;
xMax: number;
xMin: number;
yMax: number;
yMin: number;
[propName: string]: any;
}> {
}
interface ojViewportChangeInput extends CustomEvent<{
endGroup: string;
startGroup: string;
xMax: number;
xMin: number;
yMax: number;
yMin: number;
[propName: string]: any;
}> {
}
// tslint:disable-next-line interface-over-type-literal
type animationOnDataChangeChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D,
I, C>["animationOnDataChange"]>;
// tslint:disable-next-line interface-over-type-literal
type animationOnDisplayChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["animationOnDisplay"]>;
// tslint:disable-next-line interface-over-type-literal
type asChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I, C>["as"]>;
// tslint:disable-next-line interface-over-type-literal
type coordinateSystemChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["coordinateSystem"]>;
// tslint:disable-next-line interface-over-type-literal
type dataChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I, C>["data"]>;
// tslint:disable-next-line interface-over-type-literal
type dataCursorChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["dataCursor"]>;
// tslint:disable-next-line interface-over-type-literal
type dataCursorBehaviorChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["dataCursorBehavior"]>;
// tslint:disable-next-line interface-over-type-literal
type dataCursorPositionChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["dataCursorPosition"]>;
// tslint:disable-next-line interface-over-type-literal
type dataLabelChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["dataLabel"]>;
// tslint:disable-next-line interface-over-type-literal
type dndChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I, C>["dnd"]>;
// tslint:disable-next-line interface-over-type-literal
type dragModeChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["dragMode"]>;
// tslint:disable-next-line interface-over-type-literal
type drillingChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["drilling"]>;
// tslint:disable-next-line interface-over-type-literal
type groupComparatorChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["groupComparator"]>;
// tslint:disable-next-line interface-over-type-literal
type hiddenCategoriesChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["hiddenCategories"]>;
// tslint:disable-next-line interface-over-type-literal
type hideAndShowBehaviorChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D,
I, C>["hideAndShowBehavior"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightMatchChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["highlightMatch"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightedCategoriesChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D,
I, C>["highlightedCategories"]>;
// tslint:disable-next-line interface-over-type-literal
type hoverBehaviorChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["hoverBehavior"]>;
// tslint:disable-next-line interface-over-type-literal
type initialZoomingChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["initialZooming"]>;
// tslint:disable-next-line interface-over-type-literal
type legendChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["legend"]>;
// tslint:disable-next-line interface-over-type-literal
type multiSeriesDrillingChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D,
I, C>["multiSeriesDrilling"]>;
// tslint:disable-next-line interface-over-type-literal
type orientationChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["orientation"]>;
// tslint:disable-next-line interface-over-type-literal
type otherThresholdChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["otherThreshold"]>;
// tslint:disable-next-line interface-over-type-literal
type overviewChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["overview"]>;
// tslint:disable-next-line interface-over-type-literal
type pieCenterChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["pieCenter"]>;
// tslint:disable-next-line interface-over-type-literal
type plotAreaChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["plotArea"]>;
// tslint:disable-next-line interface-over-type-literal
type polarGridShapeChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["polarGridShape"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["selection"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionModeChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["selectionMode"]>;
// tslint:disable-next-line interface-over-type-literal
type seriesComparatorChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["seriesComparator"]>;
// tslint:disable-next-line interface-over-type-literal
type sortingChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["sorting"]>;
// tslint:disable-next-line interface-over-type-literal
type splitDualYChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["splitDualY"]>;
// tslint:disable-next-line interface-over-type-literal
type splitterPositionChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["splitterPosition"]>;
// tslint:disable-next-line interface-over-type-literal
type stackChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["stack"]>;
// tslint:disable-next-line interface-over-type-literal
type stackLabelChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["stackLabel"]>;
// tslint:disable-next-line interface-over-type-literal
type stackLabelProviderChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["stackLabelProvider"]>;
// tslint:disable-next-line interface-over-type-literal
type styleDefaultsChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["styleDefaults"]>;
// tslint:disable-next-line interface-over-type-literal
type timeAxisTypeChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["timeAxisType"]>;
// tslint:disable-next-line interface-over-type-literal
type tooltipChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["tooltip"]>;
// tslint:disable-next-line interface-over-type-literal
type touchResponseChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["touchResponse"]>;
// tslint:disable-next-line interface-over-type-literal
type typeChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I, C>["type"]>;
// tslint:disable-next-line interface-over-type-literal
type valueFormatsChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["valueFormats"]>;
// tslint:disable-next-line interface-over-type-literal
type xAxisChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["xAxis"]>;
// tslint:disable-next-line interface-over-type-literal
type y2AxisChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["y2Axis"]>;
// tslint:disable-next-line interface-over-type-literal
type yAxisChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["yAxis"]>;
// tslint:disable-next-line interface-over-type-literal
type zoomAndScrollChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["zoomAndScroll"]>;
// tslint:disable-next-line interface-over-type-literal
type zoomDirectionChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["zoomDirection"]>;
//------------------------------------------------------------
// Start: generated events for inherited properties
//------------------------------------------------------------
// tslint:disable-next-line interface-over-type-literal
type trackResizeChanged<K, D extends DataItem<I> | any, I extends Array<Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = dvtBaseComponent.trackResizeChanged<ojChartSettableProperties<K, D, I, C>>;
// tslint:disable-next-line interface-over-type-literal
type AxisLine = {
lineColor?: string;
lineWidth?: number;
rendered?: 'off' | 'on' | 'auto';
};
// tslint:disable-next-line interface-over-type-literal
type AxisTitleContext = {
axis: 'xAxis' | 'yAxis' | 'y2Axis';
subId: string;
};
// tslint:disable-next-line interface-over-type-literal
type BoxPlotDefaults = {
medianSvgClassName?: string;
medianSvgStyle?: Partial<CSSStyleDeclaration>;
whiskerEndLength?: string;
whiskerEndSvgClassName?: string;
whiskerEndSvgStyle?: Partial<CSSStyleDeclaration>;
whiskerSvgClassName?: string;
whiskerSvgStyle?: Partial<CSSStyleDeclaration>;
};
// tslint:disable-next-line interface-over-type-literal
type BoxPlotStyle = {
medianSvgClassName?: string;
medianSvgStyle?: Partial<CSSStyleDeclaration>;
q2Color?: string;
q2SvgClassName?: string;
q2SvgStyle?: Partial<CSSStyleDeclaration>;
q3Color?: string;
q3SvgClassName?: string;
q3SvgStyle?: Partial<CSSStyleDeclaration>;
whiskerEndLength?: string;
whiskerEndSvgClassName?: string;
whiskerEndSvgStyle?: Partial<CSSStyleDeclaration>;
whiskerSvgClassName?: string;
whiskerSvgStyle?: Partial<CSSStyleDeclaration>;
};
// tslint:disable-next-line interface-over-type-literal
type CategoricalValueFormat<T extends string | number = string | number> = {
converter?: (Converter<T>);
scaling?: 'none' | 'thousand' | 'million' | 'billion' | 'trillion' | 'quadrillion' | 'auto';
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
// tslint:disable-next-line interface-over-type-literal
type ChartType = 'line' | 'area' | 'lineWithArea' | 'stock' | 'boxPlot' | 'combo' | 'pie' | 'scatter' | 'bubble' | 'funnel' | 'pyramid' | 'bar';
// tslint:disable-next-line interface-over-type-literal
type DataCursorDefaults = {
lineColor?: string;
lineStyle?: LineStyle;
lineWidth?: number;
markerColor?: string;
markerDisplayed?: 'off' | 'on';
markerSize?: number;
};
// tslint:disable-next-line interface-over-type-literal
type DataCursorPosition<T extends number | string = number | string> = {
x?: T;
y?: number;
y2?: number;
};
// tslint:disable-next-line interface-over-type-literal
type DataItem<I extends Array<Item<any, null>> | number[] | null, K = any, D = any> = {
borderColor?: string;
borderWidth?: number;
boxPlot?: BoxPlotStyle;
categories?: string[];
close?: number;
color?: string;
drilling?: 'on' | 'off' | 'inherit';
groupId: Array<(string | number)>;
high?: number;
label?: string | string[];
labelPosition?: 'center' | 'outsideSlice' | 'aboveMarker' | 'belowMarker' | 'beforeMarker' | 'afterMarker' | 'insideBarEdge' | 'outsideBarEdge' | 'none' | 'auto';
labelStyle?: Partial<CSSStyleDeclaration> | Array<Partial<CSSStyleDeclaration>>;
low?: number;
markerDisplayed?: 'on' | 'off' | 'auto';
markerShape?: 'circle' | 'diamond' | 'human' | 'plus' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | 'auto' | string;
markerSize?: number;
open?: number;
pattern?: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' |
'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'auto';
q1?: number;
q2?: number;
q3?: number;
seriesId: string | number;
shortDesc?: (string | ((context: ItemShortDescContext<K, D, I>) => string));
source?: string;
sourceHover?: string;
sourceHoverSelected?: string;
sourceSelected?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
targetValue?: number;
value?: number;
volume?: number;
x?: number | string;
y?: number;
z?: number;
};
// tslint:disable-next-line interface-over-type-literal
type DataLabelContext<K, D, I extends Array<Item<any, null>> | number[] | null> = {
close: number;
componentElement: Element;
data: Item<K, Array<Item<any, null>> | number[] | null> | number | null;
dimensions: {
height: number;
width: number;
};
group: string | string[];
groupData: Group[] | null;
high: number;
id: any;
itemData: D;
label: string;
low: number;
open: number;
q1: number;
q2: number;
q3: number;
series: string;
seriesData: Series<K, I> | null;
targetValue: number;
totalValue: number;
value: number;
volume: number;
x: number | string;
y: number;
z: number;
};
// tslint:disable-next-line interface-over-type-literal
type DndDragConfig<T> = {
dataTypes?: string | string[];
drag?: ((param0: Event) => void);
dragEnd?: ((param0: Event) => void);
dragStart?: ((event: Event, context: T) => void);
};
// tslint:disable-next-line interface-over-type-literal
type DndDragConfigs<K, D, I extends Array<Item<any, null>> | number[] | null> = {
groups?: DndDragConfig<DndGroup>;
items?: DndDragConfig<DndItem<K, D, I>>;
series?: DndDragConfig<DndSeries<K, I>>;
};
// tslint:disable-next-line interface-over-type-literal
type DndDrop = {
x: number | null;
y: number | null;
y2: number | null;
};
// tslint:disable-next-line interface-over-type-literal
type DndDropConfig = {
dataTypes?: string | string[];
dragEnter?: ((event: Event, context: DndDrop) => void);
dragLeave?: ((event: Event, context: DndDrop) => void);
dragOver?: ((event: Event, context: DndDrop) => void);
drop?: ((event: Event, context: DndDrop) => void);
};
// tslint:disable-next-line interface-over-type-literal
type DndDropConfigs = {
legend?: DndDropConfig;
plotArea?: DndDropConfig;
xAxis?: DndDropConfig;
y2Axis?: DndDropConfig;
yAxis?: DndDropConfig;
};
// tslint:disable-next-line interface-over-type-literal
type DndGroup = {
group: string | number | Array<(string | number)>;
id: string | number | Array<(string | number)>;
label: string;
};
// tslint:disable-next-line interface-over-type-literal
type DndItem<K, D, I extends Array<Item<any, null>> | number[] | null> = {
item: Array<DataLabelContext<K, D, I>>;
};
// tslint:disable-next-line interface-over-type-literal
type DndSeries<K, I extends Array<Item<any, null>> | number[] | null> = {
color: string;
componentElement: any;
id: string | number;
series: string | number;
seriesData: Series<K, I>;
};
// tslint:disable-next-line interface-over-type-literal
type DrillItem<K, D, I extends Array<Item<any, null>> | number[] | null> = {
data: Item<K, Array<Item<any, null>> | number[] | null> | number;
group: string | string[];
id: K;
itemData: D;
series: string;
};
// tslint:disable-next-line interface-over-type-literal
type Group = {
drilling?: 'on' | 'off' | 'inherit';
groups?: Group[];
id?: string | number;
labelStyle?: Partial<CSSStyleDeclaration>;
name?: string;
shortDesc?: string;
};
// tslint:disable-next-line interface-over-type-literal
type GroupContext = {
indexPath: any[];
subId: string;
};
// tslint:disable-next-line interface-over-type-literal
type GroupSeparatorDefaults = {
color?: string;
rendered?: 'off' | 'auto';
};
// tslint:disable-next-line interface-over-type-literal
type GroupTemplateContext<D> = {
componentElement: Element;
depth: number;
ids: string[];
index: number;
items: Array<{
data: D;
index: number;
key: any;
}>;
leaf: boolean;
};
// tslint:disable-next-line interface-over-type-literal
type GroupValueFormat = {
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string | string[];
};
// tslint:disable-next-line interface-over-type-literal
type Item<K, I extends Array<Item<any, null>> | number[] | null, D = any> = {
borderColor?: string;
borderWidth?: number;
boxPlot?: BoxPlotStyle;
categories?: string[];
close?: number;
color?: string;
drilling?: 'on' | 'off' | 'inherit';
high?: number;
id: K;
items?: I;
label?: string | string[];
labelPosition?: 'center' | 'outsideSlice' | 'aboveMarker' | 'belowMarker' | 'beforeMarker' | 'afterMarker' | 'insideBarEdge' | 'outsideBarEdge' | 'none' | 'auto';
labelStyle?: Partial<CSSStyleDeclaration> | Array<Partial<CSSStyleDeclaration>>;
low?: number;
markerDisplayed?: 'on' | 'off' | 'auto';
markerShape?: 'circle' | 'diamond' | 'human' | 'plus' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | 'auto' | string;
markerSize?: number;
open?: number;
pattern?: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' |
'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'auto';
q1?: number;
q2?: number;
q3?: number;
shortDesc?: (string | ((context: ItemShortDescContext<K, D, I>) => string));
source?: string;
sourceHover?: string;
sourceHoverSelected?: string;
sourceSelected?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
targetValue?: number;
value?: number;
volume?: number;
x?: number | string;
y?: number;
z?: number;
};
// tslint:disable-next-line interface-over-type-literal
type ItemContext = {
itemIndex: number;
seriesIndex: number;
subId: string;
};
// tslint:disable-next-line interface-over-type-literal
type ItemShortDescContext<K, D, I extends Array<Item<any, null>> | number[] | null> = {
close: number;
data: Item<K, Array<Item<any, null>> | number[] | null> | number | null;
group: string | string[];
groupData: Group[] | null;
high: number;
id: any;
itemData: D;
label: string;
low: number;
open: number;
q1: number;
q2: number;
q3: number;
series: string;
seriesData: Series<K, I> | null;
targetValue: number;
value: number;
volume: number;
x: number | string;
y: number;
z: number;
};
// tslint:disable-next-line interface-over-type-literal
type ItemTemplateContext<K = any, D = any> = {
componentElement: Element;
data: D;
index: number;
key: K;
};
// tslint:disable-next-line interface-over-type-literal
type LabelValueFormat = {
converter?: (Converter<string>);
scaling?: 'none' | 'thousand' | 'million' | 'billion' | 'trillion' | 'quadrillion' | 'auto';
};
// tslint:disable-next-line interface-over-type-literal
type Legend = {
backgroundColor?: string;
borderColor?: string;
maxSize?: string;
position?: 'start' | 'end' | 'bottom' | 'top' | 'auto';
referenceObjectSection?: LegendReferenceObjectSection;
rendered?: 'on' | 'off' | 'auto';
scrolling?: 'off' | 'asNeeded';
sections?: LegendSection[];
seriesSection?: LegendSeriesSection;
size?: string;
symbolHeight?: number;
symbolWidth?: number;
textStyle?: Partial<CSSStyleDeclaration>;
title?: string;
titleHalign?: 'center' | 'end' | 'start';
titleStyle?: Partial<CSSStyleDeclaration>;
};
// tslint:disable-next-line interface-over-type-literal
type LegendItem = {
borderColor?: string;
categories?: string[];
categoryVisibility?: 'hidden' | 'visible';
color?: string;
id?: string;
lineStyle?: 'dashed' | 'dotted' | 'solid';
lineWidth?: number;
markerColor?: string;
markerShape?: 'circle' | 'diamond' | 'ellipse' | 'human' | 'plus' | 'rectangle' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | string;
pattern?: 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' | 'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none' | 'smallChecker' | 'smallCrosshatch' |
'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle';
shortDesc?: string;
source?: string;
symbolType?: 'image' | 'line' | 'lineWithMarker' | 'marker';
text: string;
};
// tslint:disable-next-line interface-over-type-literal
type LegendItemContext = {
itemIndex: number;
sectionIndexPath: any[];
subId: string;
};
// tslint:disable-next-line interface-over-type-literal
type LegendReferenceObjectSection = {
title?: string;
titleHalign?: 'center' | 'end' | 'start';
titleStyle?: Partial<CSSStyleDeclaration>;
};
// tslint:disable-next-line interface-over-type-literal
type LegendSection = {
items?: LegendItem[];
sections?: LegendSection[];
title?: string;
titleHalign?: 'center' | 'end' | 'start';
titleStyle?: Partial<CSSStyleDeclaration>;
};
// tslint:disable-next-line interface-over-type-literal
type LegendSeriesSection = {
title?: string;
titleHalign?: 'center' | 'end' | 'start';
titleStyle?: Partial<CSSStyleDeclaration>;
};
// tslint:disable-next-line interface-over-type-literal
type LineStyle = 'dotted' | 'dashed' | 'solid';
// tslint:disable-next-line interface-over-type-literal
type LineType = 'curved' | 'stepped' | 'centeredStepped' | 'segmented' | 'centeredSegmented' | 'straight';
// tslint:disable-next-line interface-over-type-literal
type MajorTick = {
baselineColor?: 'inherit' | 'auto' | string;
baselineStyle?: LineStyle;
baselineWidth?: number;
lineColor?: string;
lineStyle?: LineStyle;
lineWidth?: number;
rendered?: 'off' | 'on' | 'auto';
};
// tslint:disable-next-line interface-over-type-literal
type MinorTick = {
lineColor?: string;
lineStyle?: LineStyle;
lineWidth?: number;
rendered?: 'off' | 'on' | 'auto';
};
// tslint:disable-next-line interface-over-type-literal
type NumericValueFormat = {
converter?: (Converter<number>);
scaling?: 'none' | 'thousand' | 'million' | 'billion' | 'trillion' | 'quadrillion' | 'auto';
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
// tslint:disable-next-line interface-over-type-literal
type Overview<C> = {
content?: C;
height?: string;
rendered?: 'on' | 'off';
};
// tslint:disable-next-line interface-over-type-literal
type PieCenter = {
converter?: (Converter<number>);
label?: number | string;
labelStyle?: Partial<CSSStyleDeclaration>;
renderer?: dvtBaseComponent.PreventableDOMRendererFunction<PieCenterContext>;
scaling?: 'none' | 'thousand' | 'million' | 'billion' | 'trillion' | 'quadrillion' | 'auto';
};
// tslint:disable-next-line interface-over-type-literal
type PieCenterContext = {
componentElement: Element;
innerBounds: {
height: number;
width: number;
x: number;
y: number;
};
label: string;
labelStyle: Partial<CSSStyleDeclaration>;
outerBounds: {
height: number;
width: number;
x: number;
y: number;
};
totalValue: number;
};
// tslint:disable-next-line interface-over-type-literal
type PieCenterLabelContext = {
subId: string;
};
// tslint:disable-next-line interface-over-type-literal
type PlotArea = {
backgroundColor?: string;
borderColor?: string;
borderWidth?: number;
rendered?: 'off' | 'on';
};
// tslint:disable-next-line interface-over-type-literal
type ReferenceObject = {
axis: 'xAxis' | 'yAxis' | 'y2Axis';
index: number;
subId: string;
};
// tslint:disable-next-line interface-over-type-literal
type ReferenceObjectItem<T extends number | string = number | string> = {
high?: number;
low?: number;
value?: number;
x?: T;
};
// tslint:disable-next-line interface-over-type-literal
type Series<K, I extends Array<Item<any, null>> | number[] | null> = {
areaColor?: string;
areaSvgClassName?: string;
areaSvgStyle?: Partial<CSSStyleDeclaration>;
assignedToY2?: 'on' | 'off';
borderColor?: string;
borderWidth?: number;
boxPlot?: BoxPlotStyle;
categories?: string[];
color?: string;
displayInLegend?: 'on' | 'off' | 'auto';
drilling?: 'on' | 'off' | 'inherit';
id?: string | number;
items?: (Array<Item<K, Array<Item<any, null>> | number[] | null>> | number[]);
lineStyle?: LineStyle;
lineType?: 'curved' | 'stepped' | 'centeredStepped' | 'segmented' | 'centeredSegmented' | 'straight' | 'none' | 'auto';
lineWidth?: number;
markerColor?: string;
markerDisplayed?: 'on' | 'off' | 'auto';
markerShape?: 'circle' | 'diamond' | 'human' | 'plus' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | 'auto' | string;
markerSize?: number;
markerSvgClassName?: string;
markerSvgStyle?: Partial<CSSStyleDeclaration>;
name?: string;
pattern?: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' |
'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'auto';
pieSliceExplode?: number;
shortDesc?: string;
source?: string;
sourceHover?: string;
sourceHoverSelected?: string;
sourceSelected?: string;
stackCategory?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
type?: 'bar' | 'line' | 'area' | 'lineWithArea' | 'candlestick' | 'boxPlot' | 'auto';
};
// tslint:disable-next-line interface-over-type-literal
type SeriesContext = {
itemIndex: number;
subId: string;
};
// tslint:disable-next-line interface-over-type-literal
type SeriesTemplateContext<D> = {
componentElement: Element;
id: string;
index: number;
items: Array<{
data: D;
index: number;
key: any;
}>;
};
// tslint:disable-next-line interface-over-type-literal
type SeriesValueFormat = {
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
// tslint:disable-next-line interface-over-type-literal
type StackLabelContext<K, D, I extends Array<Item<any, null>> | number[] | null> = {
data: Array<Item<K, Array<Item<any, null>> | number[] | null> | number | null>;
groupData: Group[] | null;
groups: string | string[];
itemData: D[];
value: number;
};
// tslint:disable-next-line interface-over-type-literal
type StyleDefaults = {
animationDownColor?: string;
animationDuration?: number;
animationIndicators?: 'none' | 'all';
animationUpColor?: string;
barGapRatio?: number;
borderColor?: string;
borderWidth?: number;
boxPlot?: BoxPlotDefaults;
colors?: string[];
dataCursor?: DataCursorDefaults;
dataItemGaps?: string;
dataLabelCollision?: 'fitInBounds' | 'none';
dataLabelPosition?: 'center' | 'outsideSlice' | 'aboveMarker' | 'belowMarker' | 'beforeMarker' | 'afterMarker' | 'insideBarEdge' | 'outsideBarEdge' | 'none' | 'auto';
dataLabelStyle?: Partial<CSSStyleDeclaration> | Array<Partial<CSSStyleDeclaration>>;
funnelBackgroundColor?: string;
groupSeparators?: GroupSeparatorDefaults;
hoverBehaviorDelay?: number;
lineStyle?: LineStyle;
lineType?: 'curved' | 'stepped' | 'centeredStepped' | 'segmented' | 'centeredSegmented' | 'straight' | 'none' | 'auto';
lineWidth?: number;
markerColor?: string;
markerDisplayed?: 'on' | 'off' | 'auto';
markerShape?: 'circle' | 'diamond' | 'human' | 'plus' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | 'auto' | string;
markerSize?: number;
marqueeBorderColor?: string;
marqueeColor?: string;
maxBarWidth?: number;
otherColor?: string;
patterns?: string[];
pieFeelerColor?: string;
pieInnerRadius?: number;
selectionEffect?: 'explode' | 'highlightAndExplode' | 'highlight';
seriesEffect?: 'color' | 'pattern' | 'gradient';
shapes?: string[];
stackLabelStyle?: Partial<CSSStyleDeclaration>;
stockFallingColor?: string;
stockRangeColor?: string;
stockRisingColor?: string;
stockVolumeColor?: string;
threeDEffect?: 'on' | 'off';
tooltipLabelStyle?: Partial<CSSStyleDeclaration>;
tooltipValueStyle?: Partial<CSSStyleDeclaration>;
};
// tslint:disable-next-line interface-over-type-literal
type TooltipContext<K, D, I extends Array<Item<any, null>> | number[] | null> = {
close: number;
color: string;
componentElement: Element;
data: Item<K, Array<Item<any, null>> | number[] | null> | number | null;
group: string | string[];
groupData: Group[] | null;
high: number;
id: any;
itemData: D;
label: string;
low: number;
open: number;
parentElement: Element;
q1: number;
q2: number;
q3: number;
series: string;
seriesData: Series<K, I> | null;
targetValue: number;
value: number;
volume: number;
x: number | string;
y: number;
z: number;
};
// tslint:disable-next-line interface-over-type-literal
type ValueFormats = {
close?: NumericValueFormat;
group?: GroupValueFormat;
high?: NumericValueFormat;
label?: LabelValueFormat;
low?: NumericValueFormat;
open?: NumericValueFormat;
q1?: NumericValueFormat;
q2?: NumericValueFormat;
q3?: NumericValueFormat;
series?: SeriesValueFormat;
targetValue?: NumericValueFormat;
value?: NumericValueFormat;
volume?: NumericValueFormat;
x?: CategoricalValueFormat;
y?: NumericValueFormat;
y2?: NumericValueFormat;
z?: NumericValueFormat;
};
// tslint:disable-next-line interface-over-type-literal
type XAxis<T extends number | string = number | string> = {
axisLine?: AxisLine;
baselineScaling?: 'min' | 'zero';
dataMax?: number;
dataMin?: number;
majorTick?: MajorTick;
max?: T;
maxSize?: string;
min?: T;
minStep?: number;
minorStep?: number;
minorTick?: MinorTick;
referenceObjects?: Array<XReferenceObject<T>>;
rendered?: 'off' | 'on';
scale?: 'log' | 'linear';
size?: string;
step?: number;
tickLabel?: XTickLabel<T>;
title?: string;
titleStyle?: Partial<CSSStyleDeclaration>;
viewportEndGroup?: T;
viewportMax?: T;
viewportMin?: T;
viewportStartGroup?: T;
};
// tslint:disable-next-line interface-over-type-literal
type XReferenceObject<T extends number | string = number | string> = {
categories?: string[];
color?: string;
displayInLegend?: 'on' | 'off';
high?: T;
id?: string;
lineStyle?: LineStyle;
lineWidth?: number;
location?: 'front' | 'back';
low?: T;
shortDesc?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
text?: string;
type?: 'area' | 'line';
value?: T;
};
// tslint:disable-next-line interface-over-type-literal
type XTickLabel<T extends number | string = number | string> = {
converter?: (Converter<T>);
rendered?: 'off' | 'on';
rotation?: 'none' | 'auto';
scaling?: 'none' | 'thousand' | 'million' | 'billion' | 'trillion' | 'quadrillion' | 'auto';
style?: Partial<CSSStyleDeclaration>;
};
// tslint:disable-next-line interface-over-type-literal
type Y2Axis = {
alignTickMarks?: 'off' | 'on';
axisLine?: AxisLine;
baselineScaling?: 'min' | 'zero';
dataMax?: number;
dataMin?: number;
majorTick?: MajorTick;
max?: number;
maxSize?: string;
min?: number;
minStep?: number;
minorStep?: number;
minorTick?: MinorTick;
position?: 'start' | 'end' | 'top' | 'bottom' | 'auto';
referenceObjects?: YReferenceObject[];
rendered?: 'off' | 'on';
scale?: 'log' | 'linear';
size?: string;
step?: number;
tickLabel?: YTickLabel;
title?: string;
titleStyle?: Partial<CSSStyleDeclaration>;
};
// tslint:disable-next-line interface-over-type-literal
type YAxis = {
axisLine?: AxisLine;
baselineScaling?: 'min' | 'zero';
dataMax?: number;
dataMin?: number;
majorTick?: MajorTick;
max?: number;
maxSize?: string;
min?: number;
minStep?: number;
minorStep?: number;
minorTick?: MinorTick;
position?: 'start' | 'end' | 'top' | 'bottom' | 'auto';
referenceObjects?: YReferenceObject[];
rendered?: 'off' | 'on';
scale?: 'log' | 'linear';
size?: string;
step?: number;
tickLabel?: YTickLabel;
title?: string;
titleStyle?: Partial<CSSStyleDeclaration>;
viewportMax?: number;
viewportMin?: number;
};
// tslint:disable-next-line interface-over-type-literal
type YReferenceObject = {
categories?: string[];
color?: string;
displayInLegend?: 'on' | 'off';
high?: number;
id?: string;
items?: ReferenceObjectItem[];
lineStyle?: LineStyle;
lineType?: LineType;
lineWidth?: number;
location?: 'front' | 'back';
low?: number;
shortDesc?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
text?: string;
type?: 'area' | 'line';
value?: number;
};
// tslint:disable-next-line interface-over-type-literal
type YTickLabel = {
converter?: (Converter<number>);
position?: 'inside' | 'outside';
rendered?: 'off' | 'on';
scaling?: 'none' | 'thousand' | 'million' | 'billion' | 'trillion' | 'quadrillion' | 'auto';
style?: Partial<CSSStyleDeclaration>;
};
}
export interface ojChartEventMap<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> extends dvtBaseComponentEventMap<ojChartSettableProperties<K, D, I, C>> {
'ojDrill': ojChart.ojDrill<K, D, I>;
'ojGroupDrill': ojChart.ojGroupDrill<K, D, I>;
'ojItemDrill': ojChart.ojItemDrill<K, D, I>;
'ojMultiSeriesDrill': ojChart.ojMultiSeriesDrill<K, D, I>;
'ojSelectInput': ojChart.ojSelectInput<K, D, I>;
'ojSeriesDrill': ojChart.ojSeriesDrill<K, D, I>;
'ojViewportChange': ojChart.ojViewportChange;
'ojViewportChangeInput': ojChart.ojViewportChangeInput;
'animationOnDataChangeChanged': JetElementCustomEvent<ojChart<K, D, I, C>["animationOnDataChange"]>;
'animationOnDisplayChanged': JetElementCustomEvent<ojChart<K, D, I, C>["animationOnDisplay"]>;
'asChanged': JetElementCustomEvent<ojChart<K, D, I, C>["as"]>;
'coordinateSystemChanged': JetElementCustomEvent<ojChart<K, D, I, C>["coordinateSystem"]>;
'dataChanged': JetElementCustomEvent<ojChart<K, D, I, C>["data"]>;
'dataCursorChanged': JetElementCustomEvent<ojChart<K, D, I, C>["dataCursor"]>;
'dataCursorBehaviorChanged': JetElementCustomEvent<ojChart<K, D, I, C>["dataCursorBehavior"]>;
'dataCursorPositionChanged': JetElementCustomEvent<ojChart<K, D, I, C>["dataCursorPosition"]>;
'dataLabelChanged': JetElementCustomEvent<ojChart<K, D, I, C>["dataLabel"]>;
'dndChanged': JetElementCustomEvent<ojChart<K, D, I, C>["dnd"]>;
'dragModeChanged': JetElementCustomEvent<ojChart<K, D, I, C>["dragMode"]>;
'drillingChanged': JetElementCustomEvent<ojChart<K, D, I, C>["drilling"]>;
'groupComparatorChanged': JetElementCustomEvent<ojChart<K, D, I, C>["groupComparator"]>;
'hiddenCategoriesChanged': JetElementCustomEvent<ojChart<K, D, I, C>["hiddenCategories"]>;
'hideAndShowBehaviorChanged': JetElementCustomEvent<ojChart<K, D, I, C>["hideAndShowBehavior"]>;
'highlightMatchChanged': JetElementCustomEvent<ojChart<K, D, I, C>["highlightMatch"]>;
'highlightedCategoriesChanged': JetElementCustomEvent<ojChart<K, D, I, C>["highlightedCategories"]>;
'hoverBehaviorChanged': JetElementCustomEvent<ojChart<K, D, I, C>["hoverBehavior"]>;
'initialZoomingChanged': JetElementCustomEvent<ojChart<K, D, I, C>["initialZooming"]>;
'legendChanged': JetElementCustomEvent<ojChart<K, D, I, C>["legend"]>;
'multiSeriesDrillingChanged': JetElementCustomEvent<ojChart<K, D, I, C>["multiSeriesDrilling"]>;
'orientationChanged': JetElementCustomEvent<ojChart<K, D, I, C>["orientation"]>;
'otherThresholdChanged': JetElementCustomEvent<ojChart<K, D, I, C>["otherThreshold"]>;
'overviewChanged': JetElementCustomEvent<ojChart<K, D, I, C>["overview"]>;
'pieCenterChanged': JetElementCustomEvent<ojChart<K, D, I, C>["pieCenter"]>;
'plotAreaChanged': JetElementCustomEvent<ojChart<K, D, I, C>["plotArea"]>;
'polarGridShapeChanged': JetElementCustomEvent<ojChart<K, D, I, C>["polarGridShape"]>;
'selectionChanged': JetElementCustomEvent<ojChart<K, D, I, C>["selection"]>;
'selectionModeChanged': JetElementCustomEvent<ojChart<K, D, I, C>["selectionMode"]>;
'seriesComparatorChanged': JetElementCustomEvent<ojChart<K, D, I, C>["seriesComparator"]>;
'sortingChanged': JetElementCustomEvent<ojChart<K, D, I, C>["sorting"]>;
'splitDualYChanged': JetElementCustomEvent<ojChart<K, D, I, C>["splitDualY"]>;
'splitterPositionChanged': JetElementCustomEvent<ojChart<K, D, I, C>["splitterPosition"]>;
'stackChanged': JetElementCustomEvent<ojChart<K, D, I, C>["stack"]>;
'stackLabelChanged': JetElementCustomEvent<ojChart<K, D, I, C>["stackLabel"]>;
'stackLabelProviderChanged': JetElementCustomEvent<ojChart<K, D, I, C>["stackLabelProvider"]>;
'styleDefaultsChanged': JetElementCustomEvent<ojChart<K, D, I, C>["styleDefaults"]>;
'timeAxisTypeChanged': JetElementCustomEvent<ojChart<K, D, I, C>["timeAxisType"]>;
'tooltipChanged': JetElementCustomEvent<ojChart<K, D, I, C>["tooltip"]>;
'touchResponseChanged': JetElementCustomEvent<ojChart<K, D, I, C>["touchResponse"]>;
'typeChanged': JetElementCustomEvent<ojChart<K, D, I, C>["type"]>;
'valueFormatsChanged': JetElementCustomEvent<ojChart<K, D, I, C>["valueFormats"]>;
'xAxisChanged': JetElementCustomEvent<ojChart<K, D, I, C>["xAxis"]>;
'y2AxisChanged': JetElementCustomEvent<ojChart<K, D, I, C>["y2Axis"]>;
'yAxisChanged': JetElementCustomEvent<ojChart<K, D, I, C>["yAxis"]>;
'zoomAndScrollChanged': JetElementCustomEvent<ojChart<K, D, I, C>["zoomAndScroll"]>;
'zoomDirectionChanged': JetElementCustomEvent<ojChart<K, D, I, C>["zoomDirection"]>;
'trackResizeChanged': JetElementCustomEvent<ojChart<K, D, I, C>["trackResize"]>;
}
export interface ojChartSettableProperties<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> extends dvtBaseComponentSettableProperties {
animationOnDataChange?: 'auto' | 'slideToLeft' | 'slideToRight' | 'none';
animationOnDisplay?: 'auto' | 'alphaFade' | 'zoom' | 'none';
as?: string;
coordinateSystem?: 'polar' | 'cartesian';
data: DataProvider<K, D> | null;
dataCursor?: 'off' | 'on' | 'auto';
dataCursorBehavior?: 'smooth' | 'snap' | 'auto';
dataCursorPosition?: ojChart.DataCursorPosition;
dataLabel?: ((context: ojChart.DataLabelContext<K, D, I>) => (string[] | string | number[] | number));
dnd?: {
drag?: ojChart.DndDragConfigs<K, D, I>;
drop?: ojChart.DndDropConfigs;
};
dragMode?: 'pan' | 'zoom' | 'select' | 'off' | 'user';
drilling?: 'on' | 'seriesOnly' | 'groupsOnly' | 'off';
groupComparator?: ((context1: ojChart.GroupTemplateContext<D>, context2: ojChart.GroupTemplateContext<D>) => number);
hiddenCategories?: string[];
hideAndShowBehavior?: 'withRescale' | 'withoutRescale' | 'none';
highlightMatch?: 'any' | 'all';
highlightedCategories?: string[];
hoverBehavior?: 'dim' | 'none';
initialZooming?: 'first' | 'last' | 'none';
legend?: ojChart.Legend;
multiSeriesDrilling?: 'on' | 'off';
orientation?: 'horizontal' | 'vertical';
otherThreshold?: number;
overview?: ojChart.Overview<C>;
pieCenter?: ojChart.PieCenter;
plotArea?: ojChart.PlotArea;
polarGridShape?: 'polygon' | 'circle';
selection?: K[];
selectionMode?: 'none' | 'single' | 'multiple';
seriesComparator?: ((context1: ojChart.SeriesTemplateContext<D>, context2: ojChart.SeriesTemplateContext<D>) => number);
sorting?: 'ascending' | 'descending' | 'off';
splitDualY?: 'on' | 'off' | 'auto';
splitterPosition?: number;
stack?: 'on' | 'off';
stackLabel?: 'on' | 'off';
stackLabelProvider?: ((context: ojChart.StackLabelContext<K, D, I>) => (string));
styleDefaults?: ojChart.StyleDefaults;
timeAxisType?: 'enabled' | 'mixedFrequency' | 'skipGaps' | 'disabled' | 'auto';
tooltip?: {
renderer: dvtBaseComponent.PreventableDOMRendererFunction<ojChart.TooltipContext<K, D, I>>;
};
touchResponse?: 'touchStart' | 'auto';
type?: ojChart.ChartType;
valueFormats?: ojChart.ValueFormats;
xAxis?: ojChart.XAxis;
y2Axis?: ojChart.Y2Axis;
yAxis?: ojChart.YAxis;
zoomAndScroll?: 'delayedScrollOnly' | 'liveScrollOnly' | 'delayed' | 'live' | 'off';
zoomDirection?: 'x' | 'y' | 'auto';
translations: {
componentName?: string;
labelAndValue?: string;
labelClearSelection?: string;
labelClose?: string;
labelCountWithTotal?: string;
labelDataVisualization?: string;
labelDate?: string;
labelDefaultGroupName?: string;
labelGroup?: string;
labelHigh?: string;
labelInvalidData?: string;
labelLow?: string;
labelNoData?: string;
labelOpen?: string;
labelOther?: string;
labelPercentage?: string;
labelQ1?: string;
labelQ2?: string;
labelQ3?: string;
labelSeries?: string;
labelTargetValue?: string;
labelValue?: string;
labelVolume?: string;
labelX?: string;
labelY?: string;
labelZ?: string;
stateCollapsed?: string;
stateDrillable?: string;
stateExpanded?: string;
stateHidden?: string;
stateIsolated?: string;
stateMaximized?: string;
stateMinimized?: string;
stateSelected?: string;
stateUnselected?: string;
stateVisible?: string;
tooltipPan?: string;
tooltipSelect?: string;
tooltipZoom?: string;
};
}
export interface ojChartSettablePropertiesLenient<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> extends Partial<ojChartSettableProperties<K, D, I, C>> {
[key: string]: any;
}
export interface ojChartGroup extends JetElement<ojChartGroupSettableProperties> {
drilling?: 'on' | 'off' | 'inherit';
labelStyle?: Partial<CSSStyleDeclaration>;
name?: string;
shortDesc?: string;
addEventListener<T extends keyof ojChartGroupEventMap>(type: T, listener: (this: HTMLElement, ev: ojChartGroupEventMap[T]) => any, options?: (boolean | AddEventListenerOptions)): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void;
getProperty<T extends keyof ojChartGroupSettableProperties>(property: T): ojChartGroup[T];
getProperty(property: string): any;
setProperty<T extends keyof ojChartGroupSettableProperties>(property: T, value: ojChartGroupSettableProperties[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojChartGroupSettableProperties>): void;
setProperties(properties: ojChartGroupSettablePropertiesLenient): void;
}
export namespace ojChartGroup {
// tslint:disable-next-line interface-over-type-literal
type drillingChanged = JetElementCustomEvent<ojChartGroup["drilling"]>;
// tslint:disable-next-line interface-over-type-literal
type labelStyleChanged = JetElementCustomEvent<ojChartGroup["labelStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type nameChanged = JetElementCustomEvent<ojChartGroup["name"]>;
// tslint:disable-next-line interface-over-type-literal
type shortDescChanged = JetElementCustomEvent<ojChartGroup["shortDesc"]>;
}
export interface ojChartGroupEventMap extends HTMLElementEventMap {
'drillingChanged': JetElementCustomEvent<ojChartGroup["drilling"]>;
'labelStyleChanged': JetElementCustomEvent<ojChartGroup["labelStyle"]>;
'nameChanged': JetElementCustomEvent<ojChartGroup["name"]>;
'shortDescChanged': JetElementCustomEvent<ojChartGroup["shortDesc"]>;
}
export interface ojChartGroupSettableProperties extends JetSettableProperties {
drilling?: 'on' | 'off' | 'inherit';
labelStyle?: Partial<CSSStyleDeclaration>;
name?: string;
shortDesc?: string;
}
export interface ojChartGroupSettablePropertiesLenient extends Partial<ojChartGroupSettableProperties> {
[key: string]: any;
}
export interface ojChartItem<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] |
null> extends dvtBaseComponent<ojChartItemSettableProperties<K, D, I>> {
borderColor?: string;
borderWidth?: number;
boxPlot?: ojChart.BoxPlotStyle;
categories?: string[];
close?: number;
color?: string;
drilling?: 'on' | 'off' | 'inherit';
groupId: Array<(string | number)>;
high?: number;
items?: (Array<ojChart.Item<any, null>> | number[]);
label?: string | string[];
labelPosition?: 'center' | 'outsideSlice' | 'aboveMarker' | 'belowMarker' | 'beforeMarker' | 'afterMarker' | 'insideBarEdge' | 'outsideBarEdge' | 'none' | 'auto';
labelStyle?: Partial<CSSStyleDeclaration> | Array<Partial<CSSStyleDeclaration>>;
low?: number;
markerDisplayed?: 'on' | 'off' | 'auto';
markerShape?: 'circle' | 'diamond' | 'human' | 'plus' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | 'auto' | string;
markerSize?: number;
open?: number;
pattern?: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' |
'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'auto';
q1?: number;
q2?: number;
q3?: number;
seriesId: string | number;
shortDesc?: (string | ((context: ojChart.ItemShortDescContext<K, D, I>) => string));
source?: string;
sourceHover?: string;
sourceHoverSelected?: string;
sourceSelected?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
targetValue?: number;
value?: number;
volume?: number;
x?: number | string;
y?: number;
z?: number;
addEventListener<T extends keyof ojChartItemEventMap<K, D, I>>(type: T, listener: (this: HTMLElement, ev: ojChartItemEventMap<K, D, I>[T]) => any, options?: (boolean |
AddEventListenerOptions)): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void;
getProperty<T extends keyof ojChartItemSettableProperties<K, D, I>>(property: T): ojChartItem<K, D, I>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojChartItemSettableProperties<K, D, I>>(property: T, value: ojChartItemSettableProperties<K, D, I>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojChartItemSettableProperties<K, D, I>>): void;
setProperties(properties: ojChartItemSettablePropertiesLenient<K, D, I>): void;
}
export namespace ojChartItem {
// tslint:disable-next-line interface-over-type-literal
type borderColorChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["borderColor"]>;
// tslint:disable-next-line interface-over-type-literal
type borderWidthChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["borderWidth"]>;
// tslint:disable-next-line interface-over-type-literal
type boxPlotChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["boxPlot"]>;
// tslint:disable-next-line interface-over-type-literal
type categoriesChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["categories"]>;
// tslint:disable-next-line interface-over-type-literal
type closeChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["close"]>;
// tslint:disable-next-line interface-over-type-literal
type colorChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["color"]>;
// tslint:disable-next-line interface-over-type-literal
type drillingChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["drilling"]>;
// tslint:disable-next-line interface-over-type-literal
type groupIdChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["groupId"]>;
// tslint:disable-next-line interface-over-type-literal
type highChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["high"]>;
// tslint:disable-next-line interface-over-type-literal
type itemsChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["items"]>;
// tslint:disable-next-line interface-over-type-literal
type labelChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["label"]>;
// tslint:disable-next-line interface-over-type-literal
type labelPositionChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["labelPosition"]>;
// tslint:disable-next-line interface-over-type-literal
type labelStyleChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["labelStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type lowChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["low"]>;
// tslint:disable-next-line interface-over-type-literal
type markerDisplayedChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K,
D, I>["markerDisplayed"]>;
// tslint:disable-next-line interface-over-type-literal
type markerShapeChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["markerShape"]>;
// tslint:disable-next-line interface-over-type-literal
type markerSizeChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["markerSize"]>;
// tslint:disable-next-line interface-over-type-literal
type openChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["open"]>;
// tslint:disable-next-line interface-over-type-literal
type patternChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["pattern"]>;
// tslint:disable-next-line interface-over-type-literal
type q1Changed<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D, I>["q1"]>;
// tslint:disable-next-line interface-over-type-literal
type q2Changed<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D, I>["q2"]>;
// tslint:disable-next-line interface-over-type-literal
type q3Changed<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D, I>["q3"]>;
// tslint:disable-next-line interface-over-type-literal
type seriesIdChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["seriesId"]>;
// tslint:disable-next-line interface-over-type-literal
type shortDescChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["shortDesc"]>;
// tslint:disable-next-line interface-over-type-literal
type sourceChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["source"]>;
// tslint:disable-next-line interface-over-type-literal
type sourceHoverChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["sourceHover"]>;
// tslint:disable-next-line interface-over-type-literal
type sourceHoverSelectedChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] |
null> = JetElementCustomEvent<ojChartItem<K, D, I>["sourceHoverSelected"]>;
// tslint:disable-next-line interface-over-type-literal
type sourceSelectedChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K,
D, I>["sourceSelected"]>;
// tslint:disable-next-line interface-over-type-literal
type svgClassNameChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["svgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type svgStyleChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["svgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type targetValueChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["targetValue"]>;
// tslint:disable-next-line interface-over-type-literal
type valueChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["value"]>;
// tslint:disable-next-line interface-over-type-literal
type volumeChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["volume"]>;
// tslint:disable-next-line interface-over-type-literal
type xChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D, I>["x"]>;
// tslint:disable-next-line interface-over-type-literal
type yChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D, I>["y"]>;
// tslint:disable-next-line interface-over-type-literal
type zChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D, I>["z"]>;
}
export interface ojChartItemEventMap<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] |
null> extends dvtBaseComponentEventMap<ojChartItemSettableProperties<K, D, I>> {
'borderColorChanged': JetElementCustomEvent<ojChartItem<K, D, I>["borderColor"]>;
'borderWidthChanged': JetElementCustomEvent<ojChartItem<K, D, I>["borderWidth"]>;
'boxPlotChanged': JetElementCustomEvent<ojChartItem<K, D, I>["boxPlot"]>;
'categoriesChanged': JetElementCustomEvent<ojChartItem<K, D, I>["categories"]>;
'closeChanged': JetElementCustomEvent<ojChartItem<K, D, I>["close"]>;
'colorChanged': JetElementCustomEvent<ojChartItem<K, D, I>["color"]>;
'drillingChanged': JetElementCustomEvent<ojChartItem<K, D, I>["drilling"]>;
'groupIdChanged': JetElementCustomEvent<ojChartItem<K, D, I>["groupId"]>;
'highChanged': JetElementCustomEvent<ojChartItem<K, D, I>["high"]>;
'itemsChanged': JetElementCustomEvent<ojChartItem<K, D, I>["items"]>;
'labelChanged': JetElementCustomEvent<ojChartItem<K, D, I>["label"]>;
'labelPositionChanged': JetElementCustomEvent<ojChartItem<K, D, I>["labelPosition"]>;
'labelStyleChanged': JetElementCustomEvent<ojChartItem<K, D, I>["labelStyle"]>;
'lowChanged': JetElementCustomEvent<ojChartItem<K, D, I>["low"]>;
'markerDisplayedChanged': JetElementCustomEvent<ojChartItem<K, D, I>["markerDisplayed"]>;
'markerShapeChanged': JetElementCustomEvent<ojChartItem<K, D, I>["markerShape"]>;
'markerSizeChanged': JetElementCustomEvent<ojChartItem<K, D, I>["markerSize"]>;
'openChanged': JetElementCustomEvent<ojChartItem<K, D, I>["open"]>;
'patternChanged': JetElementCustomEvent<ojChartItem<K, D, I>["pattern"]>;
'q1Changed': JetElementCustomEvent<ojChartItem<K, D, I>["q1"]>;
'q2Changed': JetElementCustomEvent<ojChartItem<K, D, I>["q2"]>;
'q3Changed': JetElementCustomEvent<ojChartItem<K, D, I>["q3"]>;
'seriesIdChanged': JetElementCustomEvent<ojChartItem<K, D, I>["seriesId"]>;
'shortDescChanged': JetElementCustomEvent<ojChartItem<K, D, I>["shortDesc"]>;
'sourceChanged': JetElementCustomEvent<ojChartItem<K, D, I>["source"]>;
'sourceHoverChanged': JetElementCustomEvent<ojChartItem<K, D, I>["sourceHover"]>;
'sourceHoverSelectedChanged': JetElementCustomEvent<ojChartItem<K, D, I>["sourceHoverSelected"]>;
'sourceSelectedChanged': JetElementCustomEvent<ojChartItem<K, D, I>["sourceSelected"]>;
'svgClassNameChanged': JetElementCustomEvent<ojChartItem<K, D, I>["svgClassName"]>;
'svgStyleChanged': JetElementCustomEvent<ojChartItem<K, D, I>["svgStyle"]>;
'targetValueChanged': JetElementCustomEvent<ojChartItem<K, D, I>["targetValue"]>;
'valueChanged': JetElementCustomEvent<ojChartItem<K, D, I>["value"]>;
'volumeChanged': JetElementCustomEvent<ojChartItem<K, D, I>["volume"]>;
'xChanged': JetElementCustomEvent<ojChartItem<K, D, I>["x"]>;
'yChanged': JetElementCustomEvent<ojChartItem<K, D, I>["y"]>;
'zChanged': JetElementCustomEvent<ojChartItem<K, D, I>["z"]>;
}
export interface ojChartItemSettableProperties<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] |
null> extends dvtBaseComponentSettableProperties {
borderColor?: string;
borderWidth?: number;
boxPlot?: ojChart.BoxPlotStyle;
categories?: string[];
close?: number;
color?: string;
drilling?: 'on' | 'off' | 'inherit';
groupId: Array<(string | number)>;
high?: number;
items?: (Array<ojChart.Item<any, null>> | number[]);
label?: string | string[];
labelPosition?: 'center' | 'outsideSlice' | 'aboveMarker' | 'belowMarker' | 'beforeMarker' | 'afterMarker' | 'insideBarEdge' | 'outsideBarEdge' | 'none' | 'auto';
labelStyle?: Partial<CSSStyleDeclaration> | Array<Partial<CSSStyleDeclaration>>;
low?: number;
markerDisplayed?: 'on' | 'off' | 'auto';
markerShape?: 'circle' | 'diamond' | 'human' | 'plus' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | 'auto' | string;
markerSize?: number;
open?: number;
pattern?: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' |
'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'auto';
q1?: number;
q2?: number;
q3?: number;
seriesId: string | number;
shortDesc?: (string | ((context: ojChart.ItemShortDescContext<K, D, I>) => string));
source?: string;
sourceHover?: string;
sourceHoverSelected?: string;
sourceSelected?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
targetValue?: number;
value?: number;
volume?: number;
x?: number | string;
y?: number;
z?: number;
}
export interface ojChartItemSettablePropertiesLenient<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] |
null> extends Partial<ojChartItemSettableProperties<K, D, I>> {
[key: string]: any;
}
export interface ojChartSeries extends JetElement<ojChartSeriesSettableProperties> {
areaColor?: string;
areaSvgClassName?: string;
areaSvgStyle?: Partial<CSSStyleDeclaration>;
assignedToY2?: 'on' | 'off';
borderColor?: string;
borderWidth?: number;
boxPlot?: ojChart.BoxPlotStyle;
categories?: string[];
color?: string;
displayInLegend?: 'on' | 'off' | 'auto';
drilling?: 'on' | 'off' | 'inherit';
lineStyle?: ojChart.LineStyle;
lineType?: 'curved' | 'stepped' | 'centeredStepped' | 'segmented' | 'centeredSegmented' | 'straight' | 'none' | 'auto';
lineWidth?: number;
markerColor?: string;
markerDisplayed?: 'on' | 'off' | 'auto';
markerShape?: 'circle' | 'diamond' | 'human' | 'plus' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | 'auto' | string;
markerSize?: number;
markerSvgClassName?: string;
markerSvgStyle?: Partial<CSSStyleDeclaration>;
name?: string;
pattern?: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' |
'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'auto';
pieSliceExplode?: number;
shortDesc?: string;
source?: string;
sourceHover?: string;
sourceHoverSelected?: string;
sourceSelected?: string;
stackCategory?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
type?: 'bar' | 'line' | 'area' | 'lineWithArea' | 'candlestick' | 'boxPlot' | 'auto';
addEventListener<T extends keyof ojChartSeriesEventMap>(type: T, listener: (this: HTMLElement, ev: ojChartSeriesEventMap[T]) => any, options?: (boolean | AddEventListenerOptions)): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void;
getProperty<T extends keyof ojChartSeriesSettableProperties>(property: T): ojChartSeries[T];
getProperty(property: string): any;
setProperty<T extends keyof ojChartSeriesSettableProperties>(property: T, value: ojChartSeriesSettableProperties[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojChartSeriesSettableProperties>): void;
setProperties(properties: ojChartSeriesSettablePropertiesLenient): void;
}
export namespace ojChartSeries {
// tslint:disable-next-line interface-over-type-literal
type areaColorChanged = JetElementCustomEvent<ojChartSeries["areaColor"]>;
// tslint:disable-next-line interface-over-type-literal
type areaSvgClassNameChanged = JetElementCustomEvent<ojChartSeries["areaSvgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type areaSvgStyleChanged = JetElementCustomEvent<ojChartSeries["areaSvgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type assignedToY2Changed = JetElementCustomEvent<ojChartSeries["assignedToY2"]>;
// tslint:disable-next-line interface-over-type-literal
type borderColorChanged = JetElementCustomEvent<ojChartSeries["borderColor"]>;
// tslint:disable-next-line interface-over-type-literal
type borderWidthChanged = JetElementCustomEvent<ojChartSeries["borderWidth"]>;
// tslint:disable-next-line interface-over-type-literal
type boxPlotChanged = JetElementCustomEvent<ojChartSeries["boxPlot"]>;
// tslint:disable-next-line interface-over-type-literal
type categoriesChanged = JetElementCustomEvent<ojChartSeries["categories"]>;
// tslint:disable-next-line interface-over-type-literal
type colorChanged = JetElementCustomEvent<ojChartSeries["color"]>;
// tslint:disable-next-line interface-over-type-literal
type displayInLegendChanged = JetElementCustomEvent<ojChartSeries["displayInLegend"]>;
// tslint:disable-next-line interface-over-type-literal
type drillingChanged = JetElementCustomEvent<ojChartSeries["drilling"]>;
// tslint:disable-next-line interface-over-type-literal
type lineStyleChanged = JetElementCustomEvent<ojChartSeries["lineStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type lineTypeChanged = JetElementCustomEvent<ojChartSeries["lineType"]>;
// tslint:disable-next-line interface-over-type-literal
type lineWidthChanged = JetElementCustomEvent<ojChartSeries["lineWidth"]>;
// tslint:disable-next-line interface-over-type-literal
type markerColorChanged = JetElementCustomEvent<ojChartSeries["markerColor"]>;
// tslint:disable-next-line interface-over-type-literal
type markerDisplayedChanged = JetElementCustomEvent<ojChartSeries["markerDisplayed"]>;
// tslint:disable-next-line interface-over-type-literal
type markerShapeChanged = JetElementCustomEvent<ojChartSeries["markerShape"]>;
// tslint:disable-next-line interface-over-type-literal
type markerSizeChanged = JetElementCustomEvent<ojChartSeries["markerSize"]>;
// tslint:disable-next-line interface-over-type-literal
type markerSvgClassNameChanged = JetElementCustomEvent<ojChartSeries["markerSvgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type markerSvgStyleChanged = JetElementCustomEvent<ojChartSeries["markerSvgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type nameChanged = JetElementCustomEvent<ojChartSeries["name"]>;
// tslint:disable-next-line interface-over-type-literal
type patternChanged = JetElementCustomEvent<ojChartSeries["pattern"]>;
// tslint:disable-next-line interface-over-type-literal
type pieSliceExplodeChanged = JetElementCustomEvent<ojChartSeries["pieSliceExplode"]>;
// tslint:disable-next-line interface-over-type-literal
type shortDescChanged = JetElementCustomEvent<ojChartSeries["shortDesc"]>;
// tslint:disable-next-line interface-over-type-literal
type sourceChanged = JetElementCustomEvent<ojChartSeries["source"]>;
// tslint:disable-next-line interface-over-type-literal
type sourceHoverChanged = JetElementCustomEvent<ojChartSeries["sourceHover"]>;
// tslint:disable-next-line interface-over-type-literal
type sourceHoverSelectedChanged = JetElementCustomEvent<ojChartSeries["sourceHoverSelected"]>;
// tslint:disable-next-line interface-over-type-literal
type sourceSelectedChanged = JetElementCustomEvent<ojChartSeries["sourceSelected"]>;
// tslint:disable-next-line interface-over-type-literal
type stackCategoryChanged = JetElementCustomEvent<ojChartSeries["stackCategory"]>;
// tslint:disable-next-line interface-over-type-literal
type svgClassNameChanged = JetElementCustomEvent<ojChartSeries["svgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type svgStyleChanged = JetElementCustomEvent<ojChartSeries["svgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type typeChanged = JetElementCustomEvent<ojChartSeries["type"]>;
}
export interface ojChartSeriesEventMap extends HTMLElementEventMap {
'areaColorChanged': JetElementCustomEvent<ojChartSeries["areaColor"]>;
'areaSvgClassNameChanged': JetElementCustomEvent<ojChartSeries["areaSvgClassName"]>;
'areaSvgStyleChanged': JetElementCustomEvent<ojChartSeries["areaSvgStyle"]>;
'assignedToY2Changed': JetElementCustomEvent<ojChartSeries["assignedToY2"]>;
'borderColorChanged': JetElementCustomEvent<ojChartSeries["borderColor"]>;
'borderWidthChanged': JetElementCustomEvent<ojChartSeries["borderWidth"]>;
'boxPlotChanged': JetElementCustomEvent<ojChartSeries["boxPlot"]>;
'categoriesChanged': JetElementCustomEvent<ojChartSeries["categories"]>;
'colorChanged': JetElementCustomEvent<ojChartSeries["color"]>;
'displayInLegendChanged': JetElementCustomEvent<ojChartSeries["displayInLegend"]>;
'drillingChanged': JetElementCustomEvent<ojChartSeries["drilling"]>;
'lineStyleChanged': JetElementCustomEvent<ojChartSeries["lineStyle"]>;
'lineTypeChanged': JetElementCustomEvent<ojChartSeries["lineType"]>;
'lineWidthChanged': JetElementCustomEvent<ojChartSeries["lineWidth"]>;
'markerColorChanged': JetElementCustomEvent<ojChartSeries["markerColor"]>;
'markerDisplayedChanged': JetElementCustomEvent<ojChartSeries["markerDisplayed"]>;
'markerShapeChanged': JetElementCustomEvent<ojChartSeries["markerShape"]>;
'markerSizeChanged': JetElementCustomEvent<ojChartSeries["markerSize"]>;
'markerSvgClassNameChanged': JetElementCustomEvent<ojChartSeries["markerSvgClassName"]>;
'markerSvgStyleChanged': JetElementCustomEvent<ojChartSeries["markerSvgStyle"]>;
'nameChanged': JetElementCustomEvent<ojChartSeries["name"]>;
'patternChanged': JetElementCustomEvent<ojChartSeries["pattern"]>;
'pieSliceExplodeChanged': JetElementCustomEvent<ojChartSeries["pieSliceExplode"]>;
'shortDescChanged': JetElementCustomEvent<ojChartSeries["shortDesc"]>;
'sourceChanged': JetElementCustomEvent<ojChartSeries["source"]>;
'sourceHoverChanged': JetElementCustomEvent<ojChartSeries["sourceHover"]>;
'sourceHoverSelectedChanged': JetElementCustomEvent<ojChartSeries["sourceHoverSelected"]>;
'sourceSelectedChanged': JetElementCustomEvent<ojChartSeries["sourceSelected"]>;
'stackCategoryChanged': JetElementCustomEvent<ojChartSeries["stackCategory"]>;
'svgClassNameChanged': JetElementCustomEvent<ojChartSeries["svgClassName"]>;
'svgStyleChanged': JetElementCustomEvent<ojChartSeries["svgStyle"]>;
'typeChanged': JetElementCustomEvent<ojChartSeries["type"]>;
}
export interface ojChartSeriesSettableProperties extends JetSettableProperties {
areaColor?: string;
areaSvgClassName?: string;
areaSvgStyle?: Partial<CSSStyleDeclaration>;
assignedToY2?: 'on' | 'off';
borderColor?: string;
borderWidth?: number;
boxPlot?: ojChart.BoxPlotStyle;
categories?: string[];
color?: string;
displayInLegend?: 'on' | 'off' | 'auto';
drilling?: 'on' | 'off' | 'inherit';
lineStyle?: ojChart.LineStyle;
lineType?: 'curved' | 'stepped' | 'centeredStepped' | 'segmented' | 'centeredSegmented' | 'straight' | 'none' | 'auto';
lineWidth?: number;
markerColor?: string;
markerDisplayed?: 'on' | 'off' | 'auto';
markerShape?: 'circle' | 'diamond' | 'human' | 'plus' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | 'auto' | string;
markerSize?: number;
markerSvgClassName?: string;
markerSvgStyle?: Partial<CSSStyleDeclaration>;
name?: string;
pattern?: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' |
'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'auto';
pieSliceExplode?: number;
shortDesc?: string;
source?: string;
sourceHover?: string;
sourceHoverSelected?: string;
sourceSelected?: string;
stackCategory?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
type?: 'bar' | 'line' | 'area' | 'lineWithArea' | 'candlestick' | 'boxPlot' | 'auto';
}
export interface ojChartSeriesSettablePropertiesLenient extends Partial<ojChartSeriesSettableProperties> {
[key: string]: any;
}
export interface ojSparkChart<K, D extends ojSparkChart.Item | any> extends dvtBaseComponent<ojSparkChartSettableProperties<K, D>> {
animationDuration?: number | null;
animationOnDataChange?: 'auto' | 'none';
animationOnDisplay?: 'auto' | 'none';
areaColor?: string;
areaSvgClassName?: string;
areaSvgStyle?: Partial<CSSStyleDeclaration>;
as?: string;
barGapRatio?: number;
baselineScaling?: 'zero' | 'min';
color?: string;
data: DataProvider<K, D> | null;
firstColor?: string;
highColor?: string;
lastColor?: string;
lineStyle?: 'dotted' | 'dashed' | 'solid';
lineType?: 'curved' | 'stepped' | 'centeredStepped' | 'segmented' | 'centeredSegmented' | 'none' | 'straight';
lineWidth?: number;
lowColor?: string;
markerShape?: 'auto' | 'circle' | 'diamond' | 'human' | 'plus' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | string;
markerSize?: number;
referenceObjects?: ojSparkChart.ReferenceObject[];
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
tooltip?: {
renderer: ((context: ojSparkChart.TooltipContext) => ({
insert: Element | string;
} | {
preventDefault: boolean;
})) | null;
};
type?: 'area' | 'lineWithArea' | 'bar' | 'line';
visualEffects?: 'none' | 'auto';
translations: {
componentName?: string;
labelAndValue?: string;
labelClearSelection?: string;
labelCountWithTotal?: string;
labelDataVisualization?: string;
labelInvalidData?: string;
labelNoData?: string;
stateCollapsed?: string;
stateDrillable?: string;
stateExpanded?: string;
stateHidden?: string;
stateIsolated?: string;
stateMaximized?: string;
stateMinimized?: string;
stateSelected?: string;
stateUnselected?: string;
stateVisible?: string;
};
addEventListener<T extends keyof ojSparkChartEventMap<K, D>>(type: T, listener: (this: HTMLElement, ev: ojSparkChartEventMap<K, D>[T]) => any, options?: (boolean | AddEventListenerOptions)): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void;
getProperty<T extends keyof ojSparkChartSettableProperties<K, D>>(property: T): ojSparkChart<K, D>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojSparkChartSettableProperties<K, D>>(property: T, value: ojSparkChartSettableProperties<K, D>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojSparkChartSettableProperties<K, D>>): void;
setProperties(properties: ojSparkChartSettablePropertiesLenient<K, D>): void;
}
export namespace ojSparkChart {
// tslint:disable-next-line interface-over-type-literal
type animationDurationChanged<K, D extends Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["animationDuration"]>;
// tslint:disable-next-line interface-over-type-literal
type animationOnDataChangeChanged<K, D extends Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["animationOnDataChange"]>;
// tslint:disable-next-line interface-over-type-literal
type animationOnDisplayChanged<K, D extends Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["animationOnDisplay"]>;
// tslint:disable-next-line interface-over-type-literal
type areaColorChanged<K, D extends Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["areaColor"]>;
// tslint:disable-next-line interface-over-type-literal
type areaSvgClassNameChanged<K, D extends Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["areaSvgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type areaSvgStyleChanged<K, D extends Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["areaSvgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type asChanged<K, D extends Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["as"]>;
// tslint:disable-next-line interface-over-type-literal
type barGapRatioChanged<K, D extends Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["barGapRatio"]>;
// tslint:disable-next-line interface-over-type-literal
type baselineScalingChanged<K, D extends Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["baselineScaling"]>;
// tslint:disable-next-line interface-over-type-literal
type colorChanged<K, D extends Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["color"]>;
// tslint:disable-next-line interface-over-type-literal
type dataChanged<K, D extends Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["data"]>;
// tslint:disable-next-line interface-over-type-literal
type firstColorChanged<K, D extends Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["firstColor"]>;
// tslint:disable-next-line interface-over-type-literal
type highColorChanged<K, D extends Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["highColor"]>;
// tslint:disable-next-line interface-over-type-literal
type lastColorChanged<K, D extends Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["lastColor"]>;
// tslint:disable-next-line interface-over-type-literal
type lineStyleChanged<K, D extends Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["lineStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type lineTypeChanged<K, D extends Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["lineType"]>;
// tslint:disable-next-line interface-over-type-literal
type lineWidthChanged<K, D extends Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["lineWidth"]>;
// tslint:disable-next-line interface-over-type-literal
type lowColorChanged<K, D extends Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["lowColor"]>;
// tslint:disable-next-line interface-over-type-literal
type markerShapeChanged<K, D extends Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["markerShape"]>;
// tslint:disable-next-line interface-over-type-literal
type markerSizeChanged<K, D extends Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["markerSize"]>;
// tslint:disable-next-line interface-over-type-literal
type referenceObjectsChanged<K, D extends Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["referenceObjects"]>;
// tslint:disable-next-line interface-over-type-literal
type svgClassNameChanged<K, D extends Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["svgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type svgStyleChanged<K, D extends Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["svgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type tooltipChanged<K, D extends Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["tooltip"]>;
// tslint:disable-next-line interface-over-type-literal
type typeChanged<K, D extends Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["type"]>;
// tslint:disable-next-line interface-over-type-literal
type visualEffectsChanged<K, D extends Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["visualEffects"]>;
//------------------------------------------------------------
// Start: generated events for inherited properties
//------------------------------------------------------------
// tslint:disable-next-line interface-over-type-literal
type trackResizeChanged<K, D extends Item | any> = dvtBaseComponent.trackResizeChanged<ojSparkChartSettableProperties<K, D>>;
// tslint:disable-next-line interface-over-type-literal
type Item = {
borderColor?: string;
color?: string;
date?: Date;
high?: number;
low?: number;
markerDisplayed?: 'on' | 'off';
markerShape?: 'square' | 'circle' | 'diamond' | 'plus' | 'triangleDown' | 'triangleUp' | 'human' | 'star' | 'auto' | string;
markerSize?: number;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
value?: number;
};
// tslint:disable-next-line interface-over-type-literal
type ItemContext = {
borderColor: string;
color: string;
date: Date;
high: number;
low: number;
value: number;
};
// tslint:disable-next-line interface-over-type-literal
type ItemTemplateContext<K = any, D = any> = {
componentElement: Element;
data: D;
index: number;
key: K;
};
// tslint:disable-next-line interface-over-type-literal
type ReferenceObject = {
color?: string;
high?: number;
lineStyle?: 'dotted' | 'dashed' | 'solid';
lineWidth?: number;
location?: 'front' | 'back';
low?: number;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
type?: 'area' | 'line';
value?: number;
};
// tslint:disable-next-line interface-over-type-literal
type TooltipContext = {
color: string;
componentElement: Element;
parentElement: Element;
};
}
export interface ojSparkChartEventMap<K, D extends ojSparkChart.Item | any> extends dvtBaseComponentEventMap<ojSparkChartSettableProperties<K, D>> {
'animationDurationChanged': JetElementCustomEvent<ojSparkChart<K, D>["animationDuration"]>;
'animationOnDataChangeChanged': JetElementCustomEvent<ojSparkChart<K, D>["animationOnDataChange"]>;
'animationOnDisplayChanged': JetElementCustomEvent<ojSparkChart<K, D>["animationOnDisplay"]>;
'areaColorChanged': JetElementCustomEvent<ojSparkChart<K, D>["areaColor"]>;
'areaSvgClassNameChanged': JetElementCustomEvent<ojSparkChart<K, D>["areaSvgClassName"]>;
'areaSvgStyleChanged': JetElementCustomEvent<ojSparkChart<K, D>["areaSvgStyle"]>;
'asChanged': JetElementCustomEvent<ojSparkChart<K, D>["as"]>;
'barGapRatioChanged': JetElementCustomEvent<ojSparkChart<K, D>["barGapRatio"]>;
'baselineScalingChanged': JetElementCustomEvent<ojSparkChart<K, D>["baselineScaling"]>;
'colorChanged': JetElementCustomEvent<ojSparkChart<K, D>["color"]>;
'dataChanged': JetElementCustomEvent<ojSparkChart<K, D>["data"]>;
'firstColorChanged': JetElementCustomEvent<ojSparkChart<K, D>["firstColor"]>;
'highColorChanged': JetElementCustomEvent<ojSparkChart<K, D>["highColor"]>;
'lastColorChanged': JetElementCustomEvent<ojSparkChart<K, D>["lastColor"]>;
'lineStyleChanged': JetElementCustomEvent<ojSparkChart<K, D>["lineStyle"]>;
'lineTypeChanged': JetElementCustomEvent<ojSparkChart<K, D>["lineType"]>;
'lineWidthChanged': JetElementCustomEvent<ojSparkChart<K, D>["lineWidth"]>;
'lowColorChanged': JetElementCustomEvent<ojSparkChart<K, D>["lowColor"]>;
'markerShapeChanged': JetElementCustomEvent<ojSparkChart<K, D>["markerShape"]>;
'markerSizeChanged': JetElementCustomEvent<ojSparkChart<K, D>["markerSize"]>;
'referenceObjectsChanged': JetElementCustomEvent<ojSparkChart<K, D>["referenceObjects"]>;
'svgClassNameChanged': JetElementCustomEvent<ojSparkChart<K, D>["svgClassName"]>;
'svgStyleChanged': JetElementCustomEvent<ojSparkChart<K, D>["svgStyle"]>;
'tooltipChanged': JetElementCustomEvent<ojSparkChart<K, D>["tooltip"]>;
'typeChanged': JetElementCustomEvent<ojSparkChart<K, D>["type"]>;
'visualEffectsChanged': JetElementCustomEvent<ojSparkChart<K, D>["visualEffects"]>;
'trackResizeChanged': JetElementCustomEvent<ojSparkChart<K, D>["trackResize"]>;
}
export interface ojSparkChartSettableProperties<K, D extends ojSparkChart.Item | any> extends dvtBaseComponentSettableProperties {
animationDuration?: number | null;
animationOnDataChange?: 'auto' | 'none';
animationOnDisplay?: 'auto' | 'none';
areaColor?: string;
areaSvgClassName?: string;
areaSvgStyle?: Partial<CSSStyleDeclaration>;
as?: string;
barGapRatio?: number;
baselineScaling?: 'zero' | 'min';
color?: string;
data: DataProvider<K, D> | null;
firstColor?: string;
highColor?: string;
lastColor?: string;
lineStyle?: 'dotted' | 'dashed' | 'solid';
lineType?: 'curved' | 'stepped' | 'centeredStepped' | 'segmented' | 'centeredSegmented' | 'none' | 'straight';
lineWidth?: number;
lowColor?: string;
markerShape?: 'auto' | 'circle' | 'diamond' | 'human' | 'plus' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | string;
markerSize?: number;
referenceObjects?: ojSparkChart.ReferenceObject[];
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
tooltip?: {
renderer: ((context: ojSparkChart.TooltipContext) => ({
insert: Element | string;
} | {
preventDefault: boolean;
})) | null;
};
type?: 'area' | 'lineWithArea' | 'bar' | 'line';
visualEffects?: 'none' | 'auto';
translations: {
componentName?: string;
labelAndValue?: string;
labelClearSelection?: string;
labelCountWithTotal?: string;
labelDataVisualization?: string;
labelInvalidData?: string;
labelNoData?: string;
stateCollapsed?: string;
stateDrillable?: string;
stateExpanded?: string;
stateHidden?: string;
stateIsolated?: string;
stateMaximized?: string;
stateMinimized?: string;
stateSelected?: string;
stateUnselected?: string;
stateVisible?: string;
};
}
export interface ojSparkChartSettablePropertiesLenient<K, D extends ojSparkChart.Item | any> extends Partial<ojSparkChartSettableProperties<K, D>> {
[key: string]: any;
}
export interface ojSparkChartItem extends JetElement<ojSparkChartItemSettableProperties> {
borderColor?: string;
color?: string;
date?: string;
high?: number | null;
low?: number | null;
markerDisplayed?: 'off' | 'on';
markerShape?: 'auto' | 'circle' | 'diamond' | 'human' | 'plus' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | string;
markerSize?: number;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
value?: number | null;
addEventListener<T extends keyof ojSparkChartItemEventMap>(type: T, listener: (this: HTMLElement, ev: ojSparkChartItemEventMap[T]) => any, options?: (boolean | AddEventListenerOptions)): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void;
getProperty<T extends keyof ojSparkChartItemSettableProperties>(property: T): ojSparkChartItem[T];
getProperty(property: string): any;
setProperty<T extends keyof ojSparkChartItemSettableProperties>(property: T, value: ojSparkChartItemSettableProperties[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojSparkChartItemSettableProperties>): void;
setProperties(properties: ojSparkChartItemSettablePropertiesLenient): void;
}
export namespace ojSparkChartItem {
// tslint:disable-next-line interface-over-type-literal
type borderColorChanged = JetElementCustomEvent<ojSparkChartItem["borderColor"]>;
// tslint:disable-next-line interface-over-type-literal
type colorChanged = JetElementCustomEvent<ojSparkChartItem["color"]>;
// tslint:disable-next-line interface-over-type-literal
type dateChanged = JetElementCustomEvent<ojSparkChartItem["date"]>;
// tslint:disable-next-line interface-over-type-literal
type highChanged = JetElementCustomEvent<ojSparkChartItem["high"]>;
// tslint:disable-next-line interface-over-type-literal
type lowChanged = JetElementCustomEvent<ojSparkChartItem["low"]>;
// tslint:disable-next-line interface-over-type-literal
type markerDisplayedChanged = JetElementCustomEvent<ojSparkChartItem["markerDisplayed"]>;
// tslint:disable-next-line interface-over-type-literal
type markerShapeChanged = JetElementCustomEvent<ojSparkChartItem["markerShape"]>;
// tslint:disable-next-line interface-over-type-literal
type markerSizeChanged = JetElementCustomEvent<ojSparkChartItem["markerSize"]>;
// tslint:disable-next-line interface-over-type-literal
type svgClassNameChanged = JetElementCustomEvent<ojSparkChartItem["svgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type svgStyleChanged = JetElementCustomEvent<ojSparkChartItem["svgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type valueChanged = JetElementCustomEvent<ojSparkChartItem["value"]>;
}
export interface ojSparkChartItemEventMap extends HTMLElementEventMap {
'borderColorChanged': JetElementCustomEvent<ojSparkChartItem["borderColor"]>;
'colorChanged': JetElementCustomEvent<ojSparkChartItem["color"]>;
'dateChanged': JetElementCustomEvent<ojSparkChartItem["date"]>;
'highChanged': JetElementCustomEvent<ojSparkChartItem["high"]>;
'lowChanged': JetElementCustomEvent<ojSparkChartItem["low"]>;
'markerDisplayedChanged': JetElementCustomEvent<ojSparkChartItem["markerDisplayed"]>;
'markerShapeChanged': JetElementCustomEvent<ojSparkChartItem["markerShape"]>;
'markerSizeChanged': JetElementCustomEvent<ojSparkChartItem["markerSize"]>;
'svgClassNameChanged': JetElementCustomEvent<ojSparkChartItem["svgClassName"]>;
'svgStyleChanged': JetElementCustomEvent<ojSparkChartItem["svgStyle"]>;
'valueChanged': JetElementCustomEvent<ojSparkChartItem["value"]>;
}
export interface ojSparkChartItemSettableProperties extends JetSettableProperties {
borderColor?: string;
color?: string;
date?: string;
high?: number | null;
low?: number | null;
markerDisplayed?: 'off' | 'on';
markerShape?: 'auto' | 'circle' | 'diamond' | 'human' | 'plus' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | string;
markerSize?: number;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
value?: number | null;
}
export interface ojSparkChartItemSettablePropertiesLenient extends Partial<ojSparkChartItemSettableProperties> {
[key: string]: any;
}
export type ChartElement<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = ojChart<K, D, I, C>;
export type ChartGroupElement = ojChartGroup;
export type ChartItemElement<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = ojChartItem<K, D, I>;
export type ChartSeriesElement = ojChartSeries;
export type SparkChartElement<K, D extends ojSparkChart.Item | any> = ojSparkChart<K, D>;
export type SparkChartItemElement = ojSparkChartItem;
export namespace ChartElement {
interface ojDrill<K, D, I extends Array<ojChart.Item<any, null>> | number[] | null> extends CustomEvent<{
data: ojChart.Item<K, I> | number | null;
group: string;
groupData: ojChart.Group[] | null;
id: string;
itemData: D;
series: string;
seriesData: ojChart.Series<K, I> | null;
[propName: string]: any;
}> {
}
interface ojGroupDrill<K, D, I extends Array<ojChart.Item<any, null>> | number[] | null> extends CustomEvent<{
group: string | string[];
groupData: ojChart.Group[];
id: string;
items: Array<ojChart.DrillItem<K, D, I>>;
[propName: string]: any;
}> {
}
interface ojItemDrill<K, D, I extends Array<ojChart.Item<any, null>> | number[] | null> extends CustomEvent<{
data: ojChart.Item<K, I> | number;
group: string | string[];
groupData: ojChart.Group[];
id: string;
itemData: D;
series: string;
seriesData: ojChart.Series<K, I>;
[propName: string]: any;
}> {
}
interface ojMultiSeriesDrill<K, D, I extends Array<ojChart.Item<any, null>> | number[] | null> extends CustomEvent<{
items: Array<ojChart.DrillItem<K, D, I>>;
series: string[];
seriesData: ojChart.Series<K, I>;
[propName: string]: any;
}> {
}
interface ojSelectInput<K, D, I extends Array<ojChart.Item<any, null>> | number[] | null> extends CustomEvent<{
endGroup: string;
items: string[];
selectionData: Array<{
data: ojChart.Item<K, I> | number;
groupData: ojChart.Group[];
itemData: D;
seriesData: ojChart.Series<K, I>;
}>;
startGroup: string;
xMax: number;
xMin: number;
yMax: number;
yMin: number;
[propName: string]: any;
}> {
}
interface ojSeriesDrill<K, D, I extends Array<ojChart.Item<any, null>> | number[] | null> extends CustomEvent<{
id: string;
items: Array<ojChart.DrillItem<K, D, I>>;
series: string;
seriesData: ojChart.Series<K, I>;
[propName: string]: any;
}> {
}
interface ojViewportChange extends CustomEvent<{
endGroup: string;
startGroup: string;
xMax: number;
xMin: number;
yMax: number;
yMin: number;
[propName: string]: any;
}> {
}
interface ojViewportChangeInput extends CustomEvent<{
endGroup: string;
startGroup: string;
xMax: number;
xMin: number;
yMax: number;
yMin: number;
[propName: string]: any;
}> {
}
// tslint:disable-next-line interface-over-type-literal
type animationOnDataChangeChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["animationOnDataChange"]>;
// tslint:disable-next-line interface-over-type-literal
type animationOnDisplayChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["animationOnDisplay"]>;
// tslint:disable-next-line interface-over-type-literal
type asChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D, I,
C>["as"]>;
// tslint:disable-next-line interface-over-type-literal
type coordinateSystemChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["coordinateSystem"]>;
// tslint:disable-next-line interface-over-type-literal
type dataChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D,
I, C>["data"]>;
// tslint:disable-next-line interface-over-type-literal
type dataCursorChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["dataCursor"]>;
// tslint:disable-next-line interface-over-type-literal
type dataCursorBehaviorChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["dataCursorBehavior"]>;
// tslint:disable-next-line interface-over-type-literal
type dataCursorPositionChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["dataCursorPosition"]>;
// tslint:disable-next-line interface-over-type-literal
type dataLabelChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["dataLabel"]>;
// tslint:disable-next-line interface-over-type-literal
type dndChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D,
I, C>["dnd"]>;
// tslint:disable-next-line interface-over-type-literal
type dragModeChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K,
D, I, C>["dragMode"]>;
// tslint:disable-next-line interface-over-type-literal
type drillingChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K,
D, I, C>["drilling"]>;
// tslint:disable-next-line interface-over-type-literal
type groupComparatorChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["groupComparator"]>;
// tslint:disable-next-line interface-over-type-literal
type hiddenCategoriesChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["hiddenCategories"]>;
// tslint:disable-next-line interface-over-type-literal
type hideAndShowBehaviorChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["hideAndShowBehavior"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightMatchChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["highlightMatch"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightedCategoriesChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["highlightedCategories"]>;
// tslint:disable-next-line interface-over-type-literal
type hoverBehaviorChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["hoverBehavior"]>;
// tslint:disable-next-line interface-over-type-literal
type initialZoomingChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["initialZooming"]>;
// tslint:disable-next-line interface-over-type-literal
type legendChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K,
D, I, C>["legend"]>;
// tslint:disable-next-line interface-over-type-literal
type multiSeriesDrillingChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["multiSeriesDrilling"]>;
// tslint:disable-next-line interface-over-type-literal
type orientationChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["orientation"]>;
// tslint:disable-next-line interface-over-type-literal
type otherThresholdChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["otherThreshold"]>;
// tslint:disable-next-line interface-over-type-literal
type overviewChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K,
D, I, C>["overview"]>;
// tslint:disable-next-line interface-over-type-literal
type pieCenterChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["pieCenter"]>;
// tslint:disable-next-line interface-over-type-literal
type plotAreaChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K,
D, I, C>["plotArea"]>;
// tslint:disable-next-line interface-over-type-literal
type polarGridShapeChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["polarGridShape"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["selection"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionModeChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["selectionMode"]>;
// tslint:disable-next-line interface-over-type-literal
type seriesComparatorChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["seriesComparator"]>;
// tslint:disable-next-line interface-over-type-literal
type sortingChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K,
D, I, C>["sorting"]>;
// tslint:disable-next-line interface-over-type-literal
type splitDualYChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["splitDualY"]>;
// tslint:disable-next-line interface-over-type-literal
type splitterPositionChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["splitterPosition"]>;
// tslint:disable-next-line interface-over-type-literal
type stackChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D,
I, C>["stack"]>;
// tslint:disable-next-line interface-over-type-literal
type stackLabelChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["stackLabel"]>;
// tslint:disable-next-line interface-over-type-literal
type stackLabelProviderChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["stackLabelProvider"]>;
// tslint:disable-next-line interface-over-type-literal
type styleDefaultsChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["styleDefaults"]>;
// tslint:disable-next-line interface-over-type-literal
type timeAxisTypeChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["timeAxisType"]>;
// tslint:disable-next-line interface-over-type-literal
type tooltipChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K,
D, I, C>["tooltip"]>;
// tslint:disable-next-line interface-over-type-literal
type touchResponseChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["touchResponse"]>;
// tslint:disable-next-line interface-over-type-literal
type typeChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D,
I, C>["type"]>;
// tslint:disable-next-line interface-over-type-literal
type valueFormatsChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["valueFormats"]>;
// tslint:disable-next-line interface-over-type-literal
type xAxisChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D,
I, C>["xAxis"]>;
// tslint:disable-next-line interface-over-type-literal
type y2AxisChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K,
D, I, C>["y2Axis"]>;
// tslint:disable-next-line interface-over-type-literal
type yAxisChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> | null> = JetElementCustomEvent<ojChart<K, D,
I, C>["yAxis"]>;
// tslint:disable-next-line interface-over-type-literal
type zoomAndScrollChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["zoomAndScroll"]>;
// tslint:disable-next-line interface-over-type-literal
type zoomDirectionChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = JetElementCustomEvent<ojChart<K, D, I, C>["zoomDirection"]>;
//------------------------------------------------------------
// Start: generated events for inherited properties
//------------------------------------------------------------
// tslint:disable-next-line interface-over-type-literal
type trackResizeChanged<K, D extends ojChart.DataItem<I> | any, I extends Array<ojChart.Item<any, null>> | number[] | null, C extends ojChart<K, D, I, null> |
null> = dvtBaseComponent.trackResizeChanged<ojChartSettableProperties<K, D, I, C>>;
// tslint:disable-next-line interface-over-type-literal
type AxisLine = {
lineColor?: string;
lineWidth?: number;
rendered?: 'off' | 'on' | 'auto';
};
// tslint:disable-next-line interface-over-type-literal
type BoxPlotDefaults = {
medianSvgClassName?: string;
medianSvgStyle?: Partial<CSSStyleDeclaration>;
whiskerEndLength?: string;
whiskerEndSvgClassName?: string;
whiskerEndSvgStyle?: Partial<CSSStyleDeclaration>;
whiskerSvgClassName?: string;
whiskerSvgStyle?: Partial<CSSStyleDeclaration>;
};
// tslint:disable-next-line interface-over-type-literal
type CategoricalValueFormat<T extends string | number = string | number> = {
converter?: (Converter<T>);
scaling?: 'none' | 'thousand' | 'million' | 'billion' | 'trillion' | 'quadrillion' | 'auto';
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
// tslint:disable-next-line interface-over-type-literal
type DataCursorDefaults = {
lineColor?: string;
lineStyle?: ojChart.LineStyle;
lineWidth?: number;
markerColor?: string;
markerDisplayed?: 'off' | 'on';
markerSize?: number;
};
// tslint:disable-next-line interface-over-type-literal
type DataItem<I extends Array<ojChart.Item<any, null>> | number[] | null, K = any, D = any> = {
borderColor?: string;
borderWidth?: number;
boxPlot?: ojChart.BoxPlotStyle;
categories?: string[];
close?: number;
color?: string;
drilling?: 'on' | 'off' | 'inherit';
groupId: Array<(string | number)>;
high?: number;
label?: string | string[];
labelPosition?: 'center' | 'outsideSlice' | 'aboveMarker' | 'belowMarker' | 'beforeMarker' | 'afterMarker' | 'insideBarEdge' | 'outsideBarEdge' | 'none' | 'auto';
labelStyle?: Partial<CSSStyleDeclaration> | Array<Partial<CSSStyleDeclaration>>;
low?: number;
markerDisplayed?: 'on' | 'off' | 'auto';
markerShape?: 'circle' | 'diamond' | 'human' | 'plus' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | 'auto' | string;
markerSize?: number;
open?: number;
pattern?: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' |
'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'auto';
q1?: number;
q2?: number;
q3?: number;
seriesId: string | number;
shortDesc?: (string | ((context: ojChart.ItemShortDescContext<K, D, I>) => string));
source?: string;
sourceHover?: string;
sourceHoverSelected?: string;
sourceSelected?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
targetValue?: number;
value?: number;
volume?: number;
x?: number | string;
y?: number;
z?: number;
};
// tslint:disable-next-line interface-over-type-literal
type DndDragConfig<T> = {
dataTypes?: string | string[];
drag?: ((param0: Event) => void);
dragEnd?: ((param0: Event) => void);
dragStart?: ((event: Event, context: T) => void);
};
// tslint:disable-next-line interface-over-type-literal
type DndDrop = {
x: number | null;
y: number | null;
y2: number | null;
};
// tslint:disable-next-line interface-over-type-literal
type DndDropConfigs = {
legend?: ojChart.DndDropConfig;
plotArea?: ojChart.DndDropConfig;
xAxis?: ojChart.DndDropConfig;
y2Axis?: ojChart.DndDropConfig;
yAxis?: ojChart.DndDropConfig;
};
// tslint:disable-next-line interface-over-type-literal
type DndItem<K, D, I extends Array<ojChart.Item<any, null>> | number[] | null> = {
item: Array<ojChart.DataLabelContext<K, D, I>>;
};
// tslint:disable-next-line interface-over-type-literal
type DrillItem<K, D, I extends Array<ojChart.Item<any, null>> | number[] | null> = {
data: ojChart.Item<K, Array<ojChart.Item<any, null>> | number[] | null> | number;
group: string | string[];
id: K;
itemData: D;
series: string;
};
// tslint:disable-next-line interface-over-type-literal
type GroupContext = {
indexPath: any[];
subId: string;
};
// tslint:disable-next-line interface-over-type-literal
type GroupTemplateContext<D> = {
componentElement: Element;
depth: number;
ids: string[];
index: number;
items: Array<{
data: D;
index: number;
key: any;
}>;
leaf: boolean;
};
// tslint:disable-next-line interface-over-type-literal
type Item<K, I extends Array<ojChart.Item<any, null>> | number[] | null, D = any> = {
borderColor?: string;
borderWidth?: number;
boxPlot?: ojChart.BoxPlotStyle;
categories?: string[];
close?: number;
color?: string;
drilling?: 'on' | 'off' | 'inherit';
high?: number;
id: K;
items?: I;
label?: string | string[];
labelPosition?: 'center' | 'outsideSlice' | 'aboveMarker' | 'belowMarker' | 'beforeMarker' | 'afterMarker' | 'insideBarEdge' | 'outsideBarEdge' | 'none' | 'auto';
labelStyle?: Partial<CSSStyleDeclaration> | Array<Partial<CSSStyleDeclaration>>;
low?: number;
markerDisplayed?: 'on' | 'off' | 'auto';
markerShape?: 'circle' | 'diamond' | 'human' | 'plus' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | 'auto' | string;
markerSize?: number;
open?: number;
pattern?: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' |
'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'auto';
q1?: number;
q2?: number;
q3?: number;
shortDesc?: (string | ((context: ojChart.ItemShortDescContext<K, D, I>) => string));
source?: string;
sourceHover?: string;
sourceHoverSelected?: string;
sourceSelected?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
targetValue?: number;
value?: number;
volume?: number;
x?: number | string;
y?: number;
z?: number;
};
// tslint:disable-next-line interface-over-type-literal
type ItemShortDescContext<K, D, I extends Array<ojChart.Item<any, null>> | number[] | null> = {
close: number;
data: ojChart.Item<K, Array<ojChart.Item<any, null>> | number[] | null> | number | null;
group: string | string[];
groupData: ojChart.Group[] | null;
high: number;
id: any;
itemData: D;
label: string;
low: number;
open: number;
q1: number;
q2: number;
q3: number;
series: string;
seriesData: ojChart.Series<K, I> | null;
targetValue: number;
value: number;
volume: number;
x: number | string;
y: number;
z: number;
};
// tslint:disable-next-line interface-over-type-literal
type LabelValueFormat = {
converter?: (Converter<string>);
scaling?: 'none' | 'thousand' | 'million' | 'billion' | 'trillion' | 'quadrillion' | 'auto';
};
// tslint:disable-next-line interface-over-type-literal
type LegendItem = {
borderColor?: string;
categories?: string[];
categoryVisibility?: 'hidden' | 'visible';
color?: string;
id?: string;
lineStyle?: 'dashed' | 'dotted' | 'solid';
lineWidth?: number;
markerColor?: string;
markerShape?: 'circle' | 'diamond' | 'ellipse' | 'human' | 'plus' | 'rectangle' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | string;
pattern?: 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' | 'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none' | 'smallChecker' | 'smallCrosshatch' |
'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle';
shortDesc?: string;
source?: string;
symbolType?: 'image' | 'line' | 'lineWithMarker' | 'marker';
text: string;
};
// tslint:disable-next-line interface-over-type-literal
type LegendReferenceObjectSection = {
title?: string;
titleHalign?: 'center' | 'end' | 'start';
titleStyle?: Partial<CSSStyleDeclaration>;
};
// tslint:disable-next-line interface-over-type-literal
type LegendSeriesSection = {
title?: string;
titleHalign?: 'center' | 'end' | 'start';
titleStyle?: Partial<CSSStyleDeclaration>;
};
// tslint:disable-next-line interface-over-type-literal
type LineType = 'curved' | 'stepped' | 'centeredStepped' | 'segmented' | 'centeredSegmented' | 'straight';
// tslint:disable-next-line interface-over-type-literal
type MinorTick = {
lineColor?: string;
lineStyle?: ojChart.LineStyle;
lineWidth?: number;
rendered?: 'off' | 'on' | 'auto';
};
// tslint:disable-next-line interface-over-type-literal
type Overview<C> = {
content?: C;
height?: string;
rendered?: 'on' | 'off';
};
// tslint:disable-next-line interface-over-type-literal
type PieCenterContext = {
componentElement: Element;
innerBounds: {
height: number;
width: number;
x: number;
y: number;
};
label: string;
labelStyle: Partial<CSSStyleDeclaration>;
outerBounds: {
height: number;
width: number;
x: number;
y: number;
};
totalValue: number;
};
// tslint:disable-next-line interface-over-type-literal
type PlotArea = {
backgroundColor?: string;
borderColor?: string;
borderWidth?: number;
rendered?: 'off' | 'on';
};
// tslint:disable-next-line interface-over-type-literal
type ReferenceObjectItem<T extends number | string = number | string> = {
high?: number;
low?: number;
value?: number;
x?: T;
};
// tslint:disable-next-line interface-over-type-literal
type SeriesContext = {
itemIndex: number;
subId: string;
};
// tslint:disable-next-line interface-over-type-literal
type SeriesValueFormat = {
tooltipDisplay?: 'off' | 'auto';
tooltipLabel?: string;
};
// tslint:disable-next-line interface-over-type-literal
type StyleDefaults = {
animationDownColor?: string;
animationDuration?: number;
animationIndicators?: 'none' | 'all';
animationUpColor?: string;
barGapRatio?: number;
borderColor?: string;
borderWidth?: number;
boxPlot?: ojChart.BoxPlotDefaults;
colors?: string[];
dataCursor?: ojChart.DataCursorDefaults;
dataItemGaps?: string;
dataLabelCollision?: 'fitInBounds' | 'none';
dataLabelPosition?: 'center' | 'outsideSlice' | 'aboveMarker' | 'belowMarker' | 'beforeMarker' | 'afterMarker' | 'insideBarEdge' | 'outsideBarEdge' | 'none' | 'auto';
dataLabelStyle?: Partial<CSSStyleDeclaration> | Array<Partial<CSSStyleDeclaration>>;
funnelBackgroundColor?: string;
groupSeparators?: ojChart.GroupSeparatorDefaults;
hoverBehaviorDelay?: number;
lineStyle?: ojChart.LineStyle;
lineType?: 'curved' | 'stepped' | 'centeredStepped' | 'segmented' | 'centeredSegmented' | 'straight' | 'none' | 'auto';
lineWidth?: number;
markerColor?: string;
markerDisplayed?: 'on' | 'off' | 'auto';
markerShape?: 'circle' | 'diamond' | 'human' | 'plus' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | 'auto' | string;
markerSize?: number;
marqueeBorderColor?: string;
marqueeColor?: string;
maxBarWidth?: number;
otherColor?: string;
patterns?: string[];
pieFeelerColor?: string;
pieInnerRadius?: number;
selectionEffect?: 'explode' | 'highlightAndExplode' | 'highlight';
seriesEffect?: 'color' | 'pattern' | 'gradient';
shapes?: string[];
stackLabelStyle?: Partial<CSSStyleDeclaration>;
stockFallingColor?: string;
stockRangeColor?: string;
stockRisingColor?: string;
stockVolumeColor?: string;
threeDEffect?: 'on' | 'off';
tooltipLabelStyle?: Partial<CSSStyleDeclaration>;
tooltipValueStyle?: Partial<CSSStyleDeclaration>;
};
// tslint:disable-next-line interface-over-type-literal
type ValueFormats = {
close?: ojChart.NumericValueFormat;
group?: ojChart.GroupValueFormat;
high?: ojChart.NumericValueFormat;
label?: ojChart.LabelValueFormat;
low?: ojChart.NumericValueFormat;
open?: ojChart.NumericValueFormat;
q1?: ojChart.NumericValueFormat;
q2?: ojChart.NumericValueFormat;
q3?: ojChart.NumericValueFormat;
series?: ojChart.SeriesValueFormat;
targetValue?: ojChart.NumericValueFormat;
value?: ojChart.NumericValueFormat;
volume?: ojChart.NumericValueFormat;
x?: ojChart.CategoricalValueFormat;
y?: ojChart.NumericValueFormat;
y2?: ojChart.NumericValueFormat;
z?: ojChart.NumericValueFormat;
};
// tslint:disable-next-line interface-over-type-literal
type XReferenceObject<T extends number | string = number | string> = {
categories?: string[];
color?: string;
displayInLegend?: 'on' | 'off';
high?: T;
id?: string;
lineStyle?: ojChart.LineStyle;
lineWidth?: number;
location?: 'front' | 'back';
low?: T;
shortDesc?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
text?: string;
type?: 'area' | 'line';
value?: T;
};
// tslint:disable-next-line interface-over-type-literal
type Y2Axis = {
alignTickMarks?: 'off' | 'on';
axisLine?: ojChart.AxisLine;
baselineScaling?: 'min' | 'zero';
dataMax?: number;
dataMin?: number;
majorTick?: ojChart.MajorTick;
max?: number;
maxSize?: string;
min?: number;
minStep?: number;
minorStep?: number;
minorTick?: ojChart.MinorTick;
position?: 'start' | 'end' | 'top' | 'bottom' | 'auto';
referenceObjects?: ojChart.YReferenceObject[];
rendered?: 'off' | 'on';
scale?: 'log' | 'linear';
size?: string;
step?: number;
tickLabel?: ojChart.YTickLabel;
title?: string;
titleStyle?: Partial<CSSStyleDeclaration>;
};
// tslint:disable-next-line interface-over-type-literal
type YReferenceObject = {
categories?: string[];
color?: string;
displayInLegend?: 'on' | 'off';
high?: number;
id?: string;
items?: ojChart.ReferenceObjectItem[];
lineStyle?: ojChart.LineStyle;
lineType?: ojChart.LineType;
lineWidth?: number;
location?: 'front' | 'back';
low?: number;
shortDesc?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
text?: string;
type?: 'area' | 'line';
value?: number;
};
}
export namespace ChartGroupElement {
// tslint:disable-next-line interface-over-type-literal
type drillingChanged = JetElementCustomEvent<ojChartGroup["drilling"]>;
// tslint:disable-next-line interface-over-type-literal
type labelStyleChanged = JetElementCustomEvent<ojChartGroup["labelStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type nameChanged = JetElementCustomEvent<ojChartGroup["name"]>;
// tslint:disable-next-line interface-over-type-literal
type shortDescChanged = JetElementCustomEvent<ojChartGroup["shortDesc"]>;
}
export namespace ChartItemElement {
// tslint:disable-next-line interface-over-type-literal
type borderColorChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["borderColor"]>;
// tslint:disable-next-line interface-over-type-literal
type borderWidthChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["borderWidth"]>;
// tslint:disable-next-line interface-over-type-literal
type boxPlotChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["boxPlot"]>;
// tslint:disable-next-line interface-over-type-literal
type categoriesChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["categories"]>;
// tslint:disable-next-line interface-over-type-literal
type closeChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["close"]>;
// tslint:disable-next-line interface-over-type-literal
type colorChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["color"]>;
// tslint:disable-next-line interface-over-type-literal
type drillingChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["drilling"]>;
// tslint:disable-next-line interface-over-type-literal
type groupIdChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["groupId"]>;
// tslint:disable-next-line interface-over-type-literal
type highChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["high"]>;
// tslint:disable-next-line interface-over-type-literal
type itemsChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["items"]>;
// tslint:disable-next-line interface-over-type-literal
type labelChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["label"]>;
// tslint:disable-next-line interface-over-type-literal
type labelPositionChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["labelPosition"]>;
// tslint:disable-next-line interface-over-type-literal
type labelStyleChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["labelStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type lowChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["low"]>;
// tslint:disable-next-line interface-over-type-literal
type markerDisplayedChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K,
D, I>["markerDisplayed"]>;
// tslint:disable-next-line interface-over-type-literal
type markerShapeChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["markerShape"]>;
// tslint:disable-next-line interface-over-type-literal
type markerSizeChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["markerSize"]>;
// tslint:disable-next-line interface-over-type-literal
type openChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["open"]>;
// tslint:disable-next-line interface-over-type-literal
type patternChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["pattern"]>;
// tslint:disable-next-line interface-over-type-literal
type q1Changed<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D, I>["q1"]>;
// tslint:disable-next-line interface-over-type-literal
type q2Changed<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D, I>["q2"]>;
// tslint:disable-next-line interface-over-type-literal
type q3Changed<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D, I>["q3"]>;
// tslint:disable-next-line interface-over-type-literal
type seriesIdChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["seriesId"]>;
// tslint:disable-next-line interface-over-type-literal
type shortDescChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["shortDesc"]>;
// tslint:disable-next-line interface-over-type-literal
type sourceChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["source"]>;
// tslint:disable-next-line interface-over-type-literal
type sourceHoverChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["sourceHover"]>;
// tslint:disable-next-line interface-over-type-literal
type sourceHoverSelectedChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] |
null> = JetElementCustomEvent<ojChartItem<K, D, I>["sourceHoverSelected"]>;
// tslint:disable-next-line interface-over-type-literal
type sourceSelectedChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K,
D, I>["sourceSelected"]>;
// tslint:disable-next-line interface-over-type-literal
type svgClassNameChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["svgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type svgStyleChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["svgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type targetValueChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["targetValue"]>;
// tslint:disable-next-line interface-over-type-literal
type valueChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["value"]>;
// tslint:disable-next-line interface-over-type-literal
type volumeChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D,
I>["volume"]>;
// tslint:disable-next-line interface-over-type-literal
type xChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D, I>["x"]>;
// tslint:disable-next-line interface-over-type-literal
type yChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D, I>["y"]>;
// tslint:disable-next-line interface-over-type-literal
type zChanged<K = any, D = any, I extends Array<ojChart.Item<any, null>> | number[] | null = Array<ojChart.Item<any, null>> | number[] | null> = JetElementCustomEvent<ojChartItem<K, D, I>["z"]>;
}
export namespace ChartSeriesElement {
// tslint:disable-next-line interface-over-type-literal
type areaColorChanged = JetElementCustomEvent<ojChartSeries["areaColor"]>;
// tslint:disable-next-line interface-over-type-literal
type areaSvgClassNameChanged = JetElementCustomEvent<ojChartSeries["areaSvgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type areaSvgStyleChanged = JetElementCustomEvent<ojChartSeries["areaSvgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type assignedToY2Changed = JetElementCustomEvent<ojChartSeries["assignedToY2"]>;
// tslint:disable-next-line interface-over-type-literal
type borderColorChanged = JetElementCustomEvent<ojChartSeries["borderColor"]>;
// tslint:disable-next-line interface-over-type-literal
type borderWidthChanged = JetElementCustomEvent<ojChartSeries["borderWidth"]>;
// tslint:disable-next-line interface-over-type-literal
type boxPlotChanged = JetElementCustomEvent<ojChartSeries["boxPlot"]>;
// tslint:disable-next-line interface-over-type-literal
type categoriesChanged = JetElementCustomEvent<ojChartSeries["categories"]>;
// tslint:disable-next-line interface-over-type-literal
type colorChanged = JetElementCustomEvent<ojChartSeries["color"]>;
// tslint:disable-next-line interface-over-type-literal
type displayInLegendChanged = JetElementCustomEvent<ojChartSeries["displayInLegend"]>;
// tslint:disable-next-line interface-over-type-literal
type drillingChanged = JetElementCustomEvent<ojChartSeries["drilling"]>;
// tslint:disable-next-line interface-over-type-literal
type lineStyleChanged = JetElementCustomEvent<ojChartSeries["lineStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type lineTypeChanged = JetElementCustomEvent<ojChartSeries["lineType"]>;
// tslint:disable-next-line interface-over-type-literal
type lineWidthChanged = JetElementCustomEvent<ojChartSeries["lineWidth"]>;
// tslint:disable-next-line interface-over-type-literal
type markerColorChanged = JetElementCustomEvent<ojChartSeries["markerColor"]>;
// tslint:disable-next-line interface-over-type-literal
type markerDisplayedChanged = JetElementCustomEvent<ojChartSeries["markerDisplayed"]>;
// tslint:disable-next-line interface-over-type-literal
type markerShapeChanged = JetElementCustomEvent<ojChartSeries["markerShape"]>;
// tslint:disable-next-line interface-over-type-literal
type markerSizeChanged = JetElementCustomEvent<ojChartSeries["markerSize"]>;
// tslint:disable-next-line interface-over-type-literal
type markerSvgClassNameChanged = JetElementCustomEvent<ojChartSeries["markerSvgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type markerSvgStyleChanged = JetElementCustomEvent<ojChartSeries["markerSvgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type nameChanged = JetElementCustomEvent<ojChartSeries["name"]>;
// tslint:disable-next-line interface-over-type-literal
type patternChanged = JetElementCustomEvent<ojChartSeries["pattern"]>;
// tslint:disable-next-line interface-over-type-literal
type pieSliceExplodeChanged = JetElementCustomEvent<ojChartSeries["pieSliceExplode"]>;
// tslint:disable-next-line interface-over-type-literal
type shortDescChanged = JetElementCustomEvent<ojChartSeries["shortDesc"]>;
// tslint:disable-next-line interface-over-type-literal
type sourceChanged = JetElementCustomEvent<ojChartSeries["source"]>;
// tslint:disable-next-line interface-over-type-literal
type sourceHoverChanged = JetElementCustomEvent<ojChartSeries["sourceHover"]>;
// tslint:disable-next-line interface-over-type-literal
type sourceHoverSelectedChanged = JetElementCustomEvent<ojChartSeries["sourceHoverSelected"]>;
// tslint:disable-next-line interface-over-type-literal
type sourceSelectedChanged = JetElementCustomEvent<ojChartSeries["sourceSelected"]>;
// tslint:disable-next-line interface-over-type-literal
type stackCategoryChanged = JetElementCustomEvent<ojChartSeries["stackCategory"]>;
// tslint:disable-next-line interface-over-type-literal
type svgClassNameChanged = JetElementCustomEvent<ojChartSeries["svgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type svgStyleChanged = JetElementCustomEvent<ojChartSeries["svgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type typeChanged = JetElementCustomEvent<ojChartSeries["type"]>;
}
export namespace SparkChartElement {
// tslint:disable-next-line interface-over-type-literal
type animationDurationChanged<K, D extends ojSparkChart.Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["animationDuration"]>;
// tslint:disable-next-line interface-over-type-literal
type animationOnDataChangeChanged<K, D extends ojSparkChart.Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["animationOnDataChange"]>;
// tslint:disable-next-line interface-over-type-literal
type animationOnDisplayChanged<K, D extends ojSparkChart.Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["animationOnDisplay"]>;
// tslint:disable-next-line interface-over-type-literal
type areaColorChanged<K, D extends ojSparkChart.Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["areaColor"]>;
// tslint:disable-next-line interface-over-type-literal
type areaSvgClassNameChanged<K, D extends ojSparkChart.Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["areaSvgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type areaSvgStyleChanged<K, D extends ojSparkChart.Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["areaSvgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type asChanged<K, D extends ojSparkChart.Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["as"]>;
// tslint:disable-next-line interface-over-type-literal
type barGapRatioChanged<K, D extends ojSparkChart.Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["barGapRatio"]>;
// tslint:disable-next-line interface-over-type-literal
type baselineScalingChanged<K, D extends ojSparkChart.Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["baselineScaling"]>;
// tslint:disable-next-line interface-over-type-literal
type colorChanged<K, D extends ojSparkChart.Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["color"]>;
// tslint:disable-next-line interface-over-type-literal
type dataChanged<K, D extends ojSparkChart.Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["data"]>;
// tslint:disable-next-line interface-over-type-literal
type firstColorChanged<K, D extends ojSparkChart.Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["firstColor"]>;
// tslint:disable-next-line interface-over-type-literal
type highColorChanged<K, D extends ojSparkChart.Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["highColor"]>;
// tslint:disable-next-line interface-over-type-literal
type lastColorChanged<K, D extends ojSparkChart.Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["lastColor"]>;
// tslint:disable-next-line interface-over-type-literal
type lineStyleChanged<K, D extends ojSparkChart.Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["lineStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type lineTypeChanged<K, D extends ojSparkChart.Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["lineType"]>;
// tslint:disable-next-line interface-over-type-literal
type lineWidthChanged<K, D extends ojSparkChart.Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["lineWidth"]>;
// tslint:disable-next-line interface-over-type-literal
type lowColorChanged<K, D extends ojSparkChart.Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["lowColor"]>;
// tslint:disable-next-line interface-over-type-literal
type markerShapeChanged<K, D extends ojSparkChart.Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["markerShape"]>;
// tslint:disable-next-line interface-over-type-literal
type markerSizeChanged<K, D extends ojSparkChart.Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["markerSize"]>;
// tslint:disable-next-line interface-over-type-literal
type referenceObjectsChanged<K, D extends ojSparkChart.Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["referenceObjects"]>;
// tslint:disable-next-line interface-over-type-literal
type svgClassNameChanged<K, D extends ojSparkChart.Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["svgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type svgStyleChanged<K, D extends ojSparkChart.Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["svgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type tooltipChanged<K, D extends ojSparkChart.Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["tooltip"]>;
// tslint:disable-next-line interface-over-type-literal
type typeChanged<K, D extends ojSparkChart.Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["type"]>;
// tslint:disable-next-line interface-over-type-literal
type visualEffectsChanged<K, D extends ojSparkChart.Item | any> = JetElementCustomEvent<ojSparkChart<K, D>["visualEffects"]>;
//------------------------------------------------------------
// Start: generated events for inherited properties
//------------------------------------------------------------
// tslint:disable-next-line interface-over-type-literal
type trackResizeChanged<K, D extends ojSparkChart.Item | any> = dvtBaseComponent.trackResizeChanged<ojSparkChartSettableProperties<K, D>>;
// tslint:disable-next-line interface-over-type-literal
type Item = {
borderColor?: string;
color?: string;
date?: Date;
high?: number;
low?: number;
markerDisplayed?: 'on' | 'off';
markerShape?: 'square' | 'circle' | 'diamond' | 'plus' | 'triangleDown' | 'triangleUp' | 'human' | 'star' | 'auto' | string;
markerSize?: number;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
value?: number;
};
// tslint:disable-next-line interface-over-type-literal
type ItemTemplateContext<K = any, D = any> = {
componentElement: Element;
data: D;
index: number;
key: K;
};
// tslint:disable-next-line interface-over-type-literal
type TooltipContext = {
color: string;
componentElement: Element;
parentElement: Element;
};
}
export namespace SparkChartItemElement {
// tslint:disable-next-line interface-over-type-literal
type borderColorChanged = JetElementCustomEvent<ojSparkChartItem["borderColor"]>;
// tslint:disable-next-line interface-over-type-literal
type colorChanged = JetElementCustomEvent<ojSparkChartItem["color"]>;
// tslint:disable-next-line interface-over-type-literal
type dateChanged = JetElementCustomEvent<ojSparkChartItem["date"]>;
// tslint:disable-next-line interface-over-type-literal
type highChanged = JetElementCustomEvent<ojSparkChartItem["high"]>;
// tslint:disable-next-line interface-over-type-literal
type lowChanged = JetElementCustomEvent<ojSparkChartItem["low"]>;
// tslint:disable-next-line interface-over-type-literal
type markerDisplayedChanged = JetElementCustomEvent<ojSparkChartItem["markerDisplayed"]>;
// tslint:disable-next-line interface-over-type-literal
type markerShapeChanged = JetElementCustomEvent<ojSparkChartItem["markerShape"]>;
// tslint:disable-next-line interface-over-type-literal
type markerSizeChanged = JetElementCustomEvent<ojSparkChartItem["markerSize"]>;
// tslint:disable-next-line interface-over-type-literal
type svgClassNameChanged = JetElementCustomEvent<ojSparkChartItem["svgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type svgStyleChanged = JetElementCustomEvent<ojSparkChartItem["svgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type valueChanged = JetElementCustomEvent<ojSparkChartItem["value"]>;
}
export interface ChartIntrinsicProps extends Partial<Readonly<ojChartSettableProperties<any, any, any, any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> {
onojDrill?: (value: ojChartEventMap<any, any, any, any>['ojDrill']) => void;
onojGroupDrill?: (value: ojChartEventMap<any, any, any, any>['ojGroupDrill']) => void;
onojItemDrill?: (value: ojChartEventMap<any, any, any, any>['ojItemDrill']) => void;
onojMultiSeriesDrill?: (value: ojChartEventMap<any, any, any, any>['ojMultiSeriesDrill']) => void;
onojSelectInput?: (value: ojChartEventMap<any, any, any, any>['ojSelectInput']) => void;
onojSeriesDrill?: (value: ojChartEventMap<any, any, any, any>['ojSeriesDrill']) => void;
onojViewportChange?: (value: ojChartEventMap<any, any, any, any>['ojViewportChange']) => void;
onojViewportChangeInput?: (value: ojChartEventMap<any, any, any, any>['ojViewportChangeInput']) => void;
onanimationOnDataChangeChanged?: (value: ojChartEventMap<any, any, any, any>['animationOnDataChangeChanged']) => void;
onanimationOnDisplayChanged?: (value: ojChartEventMap<any, any, any, any>['animationOnDisplayChanged']) => void;
onasChanged?: (value: ojChartEventMap<any, any, any, any>['asChanged']) => void;
oncoordinateSystemChanged?: (value: ojChartEventMap<any, any, any, any>['coordinateSystemChanged']) => void;
ondataChanged?: (value: ojChartEventMap<any, any, any, any>['dataChanged']) => void;
ondataCursorChanged?: (value: ojChartEventMap<any, any, any, any>['dataCursorChanged']) => void;
ondataCursorBehaviorChanged?: (value: ojChartEventMap<any, any, any, any>['dataCursorBehaviorChanged']) => void;
ondataCursorPositionChanged?: (value: ojChartEventMap<any, any, any, any>['dataCursorPositionChanged']) => void;
ondataLabelChanged?: (value: ojChartEventMap<any, any, any, any>['dataLabelChanged']) => void;
ondndChanged?: (value: ojChartEventMap<any, any, any, any>['dndChanged']) => void;
ondragModeChanged?: (value: ojChartEventMap<any, any, any, any>['dragModeChanged']) => void;
ondrillingChanged?: (value: ojChartEventMap<any, any, any, any>['drillingChanged']) => void;
ongroupComparatorChanged?: (value: ojChartEventMap<any, any, any, any>['groupComparatorChanged']) => void;
onhiddenCategoriesChanged?: (value: ojChartEventMap<any, any, any, any>['hiddenCategoriesChanged']) => void;
onhideAndShowBehaviorChanged?: (value: ojChartEventMap<any, any, any, any>['hideAndShowBehaviorChanged']) => void;
onhighlightMatchChanged?: (value: ojChartEventMap<any, any, any, any>['highlightMatchChanged']) => void;
onhighlightedCategoriesChanged?: (value: ojChartEventMap<any, any, any, any>['highlightedCategoriesChanged']) => void;
onhoverBehaviorChanged?: (value: ojChartEventMap<any, any, any, any>['hoverBehaviorChanged']) => void;
oninitialZoomingChanged?: (value: ojChartEventMap<any, any, any, any>['initialZoomingChanged']) => void;
onlegendChanged?: (value: ojChartEventMap<any, any, any, any>['legendChanged']) => void;
onmultiSeriesDrillingChanged?: (value: ojChartEventMap<any, any, any, any>['multiSeriesDrillingChanged']) => void;
onorientationChanged?: (value: ojChartEventMap<any, any, any, any>['orientationChanged']) => void;
onotherThresholdChanged?: (value: ojChartEventMap<any, any, any, any>['otherThresholdChanged']) => void;
onoverviewChanged?: (value: ojChartEventMap<any, any, any, any>['overviewChanged']) => void;
onpieCenterChanged?: (value: ojChartEventMap<any, any, any, any>['pieCenterChanged']) => void;
onplotAreaChanged?: (value: ojChartEventMap<any, any, any, any>['plotAreaChanged']) => void;
onpolarGridShapeChanged?: (value: ojChartEventMap<any, any, any, any>['polarGridShapeChanged']) => void;
onselectionChanged?: (value: ojChartEventMap<any, any, any, any>['selectionChanged']) => void;
onselectionModeChanged?: (value: ojChartEventMap<any, any, any, any>['selectionModeChanged']) => void;
onseriesComparatorChanged?: (value: ojChartEventMap<any, any, any, any>['seriesComparatorChanged']) => void;
onsortingChanged?: (value: ojChartEventMap<any, any, any, any>['sortingChanged']) => void;
onsplitDualYChanged?: (value: ojChartEventMap<any, any, any, any>['splitDualYChanged']) => void;
onsplitterPositionChanged?: (value: ojChartEventMap<any, any, any, any>['splitterPositionChanged']) => void;
onstackChanged?: (value: ojChartEventMap<any, any, any, any>['stackChanged']) => void;
onstackLabelChanged?: (value: ojChartEventMap<any, any, any, any>['stackLabelChanged']) => void;
onstackLabelProviderChanged?: (value: ojChartEventMap<any, any, any, any>['stackLabelProviderChanged']) => void;
onstyleDefaultsChanged?: (value: ojChartEventMap<any, any, any, any>['styleDefaultsChanged']) => void;
ontimeAxisTypeChanged?: (value: ojChartEventMap<any, any, any, any>['timeAxisTypeChanged']) => void;
ontooltipChanged?: (value: ojChartEventMap<any, any, any, any>['tooltipChanged']) => void;
ontouchResponseChanged?: (value: ojChartEventMap<any, any, any, any>['touchResponseChanged']) => void;
ontypeChanged?: (value: ojChartEventMap<any, any, any, any>['typeChanged']) => void;
onvalueFormatsChanged?: (value: ojChartEventMap<any, any, any, any>['valueFormatsChanged']) => void;
onxAxisChanged?: (value: ojChartEventMap<any, any, any, any>['xAxisChanged']) => void;
ony2AxisChanged?: (value: ojChartEventMap<any, any, any, any>['y2AxisChanged']) => void;
onyAxisChanged?: (value: ojChartEventMap<any, any, any, any>['yAxisChanged']) => void;
onzoomAndScrollChanged?: (value: ojChartEventMap<any, any, any, any>['zoomAndScrollChanged']) => void;
onzoomDirectionChanged?: (value: ojChartEventMap<any, any, any, any>['zoomDirectionChanged']) => void;
ontrackResizeChanged?: (value: ojChartEventMap<any, any, any, any>['trackResizeChanged']) => void;
children?: ComponentChildren;
}
export interface ChartGroupIntrinsicProps extends Partial<Readonly<ojChartGroupSettableProperties>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> {
ondrillingChanged?: (value: ojChartGroupEventMap['drillingChanged']) => void;
onlabelStyleChanged?: (value: ojChartGroupEventMap['labelStyleChanged']) => void;
onnameChanged?: (value: ojChartGroupEventMap['nameChanged']) => void;
onshortDescChanged?: (value: ojChartGroupEventMap['shortDescChanged']) => void;
children?: ComponentChildren;
}
export interface ChartItemIntrinsicProps extends Partial<Readonly<ojChartItemSettableProperties<any, any, any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> {
onborderColorChanged?: (value: ojChartItemEventMap<any, any, any>['borderColorChanged']) => void;
onborderWidthChanged?: (value: ojChartItemEventMap<any, any, any>['borderWidthChanged']) => void;
onboxPlotChanged?: (value: ojChartItemEventMap<any, any, any>['boxPlotChanged']) => void;
oncategoriesChanged?: (value: ojChartItemEventMap<any, any, any>['categoriesChanged']) => void;
oncloseChanged?: (value: ojChartItemEventMap<any, any, any>['closeChanged']) => void;
oncolorChanged?: (value: ojChartItemEventMap<any, any, any>['colorChanged']) => void;
ondrillingChanged?: (value: ojChartItemEventMap<any, any, any>['drillingChanged']) => void;
ongroupIdChanged?: (value: ojChartItemEventMap<any, any, any>['groupIdChanged']) => void;
onhighChanged?: (value: ojChartItemEventMap<any, any, any>['highChanged']) => void;
onitemsChanged?: (value: ojChartItemEventMap<any, any, any>['itemsChanged']) => void;
onlabelChanged?: (value: ojChartItemEventMap<any, any, any>['labelChanged']) => void;
onlabelPositionChanged?: (value: ojChartItemEventMap<any, any, any>['labelPositionChanged']) => void;
onlabelStyleChanged?: (value: ojChartItemEventMap<any, any, any>['labelStyleChanged']) => void;
onlowChanged?: (value: ojChartItemEventMap<any, any, any>['lowChanged']) => void;
onmarkerDisplayedChanged?: (value: ojChartItemEventMap<any, any, any>['markerDisplayedChanged']) => void;
onmarkerShapeChanged?: (value: ojChartItemEventMap<any, any, any>['markerShapeChanged']) => void;
onmarkerSizeChanged?: (value: ojChartItemEventMap<any, any, any>['markerSizeChanged']) => void;
onopenChanged?: (value: ojChartItemEventMap<any, any, any>['openChanged']) => void;
onpatternChanged?: (value: ojChartItemEventMap<any, any, any>['patternChanged']) => void;
onq1Changed?: (value: ojChartItemEventMap<any, any, any>['q1Changed']) => void;
onq2Changed?: (value: ojChartItemEventMap<any, any, any>['q2Changed']) => void;
onq3Changed?: (value: ojChartItemEventMap<any, any, any>['q3Changed']) => void;
onseriesIdChanged?: (value: ojChartItemEventMap<any, any, any>['seriesIdChanged']) => void;
onshortDescChanged?: (value: ojChartItemEventMap<any, any, any>['shortDescChanged']) => void;
onsourceChanged?: (value: ojChartItemEventMap<any, any, any>['sourceChanged']) => void;
onsourceHoverChanged?: (value: ojChartItemEventMap<any, any, any>['sourceHoverChanged']) => void;
onsourceHoverSelectedChanged?: (value: ojChartItemEventMap<any, any, any>['sourceHoverSelectedChanged']) => void;
onsourceSelectedChanged?: (value: ojChartItemEventMap<any, any, any>['sourceSelectedChanged']) => void;
onsvgClassNameChanged?: (value: ojChartItemEventMap<any, any, any>['svgClassNameChanged']) => void;
onsvgStyleChanged?: (value: ojChartItemEventMap<any, any, any>['svgStyleChanged']) => void;
ontargetValueChanged?: (value: ojChartItemEventMap<any, any, any>['targetValueChanged']) => void;
onvalueChanged?: (value: ojChartItemEventMap<any, any, any>['valueChanged']) => void;
onvolumeChanged?: (value: ojChartItemEventMap<any, any, any>['volumeChanged']) => void;
onxChanged?: (value: ojChartItemEventMap<any, any, any>['xChanged']) => void;
onyChanged?: (value: ojChartItemEventMap<any, any, any>['yChanged']) => void;
onzChanged?: (value: ojChartItemEventMap<any, any, any>['zChanged']) => void;
children?: ComponentChildren;
}
export interface ChartSeriesIntrinsicProps extends Partial<Readonly<ojChartSeriesSettableProperties>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> {
onareaColorChanged?: (value: ojChartSeriesEventMap['areaColorChanged']) => void;
onareaSvgClassNameChanged?: (value: ojChartSeriesEventMap['areaSvgClassNameChanged']) => void;
onareaSvgStyleChanged?: (value: ojChartSeriesEventMap['areaSvgStyleChanged']) => void;
onassignedToY2Changed?: (value: ojChartSeriesEventMap['assignedToY2Changed']) => void;
onborderColorChanged?: (value: ojChartSeriesEventMap['borderColorChanged']) => void;
onborderWidthChanged?: (value: ojChartSeriesEventMap['borderWidthChanged']) => void;
onboxPlotChanged?: (value: ojChartSeriesEventMap['boxPlotChanged']) => void;
oncategoriesChanged?: (value: ojChartSeriesEventMap['categoriesChanged']) => void;
oncolorChanged?: (value: ojChartSeriesEventMap['colorChanged']) => void;
ondisplayInLegendChanged?: (value: ojChartSeriesEventMap['displayInLegendChanged']) => void;
ondrillingChanged?: (value: ojChartSeriesEventMap['drillingChanged']) => void;
onlineStyleChanged?: (value: ojChartSeriesEventMap['lineStyleChanged']) => void;
onlineTypeChanged?: (value: ojChartSeriesEventMap['lineTypeChanged']) => void;
onlineWidthChanged?: (value: ojChartSeriesEventMap['lineWidthChanged']) => void;
onmarkerColorChanged?: (value: ojChartSeriesEventMap['markerColorChanged']) => void;
onmarkerDisplayedChanged?: (value: ojChartSeriesEventMap['markerDisplayedChanged']) => void;
onmarkerShapeChanged?: (value: ojChartSeriesEventMap['markerShapeChanged']) => void;
onmarkerSizeChanged?: (value: ojChartSeriesEventMap['markerSizeChanged']) => void;
onmarkerSvgClassNameChanged?: (value: ojChartSeriesEventMap['markerSvgClassNameChanged']) => void;
onmarkerSvgStyleChanged?: (value: ojChartSeriesEventMap['markerSvgStyleChanged']) => void;
onnameChanged?: (value: ojChartSeriesEventMap['nameChanged']) => void;
onpatternChanged?: (value: ojChartSeriesEventMap['patternChanged']) => void;
onpieSliceExplodeChanged?: (value: ojChartSeriesEventMap['pieSliceExplodeChanged']) => void;
onshortDescChanged?: (value: ojChartSeriesEventMap['shortDescChanged']) => void;
onsourceChanged?: (value: ojChartSeriesEventMap['sourceChanged']) => void;
onsourceHoverChanged?: (value: ojChartSeriesEventMap['sourceHoverChanged']) => void;
onsourceHoverSelectedChanged?: (value: ojChartSeriesEventMap['sourceHoverSelectedChanged']) => void;
onsourceSelectedChanged?: (value: ojChartSeriesEventMap['sourceSelectedChanged']) => void;
onstackCategoryChanged?: (value: ojChartSeriesEventMap['stackCategoryChanged']) => void;
onsvgClassNameChanged?: (value: ojChartSeriesEventMap['svgClassNameChanged']) => void;
onsvgStyleChanged?: (value: ojChartSeriesEventMap['svgStyleChanged']) => void;
ontypeChanged?: (value: ojChartSeriesEventMap['typeChanged']) => void;
children?: ComponentChildren;
}
export interface SparkChartIntrinsicProps extends Partial<Readonly<ojSparkChartSettableProperties<any, any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> {
onanimationDurationChanged?: (value: ojSparkChartEventMap<any, any>['animationDurationChanged']) => void;
onanimationOnDataChangeChanged?: (value: ojSparkChartEventMap<any, any>['animationOnDataChangeChanged']) => void;
onanimationOnDisplayChanged?: (value: ojSparkChartEventMap<any, any>['animationOnDisplayChanged']) => void;
onareaColorChanged?: (value: ojSparkChartEventMap<any, any>['areaColorChanged']) => void;
onareaSvgClassNameChanged?: (value: ojSparkChartEventMap<any, any>['areaSvgClassNameChanged']) => void;
onareaSvgStyleChanged?: (value: ojSparkChartEventMap<any, any>['areaSvgStyleChanged']) => void;
onasChanged?: (value: ojSparkChartEventMap<any, any>['asChanged']) => void;
onbarGapRatioChanged?: (value: ojSparkChartEventMap<any, any>['barGapRatioChanged']) => void;
onbaselineScalingChanged?: (value: ojSparkChartEventMap<any, any>['baselineScalingChanged']) => void;
oncolorChanged?: (value: ojSparkChartEventMap<any, any>['colorChanged']) => void;
ondataChanged?: (value: ojSparkChartEventMap<any, any>['dataChanged']) => void;
onfirstColorChanged?: (value: ojSparkChartEventMap<any, any>['firstColorChanged']) => void;
onhighColorChanged?: (value: ojSparkChartEventMap<any, any>['highColorChanged']) => void;
onlastColorChanged?: (value: ojSparkChartEventMap<any, any>['lastColorChanged']) => void;
onlineStyleChanged?: (value: ojSparkChartEventMap<any, any>['lineStyleChanged']) => void;
onlineTypeChanged?: (value: ojSparkChartEventMap<any, any>['lineTypeChanged']) => void;
onlineWidthChanged?: (value: ojSparkChartEventMap<any, any>['lineWidthChanged']) => void;
onlowColorChanged?: (value: ojSparkChartEventMap<any, any>['lowColorChanged']) => void;
onmarkerShapeChanged?: (value: ojSparkChartEventMap<any, any>['markerShapeChanged']) => void;
onmarkerSizeChanged?: (value: ojSparkChartEventMap<any, any>['markerSizeChanged']) => void;
onreferenceObjectsChanged?: (value: ojSparkChartEventMap<any, any>['referenceObjectsChanged']) => void;
onsvgClassNameChanged?: (value: ojSparkChartEventMap<any, any>['svgClassNameChanged']) => void;
onsvgStyleChanged?: (value: ojSparkChartEventMap<any, any>['svgStyleChanged']) => void;
ontooltipChanged?: (value: ojSparkChartEventMap<any, any>['tooltipChanged']) => void;
ontypeChanged?: (value: ojSparkChartEventMap<any, any>['typeChanged']) => void;
onvisualEffectsChanged?: (value: ojSparkChartEventMap<any, any>['visualEffectsChanged']) => void;
ontrackResizeChanged?: (value: ojSparkChartEventMap<any, any>['trackResizeChanged']) => void;
children?: ComponentChildren;
}
export interface SparkChartItemIntrinsicProps extends Partial<Readonly<ojSparkChartItemSettableProperties>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> {
onborderColorChanged?: (value: ojSparkChartItemEventMap['borderColorChanged']) => void;
oncolorChanged?: (value: ojSparkChartItemEventMap['colorChanged']) => void;
ondateChanged?: (value: ojSparkChartItemEventMap['dateChanged']) => void;
onhighChanged?: (value: ojSparkChartItemEventMap['highChanged']) => void;
onlowChanged?: (value: ojSparkChartItemEventMap['lowChanged']) => void;
onmarkerDisplayedChanged?: (value: ojSparkChartItemEventMap['markerDisplayedChanged']) => void;
onmarkerShapeChanged?: (value: ojSparkChartItemEventMap['markerShapeChanged']) => void;
onmarkerSizeChanged?: (value: ojSparkChartItemEventMap['markerSizeChanged']) => void;
onsvgClassNameChanged?: (value: ojSparkChartItemEventMap['svgClassNameChanged']) => void;
onsvgStyleChanged?: (value: ojSparkChartItemEventMap['svgStyleChanged']) => void;
onvalueChanged?: (value: ojSparkChartItemEventMap['valueChanged']) => void;
children?: ComponentChildren;
}
declare global {
namespace preact.JSX {
interface IntrinsicElements {
"oj-chart": ChartIntrinsicProps;
"oj-chart-group": ChartGroupIntrinsicProps;
"oj-chart-item": ChartItemIntrinsicProps;
"oj-chart-series": ChartSeriesIntrinsicProps;
"oj-spark-chart": SparkChartIntrinsicProps;
"oj-spark-chart-item": SparkChartItemIntrinsicProps;
}
}
} | the_stack |
import React, { createContext, useContext, useEffect, useRef } from 'react';
import { useState } from 'react';
import { useMouseEvents, useWillUnmount } from 'beautiful-react-hooks';
import { useField, useFieldSchema } from '@formily/react';
import { useMount } from 'ahooks';
import constate from 'constate';
import { useSchemaPath } from '../../schemas';
export const DraggableBlockContext = createContext({
dragRef: null,
});
export function useDragDropManager({ uid }) {
const [drag, setDrag] = useState(null);
const [drop, setDrop] = useState(null);
const [drops, setDrops] = useState({});
const addDrop = (dropId, data) =>
setDrops((prevDrops) => {
prevDrops[dropId] = data;
return prevDrops;
});
const getDrop = (dropId) => {
return drops[dropId];
};
return { uid, drag, drop, drops, setDrag, addDrop, setDrop, getDrop };
}
const [DragDropManagerProvider, useDragDropManagerContext] =
constate(useDragDropManager);
export function useDragDropUID() {
const { uid } = useDragDropManagerContext();
return uid;
}
export { DragDropManagerProvider, useDragDropManagerContext };
export function mergeRefs<T = any>(
refs: Array<React.MutableRefObject<T> | React.LegacyRef<T>>,
): React.RefCallback<T> {
return (value) => {
refs.forEach((ref) => {
if (typeof ref === 'function') {
ref(value);
} else if (ref != null) {
(ref as React.MutableRefObject<T | null>).current = value;
}
});
};
}
export function useDrag(options?: any) {
const { type, onDragStart, onDrag, onDragEnd, item = {} } = options;
const dragRef = useRef<HTMLDivElement>();
const previewRef = useRef<HTMLDivElement>();
const { onMouseDown } = useMouseEvents(dragRef);
const { onMouseMove, onMouseUp } = useMouseEvents();
const [previewElement, setPreviewElement] = useState<HTMLDivElement>();
const [isDragging, setIsDragging] = useState(false);
const [mousePostionWithinPreview, setMousePostionWithinPreview] = useState({
left: 0,
top: 0,
});
const { drag, setDrag, setDrop, getDrop } = useDragDropManagerContext();
useWillUnmount(() => {
setIsDragging(false);
// @ts-ignore
window.__previewElement && window.__previewElement.remove();
// @ts-ignore
window.__previewElement = undefined;
setDrag(null);
setDrop(null);
document.body.classList.remove('dragging');
document.body.style.cursor = null;
document.body.style.userSelect = null;
});
onMouseDown((event: React.MouseEvent) => {
if (event.button !== 0) {
return;
}
setDrop({ type, item });
setDrag({ type, item });
setIsDragging(true);
const postion = {
left: event.clientX - previewRef.current.getBoundingClientRect().left,
top: event.clientY - previewRef.current.getBoundingClientRect().top,
};
setMousePostionWithinPreview(postion);
const offset = {
left: event.pageX - postion.left,
top: event.pageY - postion.top,
};
const wrap = document.createElement('div');
wrap.className = 'drag-container';
wrap.style.position = 'absolute';
wrap.style.pointerEvents = 'none';
wrap.style.opacity = '0.7';
wrap.style.left = `0px`;
wrap.style.top = `0px`;
wrap.style.zIndex = '9999';
wrap.style.width = `${previewRef.current.clientWidth}px`;
wrap.style.transform = `translate(${offset.left}px, ${offset.top}px)`;
setPreviewElement(wrap);
// @ts-ignore
window.__previewElement = wrap;
// console.log(
// 'dragDropManager.previewElement',
// dragDropManager.previewElement,
// );
document.body.appendChild(wrap);
const el = document.createElement('div');
wrap.appendChild(el);
el.outerHTML = previewRef.current.outerHTML;
onDragStart && onDragStart(event);
document.body.style.cursor = 'grab';
document.body.style.userSelect = 'none';
document.body.classList.add('dragging');
// console.log(
// 'onMouseDown',
// { isDragging, previewElement },
// dragDropManager.previewElement,
// field ? field.address.segments : null,
// );
// console.log('onMouseDown', event);
});
onMouseUp((event: React.MouseEvent) => {
if (!isDragging || !previewElement) {
return;
}
// console.log(
// 'onMouseUp',
// { isDragging, previewElement },
// field ? field.address.segments : null,
// );
// @ts-ignore
event.dragItem = item;
setIsDragging(false);
setDrag(null);
// dragDropManager.drag = null;
previewElement.remove();
setPreviewElement(undefined);
document.body.classList.remove('dragging');
document.body.style.cursor = null;
document.body.style.userSelect = null;
// @ts-ignore
window.__previewElement && window.__previewElement.remove();
// @ts-ignore
window.__previewElement = undefined;
if (!type) {
onDragEnd && onDragEnd(event);
}
let dropElement = document.elementFromPoint(event.clientX, event.clientY);
const dropIds = [];
while (dropElement) {
if (!dropElement.getAttribute) {
dropElement = dropElement.parentNode as HTMLElement;
continue;
}
const dropId = dropElement.getAttribute('data-drop-id');
const dropContext = getDrop(dropId);
if (dropContext && dropContext.accept === type) {
if (
!dropContext.shallow ||
(dropContext.shallow && dropIds.length === 0)
) {
// @ts-ignore
event.data = dropContext.data;
onDragEnd && onDragEnd(event);
dropIds.push(dropId);
}
}
dropElement = dropElement.parentNode as HTMLElement;
}
});
onMouseMove((event: React.MouseEvent) => {
if (!isDragging || !previewElement) {
return;
}
console.log('drag', drag.dropIds);
// console.log(
// 'onMouseMove',
// { isDragging, previewElement },
// dragDropManager.previewElement,
// field ? field.address.segments : null,
// );
// console.log({previewElement})
const offset = {
left: event.pageX - mousePostionWithinPreview.left,
top: event.pageY - mousePostionWithinPreview.top,
};
previewElement.style.transform = `translate(${offset.left}px, ${offset.top}px)`;
if (type) {
let dropElement = document.elementFromPoint(event.clientX, event.clientY);
const dropIds = [];
while (dropElement) {
if (!dropElement.getAttribute) {
dropElement = dropElement.parentNode as HTMLElement;
continue;
}
const dropId = dropElement.getAttribute('data-drop-id');
const dropContext = getDrop(dropId);
if (dropContext && dropContext.accept === type) {
if (
!dropContext.shallow ||
(dropContext.shallow && dropIds.length === 0)
) {
dropIds.push(dropId);
}
// @ts-ignore
// event.data = dropContext.data;
}
dropElement = dropElement.parentNode as HTMLElement;
}
setDrag({ type, dropIds });
}
onDrag && onDrag(event);
});
return { isDragging, dragRef, previewRef };
}
export function useDrop(options) {
const {
uid: dropId,
accept,
data,
shallow,
onDrop,
onHover,
canDrop = true,
} = options;
const dropRef = useRef<HTMLDivElement>();
const { onMouseEnter, onMouseLeave, onMouseMove, onMouseUp } =
useMouseEvents(dropRef);
const [isOver, setIsOver] = useState(false);
const [onTopHalf, setOnTopHalf] = useState(null);
// const dragDropManager = useContext(DragDropManagerContext);
const { drag, drop, addDrop, setDrop } = useDragDropManagerContext();
useEffect(() => {
addDrop(dropId, {
accept,
data,
shallow,
});
// console.log('dragDropManager.drops', dragDropManager.drops);
// dragDropManager.drops[dropId] = {
// accept,
// data,
// shallow,
// };
dropRef.current.setAttribute('data-drop-id', dropId);
}, [dropId]);
onMouseEnter((event) => {
if (!canDrop) {
return;
}
// console.log({ dragDropManager });
if (!drag || drag.type !== accept) {
return;
}
setIsOver(true);
});
onMouseMove((event: React.MouseEvent) => {
if (!canDrop) {
return;
}
if (!drag || drag.type !== accept) {
return;
}
console.log('drag.dropIds', drag.dropIds, dropId);
if (drag.dropIds && drag.dropIds.includes(dropId)) {
const top = event.clientY - dropRef.current.getBoundingClientRect().top;
const onTop = top < dropRef.current.clientHeight / 2;
setOnTopHalf(onTop);
// @ts-ignore
event.onTopHalf = onTop;
setIsOver(true);
onHover && onHover(event);
} else {
setIsOver(false);
}
});
onMouseUp((event: React.MouseEvent) => {
if (!canDrop) {
return;
}
if (event.button !== 0) {
return;
}
if (isOver) {
const top = event.clientY - dropRef.current.getBoundingClientRect().top;
const onTop = top < dropRef.current.clientHeight / 2;
setOnTopHalf(onTop);
// @ts-ignore
event.onTopHalf = onTop;
// @ts-ignore
event.data = data;
// @ts-ignore
event.dragItem = drop.item;
// @ts-ignore
event.dropElement = dropRef.current;
onDrop && onDrop(event);
// dragDropManager.onDrop && dragDropManager.onDrop(event);
setDrop(null);
}
setIsOver(false);
});
onMouseLeave(() => {
if (!canDrop) {
return;
}
setIsOver(false);
});
return {
onTopHalf: isOver ? onTopHalf : null,
isOver,
dropRef,
};
}
export function useColResizer(options?: any) {
const { onDragStart, onDrag, onDragEnd } = options || {};
const dragRef = useRef<HTMLDivElement>();
const [dragOffset, setDragOffset] = useState({ left: 0, top: 0 });
const { onMouseDown } = useMouseEvents(dragRef);
const { onMouseMove, onMouseUp } = useMouseEvents();
const [isDragging, setIsDragging] = useState(false);
const [columns, setColumns] = useState(options.columns || []);
const [initial, setInitial] = useState<any>(null);
onMouseDown((event: React.MouseEvent) => {
if (event.button !== 0) {
return;
}
const prev = dragRef.current.previousElementSibling as HTMLDivElement;
const next = dragRef.current.nextElementSibling as HTMLDivElement;
if (!prev || !next) {
return;
}
setIsDragging(true);
if (!initial) {
setInitial({
offset: event.clientX,
prevWidth: prev.style.width,
nextWidth: next.style.width,
});
}
});
onMouseUp((event: React.MouseEvent) => {
if (!isDragging) {
return;
}
const parent = dragRef.current.parentElement;
const els = parent.querySelectorAll(':scope > .nb-grid-col');
const size = [];
const gap = dragRef.current.clientWidth;
console.log(
'parent.clientWidth',
parent.clientWidth,
dragRef.current.clientWidth,
);
els.forEach((el: HTMLDivElement) => {
const w = (100 * el.clientWidth) / parent.clientWidth;
const w2 =
(100 * (el.clientWidth + gap + gap / els.length)) / parent.clientWidth;
size.push(w2);
el.style.width = `${w}%`;
});
console.log({ size });
setIsDragging(false);
setInitial(null);
// @ts-ignore
event.data = { size };
onDragEnd && onDragEnd(event);
});
onMouseMove((event: React.MouseEvent) => {
if (!isDragging) {
return;
}
const offset = event.clientX - initial.offset;
// dragRef.current.style.transform = `translateX(${event.clientX - initialOffset}px)`;
const prev = dragRef.current.previousElementSibling as HTMLDivElement;
const next = dragRef.current.nextElementSibling as HTMLDivElement;
prev.style.width = `calc(${initial.prevWidth} + ${offset}px)`;
next.style.width = `calc(${initial.nextWidth} - ${offset}px)`;
// console.log('dragRef.current.nextSibling', prev.style.width);
});
return { isDragging, dragOffset, dragRef, columns };
}
export function useBlockDragAndDrop() {
const schema = useFieldSchema();
const uid = useDragDropUID();
const path = useSchemaPath();
const { isDragging, dragRef, previewRef } = useDrag({
type: uid,
onDragStart() {
console.log('onDragStart');
},
onDragEnd(event) {
console.log('onDragEnd', event.data);
},
onDrag(event) {
// console.log('onDrag');
},
item: {
path,
schema: schema.toJSON(),
},
});
const { isOver, onTopHalf, dropRef } = useDrop({
uid: schema.name,
accept: uid,
data: {},
canDrop: !isDragging,
});
return {
isDragging,
dragRef,
previewRef,
isOver,
onTopHalf,
dropRef,
};
} | the_stack |
import generate from './component-generator';
it('generates', () => {
// #region EXPECTED
const EXPECTED = `
import dxCLASS_NAME, {
Properties
} from "DX/WIDGET/PATH";
import { Component as BaseComponent, IHtmlOptions } from "BASE_COMPONENT_PATH";
interface ICLASS_NAMEOptions extends Properties, IHtmlOptions {
}
class CLASS_NAME extends BaseComponent<ICLASS_NAMEOptions> {
public get instance(): dxCLASS_NAME {
return this._instance;
}
protected _WidgetClass = dxCLASS_NAME;
}
export default CLASS_NAME;
export {
CLASS_NAME,
ICLASS_NAMEOptions
};
`.trimLeft();
// #endregion
expect(
generate({
name: 'CLASS_NAME',
baseComponentPath: 'BASE_COMPONENT_PATH',
extensionComponentPath: 'EXTENSION_COMPONENT_PATH',
dxExportPath: 'DX/WIDGET/PATH',
}),
).toBe(EXPECTED);
});
it('generates extension component', () => {
// #region EXPECTED
const EXPECTED = `
import dxCLASS_NAME, {
Properties as ICLASS_NAMEOptions
} from "DX/WIDGET/PATH";
import { ExtensionComponent as BaseComponent } from "EXTENSION_COMPONENT_PATH";
class CLASS_NAME extends BaseComponent<ICLASS_NAMEOptions> {
public get instance(): dxCLASS_NAME {
return this._instance;
}
protected _WidgetClass = dxCLASS_NAME;
}
export default CLASS_NAME;
export {
CLASS_NAME,
ICLASS_NAMEOptions
};
`.trimLeft();
// #endregion
expect(
generate({
name: 'CLASS_NAME',
baseComponentPath: 'BASE_COMPONENT_PATH',
extensionComponentPath: 'EXTENSION_COMPONENT_PATH',
dxExportPath: 'DX/WIDGET/PATH',
isExtension: true,
}),
).toBe(EXPECTED);
});
describe('generic types clause', () => {
it('is generated', () => {
// #region EXPECTED
const EXPECTED = `
export { ExplicitTypes } from "DX/WIDGET/PATH";
import dxCLASS_NAME, {
Properties
} from "DX/WIDGET/PATH";
import { Component as BaseComponent, IHtmlOptions } from "BASE_COMPONENT_PATH";
interface ICLASS_NAMEOptions<T1 = any, T2 = any> extends Properties<T1, T2>, IHtmlOptions {
dataSource?: Properties<T1, T2>["dataSource"];
}
class CLASS_NAME<T1, T2> extends BaseComponent<ICLASS_NAMEOptions<T1, T2>> {
public get instance(): dxCLASS_NAME {
return this._instance;
}
protected _WidgetClass = dxCLASS_NAME;
}
export default CLASS_NAME;
export {
CLASS_NAME,
ICLASS_NAMEOptions
};
`.trimLeft();
// #endregion
expect(
generate({
name: 'CLASS_NAME',
baseComponentPath: 'BASE_COMPONENT_PATH',
extensionComponentPath: 'EXTENSION_COMPONENT_PATH',
dxExportPath: 'DX/WIDGET/PATH',
optionsTypeParams: ['T1', 'T2'],
}),
).toBe(EXPECTED);
});
it('is not generated if params array is empty', () => {
const component = {
name: 'CLASS_NAME',
baseComponentPath: 'BASE_COMPONENT_PATH',
extensionComponentPath: 'EXTENSION_COMPONENT_PATH',
dxExportPath: 'DX/WIDGET/PATH',
};
const EXPECTED = generate(component);
expect(
generate({
...component,
optionsTypeParams: [],
}),
).toBe(EXPECTED);
});
});
describe('template-props generation', () => {
it('processes option', () => {
// #region EXPECTED
const EXPECTED = `
import dxCLASS_NAME, {
Properties
} from "DX/WIDGET/PATH";
import { Component as BaseComponent, IHtmlOptions } from "BASE_COMPONENT_PATH";
interface ICLASS_NAMEOptions extends Properties, IHtmlOptions {
optionRender?: (...params: any) => React.ReactNode;
optionComponent?: React.ComponentType<any>;
optionKeyFn?: (data: any) => string;
}
class CLASS_NAME extends BaseComponent<ICLASS_NAMEOptions> {
public get instance(): dxCLASS_NAME {
return this._instance;
}
protected _WidgetClass = dxCLASS_NAME;
protected _templateProps = [{
tmplOption: "optionTemplate",
render: "optionRender",
component: "optionComponent",
keyFn: "optionKeyFn"
}];
}
export default CLASS_NAME;
export {
CLASS_NAME,
ICLASS_NAMEOptions
};
`.trimLeft();
// #endregion
expect(
generate({
name: 'CLASS_NAME',
baseComponentPath: 'BASE_COMPONENT_PATH',
extensionComponentPath: 'EXTENSION_COMPONENT_PATH',
dxExportPath: 'DX/WIDGET/PATH',
templates: ['optionTemplate'],
}),
).toBe(EXPECTED);
});
it('processes several options', () => {
// #region EXPECTED
const EXPECTED = `
import dxCLASS_NAME, {
Properties
} from "DX/WIDGET/PATH";
import { Component as BaseComponent, IHtmlOptions } from "BASE_COMPONENT_PATH";
interface ICLASS_NAMEOptions extends Properties, IHtmlOptions {
optionRender?: (...params: any) => React.ReactNode;
optionComponent?: React.ComponentType<any>;
optionKeyFn?: (data: any) => string;
anotherOptionRender?: (...params: any) => React.ReactNode;
anotherOptionComponent?: React.ComponentType<any>;
anotherOptionKeyFn?: (data: any) => string;
}
class CLASS_NAME extends BaseComponent<ICLASS_NAMEOptions> {
public get instance(): dxCLASS_NAME {
return this._instance;
}
protected _WidgetClass = dxCLASS_NAME;
protected _templateProps = [{
tmplOption: "optionTemplate",
render: "optionRender",
component: "optionComponent",
keyFn: "optionKeyFn"
}, {
tmplOption: "anotherOptionTemplate",
render: "anotherOptionRender",
component: "anotherOptionComponent",
keyFn: "anotherOptionKeyFn"
}];
}
export default CLASS_NAME;
export {
CLASS_NAME,
ICLASS_NAMEOptions
};
`.trimLeft();
// #endregion
expect(
generate({
name: 'CLASS_NAME',
baseComponentPath: 'BASE_COMPONENT_PATH',
extensionComponentPath: 'EXTENSION_COMPONENT_PATH',
dxExportPath: 'DX/WIDGET/PATH',
templates: ['optionTemplate', 'anotherOptionTemplate'],
}),
).toBe(EXPECTED);
});
it('processes single widget-template option', () => {
// #region EXPECTED
const EXPECTED = `
import dxCLASS_NAME, {
Properties
} from "DX/WIDGET/PATH";
import { Component as BaseComponent, IHtmlOptions } from "BASE_COMPONENT_PATH";
interface ICLASS_NAMEOptions extends Properties, IHtmlOptions {
render?: (...params: any) => React.ReactNode;
component?: React.ComponentType<any>;
keyFn?: (data: any) => string;
}
class CLASS_NAME extends BaseComponent<ICLASS_NAMEOptions> {
public get instance(): dxCLASS_NAME {
return this._instance;
}
protected _WidgetClass = dxCLASS_NAME;
protected _templateProps = [{
tmplOption: "template",
render: "render",
component: "component",
keyFn: "keyFn"
}];
}
export default CLASS_NAME;
export {
CLASS_NAME,
ICLASS_NAMEOptions
};
`.trimLeft();
// #endregion
expect(
generate({
name: 'CLASS_NAME',
baseComponentPath: 'BASE_COMPONENT_PATH',
extensionComponentPath: 'EXTENSION_COMPONENT_PATH',
dxExportPath: 'DX/WIDGET/PATH',
templates: ['template'],
}),
).toBe(EXPECTED);
});
});
describe('props generation', () => {
it('processes subscribable option', () => {
// #region EXPECTED
const EXPECTED = `
import dxCLASS_NAME, {
Properties
} from "DX/WIDGET/PATH";
import { Component as BaseComponent, IHtmlOptions } from "BASE_COMPONENT_PATH";
interface ICLASS_NAMEOptions extends Properties, IHtmlOptions {
defaultOption1?: someType;
onOption1Change?: (value: someType) => void;
}
class CLASS_NAME extends BaseComponent<ICLASS_NAMEOptions> {
public get instance(): dxCLASS_NAME {
return this._instance;
}
protected _WidgetClass = dxCLASS_NAME;
protected subscribableOptions = ["option1"];
protected _defaults = {
defaultOption1: "option1"
};
}
export default CLASS_NAME;
export {
CLASS_NAME,
ICLASS_NAMEOptions
};
`.trimLeft();
// #endregion
expect(
generate({
name: 'CLASS_NAME',
baseComponentPath: 'BASE_COMPONENT_PATH',
extensionComponentPath: 'EXTENSION_COMPONENT_PATH',
dxExportPath: 'DX/WIDGET/PATH',
subscribableOptions: [
{ name: 'option1', type: 'someType' },
],
}),
).toBe(EXPECTED);
});
it('processes several subscribable options', () => {
// #region EXPECTED
const EXPECTED = `
import dxCLASS_NAME, {
Properties
} from "DX/WIDGET/PATH";
import { Component as BaseComponent, IHtmlOptions } from "BASE_COMPONENT_PATH";
interface ICLASS_NAMEOptions extends Properties, IHtmlOptions {
defaultOption1?: someType;
defaultOption2?: anotherType;
onOption1Change?: (value: someType) => void;
onOption2Change?: (value: anotherType) => void;
}
class CLASS_NAME extends BaseComponent<ICLASS_NAMEOptions> {
public get instance(): dxCLASS_NAME {
return this._instance;
}
protected _WidgetClass = dxCLASS_NAME;
protected subscribableOptions = ["option1","option2"];
protected _defaults = {
defaultOption1: "option1",
defaultOption2: "option2"
};
}
export default CLASS_NAME;
export {
CLASS_NAME,
ICLASS_NAMEOptions
};
`.trimLeft();
// #endregion
expect(
generate({
name: 'CLASS_NAME',
baseComponentPath: 'BASE_COMPONENT_PATH',
extensionComponentPath: 'EXTENSION_COMPONENT_PATH',
dxExportPath: 'DX/WIDGET/PATH',
subscribableOptions: [
{ name: 'option1', type: 'someType' },
{ name: 'option2', type: 'anotherType' },
],
}),
).toBe(EXPECTED);
});
it('processes nested subscribable option', () => {
// #region EXPECTED
const EXPECTED = `
import dxCLASS_NAME, {
Properties
} from "DX/WIDGET/PATH";
import { Component as BaseComponent, IHtmlOptions } from "BASE_COMPONENT_PATH";
interface ICLASS_NAMEOptions extends Properties, IHtmlOptions {
defaultOption1?: someType;
onOption1Change?: (value: someType) => void;
}
class CLASS_NAME extends BaseComponent<ICLASS_NAMEOptions> {
public get instance(): dxCLASS_NAME {
return this._instance;
}
protected _WidgetClass = dxCLASS_NAME;
protected subscribableOptions = ["option1","option1.subOption1","option2.subOption1"];
protected _defaults = {
defaultOption1: "option1"
};
}
export default CLASS_NAME;
export {
CLASS_NAME,
ICLASS_NAMEOptions
};
`.trimLeft();
// #endregion
expect(
generate({
name: 'CLASS_NAME',
baseComponentPath: 'BASE_COMPONENT_PATH',
extensionComponentPath: 'EXTENSION_COMPONENT_PATH',
dxExportPath: 'DX/WIDGET/PATH',
subscribableOptions: [
{ name: 'option1', type: 'someType' },
{ name: 'option1.subOption1', type: 'someType' },
{ name: 'option2.subOption1', type: 'someType' },
],
}),
).toBe(EXPECTED);
});
});
describe('nested options', () => {
it('processes nested options', () => {
// #region EXPECTED
const EXPECTED = `
import dxCLASS_NAME, {
Properties
} from "DX/WIDGET/PATH";
import { Component as BaseComponent, IHtmlOptions } from "BASE_COMPONENT_PATH";
import NestedOption from "CONFIG_COMPONENT_PATH";
interface ICLASS_NAMEOptions extends Properties, IHtmlOptions {
}
class CLASS_NAME extends BaseComponent<ICLASS_NAMEOptions> {
public get instance(): dxCLASS_NAME {
return this._instance;
}
protected _WidgetClass = dxCLASS_NAME;
}
// owners:
// CLASS_NAME
interface IOpt_1_ComponentProps {
sub_opt_2?: TYPE_1;
sub_opt_3?: TYPE_SUB_3 | {
sub_sub_opt_4?: TYPE_2;
sub_sub_opt_5?: TYPE_SUB_OPT_5 | TYPE_SUB_OPT_6 | {
sub_sub_sub_opt_6?: TYPE_3;
};
};
}
class Opt_1_Component extends NestedOption<IOpt_1_ComponentProps> {
public static OptionName = "opt_1";
}
// owners:
// Opt_1_Component
interface IOpt_6_SubComponentProps {
sub_sub_sub_opt_8?: TYPE_4;
}
class Opt_6_SubComponent extends NestedOption<IOpt_6_SubComponentProps> {
public static OptionName = "sub_sub_opt_7";
}
export default CLASS_NAME;
export {
CLASS_NAME,
ICLASS_NAMEOptions,
Opt_1_Component,
IOpt_1_ComponentProps,
Opt_6_SubComponent,
IOpt_6_SubComponentProps
};
`.trimLeft();
// #endregion
expect(
generate({
name: 'CLASS_NAME',
baseComponentPath: 'BASE_COMPONENT_PATH',
extensionComponentPath: 'EXTENSION_COMPONENT_PATH',
configComponentPath: 'CONFIG_COMPONENT_PATH',
dxExportPath: 'DX/WIDGET/PATH',
nestedComponents: [
{
className: 'Opt_1_Component',
owners: ['CLASS_NAME'],
optionName: 'opt_1',
options: [
{
name: 'sub_opt_2',
type: 'TYPE_1',
},
{
name: 'sub_opt_3',
type: 'TYPE_SUB_3',
nested: [
{
name: 'sub_sub_opt_4',
type: 'TYPE_2',
},
{
name: 'sub_sub_opt_5',
type: 'TYPE_SUB_OPT_5 | TYPE_SUB_OPT_6',
nested: [
{
name: 'sub_sub_sub_opt_6',
type: 'TYPE_3',
},
],
},
],
},
],
},
{
className: 'Opt_6_SubComponent',
owners: ['Opt_1_Component'],
optionName: 'sub_sub_opt_7',
options: [
{
name: 'sub_sub_sub_opt_8',
type: 'TYPE_4',
},
],
},
],
}),
).toBe(EXPECTED);
});
it('processes nested array option', () => {
// #region EXPECTED
const EXPECTED = `
import dxCLASS_NAME, {
Properties
} from "DX/WIDGET/PATH";
import { Component as BaseComponent, IHtmlOptions } from "BASE_COMPONENT_PATH";
import NestedOption from "CONFIG_COMPONENT_PATH";
interface ICLASS_NAMEOptions extends Properties, IHtmlOptions {
}
class CLASS_NAME extends BaseComponent<ICLASS_NAMEOptions> {
public get instance(): dxCLASS_NAME {
return this._instance;
}
protected _WidgetClass = dxCLASS_NAME;
}
// owners:
// CLASS_NAME
interface IOpt_1_ComponentProps {
sub_opt_2?: TYPE_1;
}
class Opt_1_Component extends NestedOption<IOpt_1_ComponentProps> {
public static OptionName = "opt_1";
public static IsCollectionItem = true;
}
export default CLASS_NAME;
export {
CLASS_NAME,
ICLASS_NAMEOptions,
Opt_1_Component,
IOpt_1_ComponentProps
};
`.trimLeft();
// #endregion
expect(
generate({
name: 'CLASS_NAME',
baseComponentPath: 'BASE_COMPONENT_PATH',
extensionComponentPath: 'EXTENSION_COMPONENT_PATH',
configComponentPath: 'CONFIG_COMPONENT_PATH',
dxExportPath: 'DX/WIDGET/PATH',
nestedComponents: [
{
className: 'Opt_1_Component',
owners: ['CLASS_NAME'],
optionName: 'opt_1',
isCollectionItem: true,
options: [
{
name: 'sub_opt_2',
type: 'TYPE_1',
},
],
},
],
}),
).toBe(EXPECTED);
});
it('generates default props for nested options', () => {
// #region EXPECTED
const EXPECTED = `
import dxCLASS_NAME, {
Properties
} from "DX/WIDGET/PATH";
import { Component as BaseComponent, IHtmlOptions } from "BASE_COMPONENT_PATH";
import NestedOption from "CONFIG_COMPONENT_PATH";
interface ICLASS_NAMEOptions extends Properties, IHtmlOptions {
}
class CLASS_NAME extends BaseComponent<ICLASS_NAMEOptions> {
public get instance(): dxCLASS_NAME {
return this._instance;
}
protected _WidgetClass = dxCLASS_NAME;
}
// owners:
// CLASS_NAME
interface IOpt_1_ComponentProps {
sub_opt_2?: TYPE_1;
sub_opt_3?: {
sub_sub_opt_4?: TYPE_2;
};
defaultSub_opt_2?: TYPE_1;
onSub_opt_2Change?: (value: TYPE_1) => void;
}
class Opt_1_Component extends NestedOption<IOpt_1_ComponentProps> {
public static OptionName = "opt_1";
public static DefaultsProps = {
defaultSub_opt_2: "sub_opt_2"
};
}
export default CLASS_NAME;
export {
CLASS_NAME,
ICLASS_NAMEOptions,
Opt_1_Component,
IOpt_1_ComponentProps
};
`.trimLeft();
// #endregion
expect(
generate({
name: 'CLASS_NAME',
baseComponentPath: 'BASE_COMPONENT_PATH',
extensionComponentPath: 'EXTENSION_COMPONENT_PATH',
configComponentPath: 'CONFIG_COMPONENT_PATH',
dxExportPath: 'DX/WIDGET/PATH',
nestedComponents: [
{
className: 'Opt_1_Component',
owners: ['CLASS_NAME'],
optionName: 'opt_1',
options: [
{
name: 'sub_opt_2',
type: 'TYPE_1',
isSubscribable: true,
},
{
name: 'sub_opt_3',
nested: [
{
name: 'sub_sub_opt_4',
type: 'TYPE_2',
isSubscribable: true, // should not be rendered
},
],
},
],
},
],
}),
).toBe(EXPECTED);
});
it('generates component/render props for nested options', () => {
// #region EXPECTED
const EXPECTED = `
import dxCLASS_NAME, {
Properties
} from "DX/WIDGET/PATH";
import { Component as BaseComponent, IHtmlOptions } from "BASE_COMPONENT_PATH";
import NestedOption from "CONFIG_COMPONENT_PATH";
interface ICLASS_NAMEOptions extends Properties, IHtmlOptions {
}
class CLASS_NAME extends BaseComponent<ICLASS_NAMEOptions> {
public get instance(): dxCLASS_NAME {
return this._instance;
}
protected _WidgetClass = dxCLASS_NAME;
}
// owners:
// CLASS_NAME
interface IOpt_1_ComponentProps {
optionTemplate?: TYPE_1;
optionRender?: (...params: any) => React.ReactNode;
optionComponent?: React.ComponentType<any>;
optionKeyFn?: (data: any) => string;
}
class Opt_1_Component extends NestedOption<IOpt_1_ComponentProps> {
public static OptionName = "opt_1";
public static TemplateProps = [{
tmplOption: "optionTemplate",
render: "optionRender",
component: "optionComponent",
keyFn: "optionKeyFn"
}];
}
export default CLASS_NAME;
export {
CLASS_NAME,
ICLASS_NAMEOptions,
Opt_1_Component,
IOpt_1_ComponentProps
};
`.trimLeft();
// #endregion
expect(
generate({
name: 'CLASS_NAME',
baseComponentPath: 'BASE_COMPONENT_PATH',
extensionComponentPath: 'EXTENSION_COMPONENT_PATH',
configComponentPath: 'CONFIG_COMPONENT_PATH',
dxExportPath: 'DX/WIDGET/PATH',
nestedComponents: [
{
className: 'Opt_1_Component',
owners: ['CLASS_NAME'],
optionName: 'opt_1',
templates: ['optionTemplate'],
options: [
{
name: 'optionTemplate',
type: 'TYPE_1',
},
],
},
],
}),
).toBe(EXPECTED);
});
it('processes nested option predefined props', () => {
// #region EXPECTED
const EXPECTED = `
import dxCLASS_NAME, {
Properties
} from "DX/WIDGET/PATH";
import { Component as BaseComponent, IHtmlOptions } from "BASE_COMPONENT_PATH";
import NestedOption from "CONFIG_COMPONENT_PATH";
interface ICLASS_NAMEOptions extends Properties, IHtmlOptions {
}
class CLASS_NAME extends BaseComponent<ICLASS_NAMEOptions> {
public get instance(): dxCLASS_NAME {
return this._instance;
}
protected _WidgetClass = dxCLASS_NAME;
}
// owners:
// CLASS_NAME
interface IOpt_1_ComponentProps {
sub_opt_2?: TYPE_1;
}
class Opt_1_Component extends NestedOption<IOpt_1_ComponentProps> {
public static OptionName = "opt_1";
public static IsCollectionItem = true;
public static PredefinedProps = {
predefinedProp_1: "predefined-value"
};
}
export default CLASS_NAME;
export {
CLASS_NAME,
ICLASS_NAMEOptions,
Opt_1_Component,
IOpt_1_ComponentProps
};
`.trimLeft();
// #endregion
expect(
generate({
name: 'CLASS_NAME',
baseComponentPath: 'BASE_COMPONENT_PATH',
extensionComponentPath: 'EXTENSION_COMPONENT_PATH',
configComponentPath: 'CONFIG_COMPONENT_PATH',
dxExportPath: 'DX/WIDGET/PATH',
nestedComponents: [
{
className: 'Opt_1_Component',
owners: ['CLASS_NAME'],
optionName: 'opt_1',
isCollectionItem: true,
predefinedProps: {
predefinedProp_1: 'predefined-value',
},
options: [
{
name: 'sub_opt_2',
type: 'TYPE_1',
},
],
},
],
}),
).toBe(EXPECTED);
});
it('renders [] if nested suboption has array type', () => {
// #region EXPECTED
const EXPECTED = `
import dxCLASS_NAME, {
Properties
} from "DX/WIDGET/PATH";
import { Component as BaseComponent, IHtmlOptions } from "BASE_COMPONENT_PATH";
import NestedOption from "CONFIG_COMPONENT_PATH";
interface ICLASS_NAMEOptions extends Properties, IHtmlOptions {
}
class CLASS_NAME extends BaseComponent<ICLASS_NAMEOptions> {
public get instance(): dxCLASS_NAME {
return this._instance;
}
protected _WidgetClass = dxCLASS_NAME;
}
// owners:
// CLASS_NAME
interface IOpt_1_ComponentProps {
sub_opt_2?: TYPE_1;
sub_opt_3?: {
subsub_1?: TYPE_3;
subsub_2?: TYPE_4;
}[];
}
class Opt_1_Component extends NestedOption<IOpt_1_ComponentProps> {
public static OptionName = "opt_1";
public static IsCollectionItem = true;
public static PredefinedProps = {
predefinedProp_1: "predefined-value"
};
}
export default CLASS_NAME;
export {
CLASS_NAME,
ICLASS_NAMEOptions,
Opt_1_Component,
IOpt_1_ComponentProps
};
`.trimLeft();
// #endregion
expect(
generate({
name: 'CLASS_NAME',
baseComponentPath: 'BASE_COMPONENT_PATH',
extensionComponentPath: 'EXTENSION_COMPONENT_PATH',
configComponentPath: 'CONFIG_COMPONENT_PATH',
dxExportPath: 'DX/WIDGET/PATH',
nestedComponents: [
{
className: 'Opt_1_Component',
owners: ['CLASS_NAME'],
optionName: 'opt_1',
isCollectionItem: true,
predefinedProps: {
predefinedProp_1: 'predefined-value',
},
options: [
{
name: 'sub_opt_2',
type: 'TYPE_1',
},
{
name: 'sub_opt_3',
nested: [{
name: 'subsub_1',
type: 'TYPE_3',
},
{
name: 'subsub_2',
type: 'TYPE_4',
},
],
isArray: true,
},
],
},
],
}),
).toBe(EXPECTED);
});
});
describe('prop typings', () => {
it('adds check for single type', () => {
// #region EXPECTED
const EXPECTED = `
import dxCLASS_NAME, {
Properties
} from "DX/WIDGET/PATH";
import * as PropTypes from "prop-types";
import { Component as BaseComponent, IHtmlOptions } from "BASE_COMPONENT_PATH";
interface ICLASS_NAMEOptions extends Properties, IHtmlOptions {
}
class CLASS_NAME extends BaseComponent<ICLASS_NAMEOptions> {
public get instance(): dxCLASS_NAME {
return this._instance;
}
protected _WidgetClass = dxCLASS_NAME;
}
(CLASS_NAME as any).propTypes = {
PROP1: PropTypes.SOME_TYPE
};
export default CLASS_NAME;
export {
CLASS_NAME,
ICLASS_NAMEOptions
};
`.trimLeft();
// #endregion
expect(
generate({
name: 'CLASS_NAME',
baseComponentPath: 'BASE_COMPONENT_PATH',
extensionComponentPath: 'EXTENSION_COMPONENT_PATH',
dxExportPath: 'DX/WIDGET/PATH',
propTypings: [
{
propName: 'PROP1',
types: ['SOME_TYPE'],
},
],
}),
).toBe(EXPECTED);
});
it('adds check for acceptable values', () => {
// #region EXPECTED
const EXPECTED = `
import dxCLASS_NAME, {
Properties
} from "DX/WIDGET/PATH";
import * as PropTypes from "prop-types";
import { Component as BaseComponent, IHtmlOptions } from "BASE_COMPONENT_PATH";
interface ICLASS_NAMEOptions extends Properties, IHtmlOptions {
}
class CLASS_NAME extends BaseComponent<ICLASS_NAMEOptions> {
public get instance(): dxCLASS_NAME {
return this._instance;
}
protected _WidgetClass = dxCLASS_NAME;
}
(CLASS_NAME as any).propTypes = {
PROP1: PropTypes.oneOf([
"VALUE_1",
"VALUE_2"
])
};
export default CLASS_NAME;
export {
CLASS_NAME,
ICLASS_NAMEOptions
};
`.trimLeft();
// #endregion
expect(
generate({
name: 'CLASS_NAME',
baseComponentPath: 'BASE_COMPONENT_PATH',
extensionComponentPath: 'EXTENSION_COMPONENT_PATH',
dxExportPath: 'DX/WIDGET/PATH',
propTypings: [
{
propName: 'PROP1',
types: [],
acceptableValues: ['"VALUE_1"', '"VALUE_2"'],
},
],
}),
).toBe(EXPECTED);
});
it('adds check for several types', () => {
// #region EXPECTED
const EXPECTED = `
import dxCLASS_NAME, {
Properties
} from "DX/WIDGET/PATH";
import * as PropTypes from "prop-types";
import { Component as BaseComponent, IHtmlOptions } from "BASE_COMPONENT_PATH";
interface ICLASS_NAMEOptions extends Properties, IHtmlOptions {
}
class CLASS_NAME extends BaseComponent<ICLASS_NAMEOptions> {
public get instance(): dxCLASS_NAME {
return this._instance;
}
protected _WidgetClass = dxCLASS_NAME;
}
(CLASS_NAME as any).propTypes = {
PROP1: PropTypes.oneOfType([
PropTypes.SOME_TYPE,
PropTypes.ANOTHER_TYPE
])
};
export default CLASS_NAME;
export {
CLASS_NAME,
ICLASS_NAMEOptions
};
`.trimLeft();
// #endregion
expect(
generate({
name: 'CLASS_NAME',
baseComponentPath: 'BASE_COMPONENT_PATH',
extensionComponentPath: 'EXTENSION_COMPONENT_PATH',
dxExportPath: 'DX/WIDGET/PATH',
propTypings: [
{
propName: 'PROP1',
types: ['SOME_TYPE', 'ANOTHER_TYPE'],
},
],
}),
).toBe(EXPECTED);
});
it('adds typings in alphabetic order', () => {
// #region EXPECTED
const EXPECTED = `
import dxCLASS_NAME, {
Properties
} from "DX/WIDGET/PATH";
import * as PropTypes from "prop-types";
import { Component as BaseComponent, IHtmlOptions } from "BASE_COMPONENT_PATH";
interface ICLASS_NAMEOptions extends Properties, IHtmlOptions {
}
class CLASS_NAME extends BaseComponent<ICLASS_NAMEOptions> {
public get instance(): dxCLASS_NAME {
return this._instance;
}
protected _WidgetClass = dxCLASS_NAME;
}
(CLASS_NAME as any).propTypes = {
A-PROP: PropTypes.oneOfType([
PropTypes.TYPE_1,
PropTypes.TYPE_2
]),
a-PROP: PropTypes.TYPE_3,
B-PROP: PropTypes.TYPE_4,
c-PROP: PropTypes.TYPE_2
};
export default CLASS_NAME;
export {
CLASS_NAME,
ICLASS_NAMEOptions
};
`.trimLeft();
// #endregion
expect(
generate({
name: 'CLASS_NAME',
baseComponentPath: 'BASE_COMPONENT_PATH',
extensionComponentPath: 'EXTENSION_COMPONENT_PATH',
dxExportPath: 'DX/WIDGET/PATH',
propTypings: [
{
propName: 'A-PROP',
types: ['TYPE_1', 'TYPE_2'],
},
{
propName: 'c-PROP',
types: ['TYPE_2'],
},
{
propName: 'a-PROP',
types: ['TYPE_3'],
},
{
propName: 'B-PROP',
types: ['TYPE_4'],
},
],
}),
).toBe(EXPECTED);
});
});
describe('child expectation', () => {
it('is rendered for widget', () => {
// #region EXPECTED
const EXPECTED = `
import dxCLASS_NAME, {
Properties
} from "DX/WIDGET/PATH";
import { Component as BaseComponent, IHtmlOptions } from "BASE_COMPONENT_PATH";
interface ICLASS_NAMEOptions extends Properties, IHtmlOptions {
}
class CLASS_NAME extends BaseComponent<ICLASS_NAMEOptions> {
public get instance(): dxCLASS_NAME {
return this._instance;
}
protected _WidgetClass = dxCLASS_NAME;
protected _expectedChildren = {
expectedOption1: { optionName: "expectedName1", isCollectionItem: true },
expectedOption2: { optionName: "expectedName2", isCollectionItem: false }
};
}
export default CLASS_NAME;
export {
CLASS_NAME,
ICLASS_NAMEOptions
};
`.trimLeft();
// #endregion
expect(
generate({
name: 'CLASS_NAME',
baseComponentPath: 'BASE_COMPONENT_PATH',
extensionComponentPath: 'EXTENSION_COMPONENT_PATH',
dxExportPath: 'DX/WIDGET/PATH',
expectedChildren: [
{ componentName: 'expectedOption1', optionName: 'expectedName1', isCollectionItem: true },
{ componentName: 'expectedOption2', optionName: 'expectedName2' },
],
}),
).toBe(EXPECTED);
});
it('is rendered for nested option', () => {
// #region EXPECTED
const EXPECTED = `
import dxCLASS_NAME, {
Properties
} from "DX/WIDGET/PATH";
import { Component as BaseComponent, IHtmlOptions } from "BASE_COMPONENT_PATH";
import NestedOption from "CONFIG_COMPONENT_PATH";
interface ICLASS_NAMEOptions extends Properties, IHtmlOptions {
}
class CLASS_NAME extends BaseComponent<ICLASS_NAMEOptions> {
public get instance(): dxCLASS_NAME {
return this._instance;
}
protected _WidgetClass = dxCLASS_NAME;
}
// owners:
// CLASS_NAME
interface IOpt_1_ComponentProps {
}
class Opt_1_Component extends NestedOption<IOpt_1_ComponentProps> {
public static OptionName = "opt_1";
public static ExpectedChildren = {
expectedOption1: { optionName: "expectedName1", isCollectionItem: true },
expectedOption2: { optionName: "expectedName2", isCollectionItem: false }
};
}
export default CLASS_NAME;
export {
CLASS_NAME,
ICLASS_NAMEOptions,
Opt_1_Component,
IOpt_1_ComponentProps
};
`.trimLeft();
// #endregion
expect(
generate({
name: 'CLASS_NAME',
baseComponentPath: 'BASE_COMPONENT_PATH',
extensionComponentPath: 'EXTENSION_COMPONENT_PATH',
configComponentPath: 'CONFIG_COMPONENT_PATH',
dxExportPath: 'DX/WIDGET/PATH',
nestedComponents: [
{
className: 'Opt_1_Component',
owners: ['CLASS_NAME'],
optionName: 'opt_1',
options: [],
expectedChildren: [
{
componentName: 'expectedOption1',
optionName: 'expectedName1',
isCollectionItem: true,
},
{
componentName: 'expectedOption2',
optionName: 'expectedName2',
},
],
},
],
}),
).toBe(EXPECTED);
});
}); | the_stack |
import { IRequestPaymentOptions } from './settings';
import { IPreparedTransaction } from './prepared-transaction';
import { providers, BigNumber } from 'ethers';
import { hasErc20Approval, prepareApproveErc20 } from './erc20';
import { ClientTypes, ExtensionTypes, RequestLogicTypes } from '@requestnetwork/types';
import {
hasErc20ApprovalForProxyConversion,
prepareApproveErc20ForProxyConversion,
} from './conversion-erc20';
import { hasApprovalErc20ForSwapToPay, prepareApprovalErc20ForSwapToPay } from './swap-erc20';
import {
hasErc20ApprovalForSwapWithConversion,
prepareApprovalErc20ForSwapWithConversionToPay,
} from './swap-conversion-erc20';
import { getPaymentNetworkExtension } from './utils';
/**
* For a given request and user, encode an approval transaction if it is needed.
* @param request the request
* @param provider generic provider
* @param from the user who will pay the request
* @param options specific to the request payment (conversion, swapping, ...)
*/
export async function encodeRequestErc20ApprovalIfNeeded(
request: ClientTypes.IRequestData,
provider: providers.Provider,
from: string,
options?: IRequestPaymentOptions,
): Promise<IPreparedTransaction | void> {
if (options && options.swap) {
return encodeRequestErc20ApprovalWithSwapIfNeeded(request, provider, from, options);
} else {
return encodeRequestErc20ApprovalWithoutSwapIfNeeded(request, provider, from, options);
}
}
/**
* For a given request, encode an approval transaction.
* @param request the request
* @param provider generic provider
* @param options specific to the request payment (conversion, ...)
*/
export function encodeRequestErc20Approval(
request: ClientTypes.IRequestData,
provider: providers.Provider,
options?: IRequestPaymentOptions,
): IPreparedTransaction | void {
if (options && options.swap) {
return encodeRequestErc20ApprovalWithSwap(request, provider, options);
} else {
return encodeRequestErc20ApprovalWithoutSwap(request, provider, options);
}
}
/**
* For a given request and user, encode an approval transaction if it is needed when swap is not used.
* @param request the request
* @param provider generic provider
* @param from user who will pay the request
* @param options specific to the request payment (conversion, swapping, ...)
*/
export async function encodeRequestErc20ApprovalWithoutSwapIfNeeded(
request: ClientTypes.IRequestData,
provider: providers.Provider,
from: string,
options?: IRequestPaymentOptions,
): Promise<IPreparedTransaction | void> {
if (await isRequestErc20ApprovalWithoutSwapNeeded(request, provider, from, options)) {
return encodeRequestErc20ApprovalWithoutSwap(request, provider, options);
}
}
/**
* For a given request and user, encode an approval transaction if it is needed when swap is used.
* @param request the request
* @param provider generic provider
* @param from user who will pay the request
* @param options specific to the request payment (conversion, swapping, ...)
*/
export async function encodeRequestErc20ApprovalWithSwapIfNeeded(
request: ClientTypes.IRequestData,
provider: providers.Provider,
from: string,
options?: IRequestPaymentOptions,
): Promise<IPreparedTransaction | void> {
if (!options || !options.swap) {
throw new Error('No swap options');
}
if (await isRequestErc20ApprovalWithSwapNeeded(request, provider, from, options)) {
return encodeRequestErc20ApprovalWithSwap(request, provider, options);
}
}
/**
* For a given request, encode an approval transaction when swap is not used.
* @param request the request
* @param provider generic provider
* @param options specific to the request payment (conversion, ...)
*/
export function encodeRequestErc20ApprovalWithoutSwap(
request: ClientTypes.IRequestData,
provider: providers.Provider,
options?: IRequestPaymentOptions,
): IPreparedTransaction | void {
const paymentNetwork = getPaymentNetworkExtension(request)?.id;
const overrides = options?.overrides ? options.overrides : undefined;
switch (paymentNetwork) {
case ExtensionTypes.ID.PAYMENT_NETWORK_ERC20_PROXY_CONTRACT:
return prepareApproveErc20(request, provider, overrides);
case ExtensionTypes.ID.PAYMENT_NETWORK_ERC20_FEE_PROXY_CONTRACT:
return prepareApproveErc20(request, provider, overrides);
case ExtensionTypes.ID.PAYMENT_NETWORK_ANY_TO_ERC20_PROXY: {
if (
!options ||
!options.conversion ||
!options.conversion.currency ||
options.conversion.currency.type !== RequestLogicTypes.CURRENCY.ERC20
) {
throw new Error('Conversion settings missing');
}
return prepareApproveErc20ForProxyConversion(
request,
options.conversion.currency.value,
provider,
overrides,
);
}
}
}
/**
* For a given request, encode an approval transaction when swap is used.
* @param request the request
* @param provider generic provider
* @param options specific to the request payment (conversion, swapping, ...)
*/
export function encodeRequestErc20ApprovalWithSwap(
request: ClientTypes.IRequestData,
provider: providers.Provider,
options: IRequestPaymentOptions,
): IPreparedTransaction | void {
const paymentNetwork = getPaymentNetworkExtension(request)?.id;
const overrides = options?.overrides ? options.overrides : undefined;
switch (paymentNetwork) {
case ExtensionTypes.ID.PAYMENT_NETWORK_ERC20_FEE_PROXY_CONTRACT:
if (options && options.swap) {
return prepareApprovalErc20ForSwapToPay(request, options.swap.path[0], provider, overrides);
} else {
throw new Error('No swap options');
}
case ExtensionTypes.ID.PAYMENT_NETWORK_ANY_TO_ERC20_PROXY: {
if (
!options ||
!options.conversion ||
!options.conversion.currency ||
options.conversion.currency.type !== RequestLogicTypes.CURRENCY.ERC20
) {
throw new Error('Conversion settings missing');
}
if (options.swap) {
return prepareApprovalErc20ForSwapWithConversionToPay(
request,
options.swap.path[0],
provider,
overrides,
);
} else {
throw new Error('No swap options');
}
}
default:
return;
}
}
/**
* Check if for a given request and user, an approval transaction is needed.
* @param request the request
* @param provider generic provider
* @param from user who will make the payment
* @param options specific to the request payment (conversion, ...)
*/
export async function isRequestErc20ApprovalNeeded(
request: ClientTypes.IRequestData,
provider: providers.Provider,
from: string,
options?: IRequestPaymentOptions,
): Promise<boolean> {
if (options && options.swap) {
return isRequestErc20ApprovalWithSwapNeeded(request, provider, from, options);
}
return isRequestErc20ApprovalWithoutSwapNeeded(request, provider, from, options);
}
/**
* Check if for a given request and user, an approval transaction is needed when swap is not used.
* @param request the request
* @param provider generic provider
* @param from user who will make the payment
* @param options specific to the request payment (conversion, ...)
*/
export async function isRequestErc20ApprovalWithoutSwapNeeded(
request: ClientTypes.IRequestData,
provider: providers.Provider,
from: string,
options?: IRequestPaymentOptions,
): Promise<boolean> {
const paymentNetwork = getPaymentNetworkExtension(request)?.id;
switch (paymentNetwork) {
case ExtensionTypes.ID.PAYMENT_NETWORK_ERC20_PROXY_CONTRACT:
if (!(await hasErc20Approval(request, from))) {
return true;
}
break;
case ExtensionTypes.ID.PAYMENT_NETWORK_ERC20_FEE_PROXY_CONTRACT:
if (!(await hasErc20Approval(request, from))) {
return true;
}
break;
case ExtensionTypes.ID.PAYMENT_NETWORK_ANY_TO_ERC20_PROXY: {
if (
!options ||
!options.conversion ||
!options.conversion.currency ||
options.conversion.currency.type !== RequestLogicTypes.CURRENCY.ERC20
) {
throw new Error('Conversion settings missing');
}
const amount = options.conversion.maxToSpend
? options.conversion.maxToSpend
: BigNumber.from(0);
if (
!(await hasErc20ApprovalForProxyConversion(
request,
from,
options.conversion.currency.value,
provider,
amount,
))
) {
return true;
}
break;
}
}
return false;
}
/**
* Check if for a given request and user, an approval transaction is needed when swap is used.
* @param request the request
* @param provider generic provider
* @param from user who will make the payment
* @param options specific to the request payment (conversion, swapping, ...)
*/
export async function isRequestErc20ApprovalWithSwapNeeded(
request: ClientTypes.IRequestData,
provider: providers.Provider,
from: string,
options: IRequestPaymentOptions,
): Promise<boolean> {
const paymentNetwork = getPaymentNetworkExtension(request)?.id;
switch (paymentNetwork) {
case ExtensionTypes.ID.PAYMENT_NETWORK_ERC20_FEE_PROXY_CONTRACT:
if (options && options.swap) {
if (
!(await hasApprovalErc20ForSwapToPay(
request,
from,
options.swap.path[0],
provider,
options.swap.maxInputAmount,
))
) {
return true;
}
} else {
throw new Error('No swap options');
}
break;
case ExtensionTypes.ID.PAYMENT_NETWORK_ANY_TO_ERC20_PROXY: {
if (
!options ||
!options.conversion ||
!options.conversion.currency ||
options.conversion.currency.type !== RequestLogicTypes.CURRENCY.ERC20
) {
throw new Error('Conversion settings missing');
}
if (options.swap) {
const amount = options.swap.maxInputAmount
? options.swap.maxInputAmount
: BigNumber.from(0);
if (
!(await hasErc20ApprovalForSwapWithConversion(
request,
from,
options.swap.path[0],
provider,
amount,
))
) {
return true;
}
} else {
throw new Error('No swap options');
}
break;
}
}
return false;
} | the_stack |
import { domSearch, domSearchAll, getNumber, searchIFrame, sleep, StringUtils, waitForRecognize } from '../../core/utils';
import { OCSWorker } from '../../core/worker';
import { defaultAnswerWrapperHandler } from '../../core/worker/answer.wrapper.handler';
import { logger } from '../../logger';
import { ScriptSettings } from '../../scripts';
import { message } from '../../components/utils';
import CXAnalyses from './utils';
import { useSettings, useContext, useStore } from '../../store';
/**
* cx 任务学习
*/
export async function study() {
logger('debug', '即将开始');
const { cx: setting } = useSettings();
const tasks = searchTask(setting.study);
for (const task of tasks) {
try {
await sleep(3000);
await task();
} catch (e) {
logger('error', '未知错误:', e);
}
}
// 下一章按钮
const { next } = domSearch({ next: '.next[onclick^="PCount.next"]' }, top?.document);
// 如果按钮显示
if (next !== null && next.style.display === 'block') {
// 如果即将切换到下一章节
if (CXAnalyses.isInFinalTab()) {
if (CXAnalyses.isStuckInBreakingMode()) {
message('warn', '检测到此章节重复进入, 为了避免无限重复, 请自行手动完成后手动点击下一章, 或者刷新重试。');
return;
}
}
logger('debug', '完成, 即将跳转, 如卡死请自行点击下一章。');
await sleep(3000);
next.click();
} else {
if (CXAnalyses.isInFinalChapter()) {
if (CXAnalyses.isFinishedAllChapters()) {
message('success', '全部任务点已完成!');
} else {
message('warn', '已经抵达最后一个章节!但仍然有任务点未完成,请手动切换至未完成的章节。');
}
} else {
message('error', '下一章按钮不存在,请尝试刷新或者手动切换下一章。');
}
}
}
/**
* 搜索任务点
*/
function searchTask(setting: ScriptSettings['cx']['study']): (() => Promise<void> | undefined)[] {
return searchIFrame(document)
.map((frame) => {
const { media, read, chapterTest } = domSearch(
{
media: 'video,audio',
chapterTest: '.TiMu',
read: '#img.imglook'
},
frame.contentDocument || document
);
function getJob() {
return media
? mediaTask(setting, media as any, frame)
: read
? readTask(frame)
: chapterTest
? chapterTestTask(frame)
: undefined;
}
if (media || read || chapterTest) {
return () => {
// @ts-ignore
let _parent = frame.contentWindow;
// @ts-ignore
let jobIndex = getNumber(frame.contentWindow?._jobindex, _parent._jobindex);
while (_parent) {
// @ts-ignore
jobIndex = getNumber(jobIndex, frame.contentWindow?._jobindex, _parent._jobindex);
// @ts-ignore
const attachments = _parent?.JC?.attachments || _parent.attachments;
if (attachments && typeof jobIndex === 'number') {
const { name, title, bookname, author } = attachments[jobIndex]?.property || {};
const jobName = name || title || (bookname ? bookname + author : undefined) || '未知任务';
// 直接重复学习,不执行任何判断, 章节测试除外
if (setting.restudy && !chapterTest) {
logger('debug', jobName, '即将重新学习。');
return getJob();
} else if (attachments[jobIndex]?.job === true) {
logger('debug', jobName, '即将开始。');
return getJob();
} else if (chapterTest && setting.forceWork) {
logger('debug', jobName, '开启强制答题。');
return getJob();
} else {
logger('debug', jobName, '已经完成,即将跳过。');
break;
}
}
// @ts-ignore
if (_parent.parent === _parent) {
break;
}
// @ts-ignore
_parent = _parent.parent;
}
};
} else {
return undefined;
}
})
.filter((f) => f) as any[];
}
/**
* 永久固定显示视频进度
*/
export function fixedVideoProgress(fixed: boolean) {
const videojs = useContext().cx.videojs;
if (videojs) {
const { bar } = domSearch({ bar: '.vjs-control-bar' }, videojs);
if (bar) {
console.log('fixedVideoProgress', { bar, fixed });
bar.style.opacity = fixed ? '1' : '0';
}
}
}
/**
* 视频路线切换
*/
export function switchPlayLine(
setting: ScriptSettings['cx']['study'],
videojs: HTMLElement,
media: HTMLMediaElement,
line: string
) {
if (setting.line === '默认路线') {
logger('debug', '当前播放路线为: 默认路线,如觉得视频卡顿,请尝试切换其他路线。');
} else {
const { playbackRate = 1 } = setting;
// @ts-ignore
if (videojs?.player) {
// @ts-ignore 播放路线列表
const playlines: { label: string }[] = Array.from(videojs.player.controlBar.options_.playerOptions.playlines);
// 播放菜单元素
const menus: HTMLElement[] = Array.from(
// @ts-ignore
videojs.player.controlBar.videoJsPlayLine.querySelectorAll('ul li')
);
setting.playlines = ['默认路线'].concat(playlines.map(line => line.label));
logger('debug', '切换路线中: ' + line);
selectLine(line);
function selectLine(line: string) {
for (const menu of menus) {
if (menu.textContent?.includes(line)) {
menu.click();
setting.line = line;
/** 重新选择倍速 */
setTimeout(() => (media.playbackRate = playbackRate), 3000);
break;
}
}
}
}
}
}
/**
* 播放视频和音频
*/
function mediaTask(setting: ScriptSettings['cx']['study'], media: HTMLMediaElement, frame: HTMLIFrameElement) {
const { playbackRate = 1, volume = 0 } = setting;
// @ts-ignore
const { videojs } = domSearch({ videojs: '#video' }, frame.contentDocument || document);
if (!videojs) {
message('error', '视频检测不到,请尝试刷新或者手动切换下一章。');
return;
}
const { cx, common } = useStore('context');
cx.videojs = videojs;
common.currentMedia = media;
if (videojs && setting.line) {
// 切换路线
setTimeout(() => switchPlayLine(setting, videojs, media, setting.line), 3000);
}
// 是否固定视频进度
fixedVideoProgress(setting.showProgress);
/**
* 视频播放
*/
return new Promise<void>((resolve) => {
if (media) {
media.volume = volume;
media.play();
media.playbackRate = playbackRate;
async function playFunction() {
// @ts-ignore
if (!media.ended && !media.__played__) {
// 重新播放
await sleep(1000);
media.play();
} else {
// @ts-ignore
media.__played__ = true;
logger('info', '视频播放完毕');
// @ts-ignore
media.removeEventListener('pause', playFunction);
}
}
media.addEventListener('pause', playFunction);
media.addEventListener('ended', () => resolve());
}
});
}
/**
* 阅读 ppt
*/
async function readTask(frame?: HTMLIFrameElement) {
// @ts-ignore
const finishJob = frame?.contentWindow?.finishJob;
if (finishJob) finishJob();
await sleep(3000);
}
/**
* 章节测验
*/
async function chapterTestTask(frame: HTMLIFrameElement) {
const { period, timeout, retry, waitForCheck } = useSettings().cx.work;
const { answererWrappers } = useSettings().common;
const { study } = useSettings().cx;
const ctx = useContext();
if (study.upload === 'close') {
logger('warn', '自动答题已被关闭!');
} else if (answererWrappers.length === 0) {
logger('warn', '题库配置为空,请设置。');
// @ts-ignore
} else if (!frame.contentWindow) {
logger('warn', '元素不可访问');
} else {
logger('info', '开始自动答题');
// 等待文字识别
await waitForRecognize('cx');
const { window: frameWindow } = frame.contentWindow;
const { TiMu } = domSearchAll({ TiMu: '.TiMu' }, frameWindow.document);
/** 清空答案 */
ctx.common.workResults = [];
/** 新建答题器 */
const worker = new OCSWorker({
root: TiMu,
elements: {
title: '.Zy_TItle .clearfix',
/**
* 兼容各种选项
*
* ul li .after 单选多选
* ul li label:not(.after) 判断题
* ul li textarea 填空题
*/
options: 'ul li .after,ul li textarea,ul textarea,ul li label:not(.before)',
type: 'input[id^="answertype"]'
},
/** 默认搜题方法构造器 */
answerer: (elements, type, ctx) => {
const title = StringUtils.nowrap(elements.title[0].innerText)
.replace(/(\d+)?【.*?题】/, '')
.replace(/(\d+.0分)/, '')
.trim();
if (title) {
return defaultAnswerWrapperHandler(answererWrappers, { type, title, root: ctx.root });
} else {
throw new Error('题目为空,请查看题目是否为空,或者忽略此题');
}
},
work: {
/**
* cx 题目类型 :
* 0 单选题
* 1 多选题
* 2 简答题
* 3 判断题
* 4 填空题
*/
type({ elements }) {
const typeInput = elements.type[0] as HTMLInputElement;
const type = parseInt(typeInput.value);
return type === 0
? 'single'
: type === 1
? 'multiple'
: type === 2
? 'completion'
: type === 3
? 'judgement'
: elements.options[0].tagName === 'TEXTAREA' ||
elements.options[0].querySelector('textarea') ||
elements.options[0].parentElement?.querySelector('textarea')
? 'completion'
: undefined;
},
/** 自定义处理器 */
handler(type, answer, option) {
if (type === 'judgement' || type === 'single' || type === 'multiple') {
if (!option.parentElement?.querySelector('input')?.checked) {
// @ts-ignore
option.parentElement?.querySelector('a,label')?.click();
}
} else if (type === 'completion' && answer.trim()) {
const textarea = option.parentElement?.querySelector('textarea');
const textareaFrame = option.parentElement?.querySelector('iframe');
if (textarea) {
textarea.value = answer;
}
if (textareaFrame?.contentDocument) {
textareaFrame.contentDocument.body.innerHTML = answer;
}
}
}
},
/** 元素搜索完成后 */
onElementSearched(elements) {
const typeInput = elements.type[0] as HTMLInputElement;
const type = parseInt(typeInput.value);
/** 判断题 */
if (type === 3) {
elements.options.forEach((option) => {
const ri = option.querySelector('.ri');
const span = document.createElement('span');
span.innerText = ri ? '√' : '×';
option.appendChild(span);
});
}
},
/** 完成答题后 */
onResult: async (res) => {
if (res.ctx) {
ctx.common.workResults.push(res);
}
const randomWork = study.randomWork;
// 没有完成时随机作答
if (!res.result?.finish && randomWork.enable) {
const options = res.ctx?.elements?.options || [];
const type = res.type;
if (randomWork.choice && (type === 'judgement' || type === 'single' || type === 'multiple')) {
const option = options[Math.floor(Math.random() * options.length)];
// @ts-ignore 随机选择选项
option.parentElement?.querySelector('a,label')?.click();
} else if (randomWork.complete && type === 'completion') {
// 随机填写答案
for (const option of options) {
const textarea = option.parentElement?.querySelector('textarea');
const completeTexts = randomWork.completeTexts
.filter(Boolean);
const text = completeTexts[Math.floor(Math.random() * completeTexts.length)];
const textareaFrame = option.parentElement?.querySelector('iframe');
if (textarea) {
textarea.value = text;
}
if (textareaFrame?.contentDocument) {
textareaFrame.contentDocument.body.innerHTML = text;
}
await sleep(500);
}
}
logger('info', '正在随机作答');
} else {
logger('info', '答题', res.result?.finish ? '完成' : '未完成');
}
},
/** 其余配置 */
period: (period || 3) * 1000,
timeout: (timeout || 30) * 1000,
retry,
stopWhenError: false
});
const results = await worker.doWork();
logger('info', '做题完毕', results);
// 处理提交
await worker.uploadHandler({
uploadRate: study.upload,
results,
async callback(finishedRate, uploadable) {
const name = study.upload === 'force' ? '强制提交' : '自动提交';
logger('info', '完成率 : ', finishedRate, ' , ', uploadable ? '5秒后将' + name : ' 5秒后将自动保存');
await sleep(5000);
if (uploadable) {
// @ts-ignore 提交
frameWindow.btnBlueSubmit();
await sleep(3000);
/** 确定按钮 */
// @ts-ignore 确定
frameWindow.submitCheckTimes();
} else {
// @ts-ignore 禁止弹窗
frameWindow.alert = () => { };
// @ts-ignore 暂时保存
frameWindow.noSubmit();
}
}
});
}
if (waitForCheck) {
logger('debug', `正在等待答题检查: 一共 ${waitForCheck} 秒`);
await sleep(waitForCheck * 1000);
}
} | the_stack |
import React, { useState, useRef, useCallback } from 'react';
import { localPoint } from '@visx/event';
import { useGesture, UserHandlers } from '@use-gesture/react';
import {
composeMatrices,
inverseMatrix,
applyMatrixToPoint,
applyInverseMatrixToPoint,
translateMatrix,
identityMatrix,
scaleMatrix,
} from './util/matrix';
import {
TransformMatrix,
Point,
Translate,
Scale,
ScaleSignature,
ProvidedZoom,
PinchDelta,
} from './types';
// default prop values
const defaultInitialTransformMatrix = {
scaleX: 1,
scaleY: 1,
translateX: 0,
translateY: 0,
skewX: 0,
skewY: 0,
};
const defaultWheelDelta = (event: React.WheelEvent | WheelEvent) =>
-event.deltaY > 0 ? { scaleX: 1.1, scaleY: 1.1 } : { scaleX: 0.9, scaleY: 0.9 };
const defaultPinchDelta: PinchDelta = ({ offset: [s], lastOffset: [lastS] }) => ({
scaleX: s - lastS < 0 ? 0.9 : 1.1,
scaleY: s - lastS < 0 ? 0.9 : 1.1,
});
export type ZoomProps<ElementType> = {
/** Width of the zoom container. */
width: number;
/** Height of the zoom container. */
height: number;
/**
* ```js
* wheelDelta(event)
* ```
*
* A function that returns { scaleX,scaleY } factors to scale the matrix by.
* Scale factors greater than 1 will increase (zoom in), less than 1 will decrease (zoom out).
*/
wheelDelta?: (event: React.WheelEvent | WheelEvent) => Scale;
/**
* ```js
* pinchDelta(state)
* ```
*
* A function that returns { scaleX, scaleY, point } factors to scale the matrix by.
* Scale factors greater than 1 will increase (zoom in), less than 1 will decrease (zoom out), the point is used to find where to zoom.
* The state parameter is from react-use-gestures onPinch handler
*/
pinchDelta?: PinchDelta;
/** Minimum x scale value for transform. */
scaleXMin?: number;
/** Maximum x scale value for transform. */
scaleXMax?: number;
/** Minimum y scale value for transform. */
scaleYMin?: number;
/** Maximum y scale value for transform. */
scaleYMax?: number;
/**
* By default constrain() will only constrain scale values. To change
* constraints you can pass in your own constrain function as a prop.
*
* For example, if you wanted to constrain your view to within [[0, 0], [width, height]]:
*
* ```js
* function constrain(transformMatrix, prevTransformMatrix) {
* const min = applyMatrixToPoint(transformMatrix, { x: 0, y: 0 });
* const max = applyMatrixToPoint(transformMatrix, { x: width, y: height });
* if (max.x < width || max.y < height) {
* return prevTransformMatrix;
* }
* if (min.x > 0 || min.y > 0) {
* return prevTransformMatrix;
* }
* return transformMatrix;
* }
* ```
*/
constrain?: (transform: TransformMatrix, prevTransform: TransformMatrix) => TransformMatrix;
/** Initial transform matrix to apply. */
initialTransformMatrix?: TransformMatrix;
children: (zoom: ProvidedZoom<ElementType> & ZoomState) => React.ReactNode;
};
type ZoomState = {
initialTransformMatrix: TransformMatrix;
transformMatrix: TransformMatrix;
isDragging: boolean;
};
function Zoom<ElementType extends Element>({
scaleXMin = 0,
scaleXMax = Infinity,
scaleYMin = 0,
scaleYMax = Infinity,
initialTransformMatrix = defaultInitialTransformMatrix,
wheelDelta = defaultWheelDelta,
pinchDelta = defaultPinchDelta,
width,
height,
constrain,
children,
}: ZoomProps<ElementType>): JSX.Element {
const containerRef = useRef<ElementType>(null);
const matrixStateRef = useRef<TransformMatrix>(initialTransformMatrix);
const [transformMatrix, setTransformMatrixState] = useState<TransformMatrix>(
initialTransformMatrix!,
);
const [isDragging, setIsDragging] = useState(false);
const [startTranslate, setStartTranslate] = useState<Translate | undefined>(undefined);
const [startPoint, setStartPoint] = useState<Point | undefined>(undefined);
const defaultConstrain = useCallback(
(newTransformMatrix: TransformMatrix, prevTransformMatrix: TransformMatrix) => {
if (constrain) return constrain(newTransformMatrix, prevTransformMatrix);
const { scaleX, scaleY } = newTransformMatrix;
const shouldConstrainScaleX = scaleX > scaleXMax! || scaleX < scaleXMin!;
const shouldConstrainScaleY = scaleY > scaleYMax! || scaleY < scaleYMin!;
if (shouldConstrainScaleX || shouldConstrainScaleY) {
return prevTransformMatrix;
}
return newTransformMatrix;
},
[constrain, scaleXMin, scaleXMax, scaleYMin, scaleYMax],
);
const setTransformMatrix = useCallback(
(newTransformMatrix: TransformMatrix) => {
setTransformMatrixState((prevTransformMatrix) => {
const updatedTransformMatrix = defaultConstrain(newTransformMatrix, prevTransformMatrix);
matrixStateRef.current = updatedTransformMatrix;
return updatedTransformMatrix;
});
},
[defaultConstrain],
);
const applyToPoint = useCallback(
({ x, y }: Point) => {
return applyMatrixToPoint(transformMatrix, { x, y });
},
[transformMatrix],
);
const applyInverseToPoint = useCallback(
({ x, y }: Point) => {
return applyInverseMatrixToPoint(transformMatrix, { x, y });
},
[transformMatrix],
);
const reset = useCallback(() => {
setTransformMatrix(initialTransformMatrix);
}, [initialTransformMatrix, setTransformMatrix]);
const scale = useCallback(
({ scaleX, scaleY: maybeScaleY, point }: ScaleSignature) => {
const scaleY = maybeScaleY || scaleX;
const cleanPoint = point || { x: width / 2, y: height / 2 };
// need to use ref value instead of state here because wheel listener does not have access to latest state
const translate = applyInverseMatrixToPoint(matrixStateRef.current, cleanPoint);
const nextMatrix = composeMatrices(
matrixStateRef.current,
translateMatrix(translate.x, translate.y),
scaleMatrix(scaleX, scaleY),
translateMatrix(-translate.x, -translate.y),
);
setTransformMatrix(nextMatrix);
},
[height, width, setTransformMatrix],
);
const translate = useCallback(
({ translateX, translateY }: Translate) => {
const nextMatrix = composeMatrices(transformMatrix, translateMatrix(translateX, translateY));
setTransformMatrix(nextMatrix);
},
[setTransformMatrix, transformMatrix],
);
const setTranslate = useCallback(
({ translateX, translateY }: Translate) => {
const nextMatrix = {
...transformMatrix,
translateX,
translateY,
};
setTransformMatrix(nextMatrix);
},
[setTransformMatrix, transformMatrix],
);
const translateTo = useCallback(
({ x, y }: Point) => {
const point = applyInverseMatrixToPoint(transformMatrix, { x, y });
setTranslate({ translateX: point.x, translateY: point.y });
},
[setTranslate, transformMatrix],
);
const invert = useCallback(() => inverseMatrix(transformMatrix), [transformMatrix]);
const toStringInvert = useCallback(() => {
const { translateX, translateY, scaleX, scaleY, skewX, skewY } = invert();
return `matrix(${scaleX}, ${skewY}, ${skewX}, ${scaleY}, ${translateX}, ${translateY})`;
}, [invert]);
const dragStart = useCallback(
(event: React.MouseEvent | React.TouchEvent | MouseEvent | TouchEvent | React.PointerEvent) => {
const { translateX, translateY } = transformMatrix;
setStartPoint(localPoint(event) || undefined);
setStartTranslate({ translateX, translateY });
setIsDragging(true);
},
[transformMatrix],
);
const dragMove = useCallback(
(
event: React.MouseEvent | React.TouchEvent | MouseEvent | TouchEvent | React.PointerEvent,
options?: { offsetX?: number; offsetY?: number },
) => {
if (!isDragging || !startPoint || !startTranslate) return;
const currentPoint = localPoint(event);
const dx = currentPoint ? -(startPoint.x - currentPoint.x) : -startPoint.x;
const dy = currentPoint ? -(startPoint.y - currentPoint.y) : -startPoint.y;
let translateX = startTranslate.translateX + dx;
if (options?.offsetX) translateX += options?.offsetX;
let translateY = startTranslate.translateY + dy;
if (options?.offsetY) translateY += options?.offsetY;
setTranslate({
translateX,
translateY,
});
},
[isDragging, setTranslate, startPoint, startTranslate],
);
const dragEnd = useCallback(() => {
setStartPoint(undefined);
setStartTranslate(undefined);
setIsDragging(false);
}, []);
const handleWheel = useCallback(
(event: React.WheelEvent | WheelEvent) => {
event.preventDefault();
const point = localPoint(event) || undefined;
const { scaleX, scaleY } = wheelDelta!(event);
scale({ scaleX, scaleY, point });
},
[scale, wheelDelta],
);
const handlePinch: UserHandlers['onPinch'] = useCallback(
(state) => {
const {
origin: [ox, oy],
memo,
} = state;
let currentMemo = memo;
if (containerRef.current) {
const { top, left } = currentMemo ?? containerRef.current.getBoundingClientRect();
if (!currentMemo) {
currentMemo = { top, left };
}
const { scaleX, scaleY } = pinchDelta(state);
scale({
scaleX,
scaleY,
point: { x: ox - left, y: oy - top },
});
}
return currentMemo;
},
[scale, pinchDelta],
);
const toString = useCallback(() => {
const { translateX, translateY, scaleX, scaleY, skewX, skewY } = transformMatrix;
return `matrix(${scaleX}, ${skewY}, ${skewX}, ${scaleY}, ${translateX}, ${translateY})`;
}, [transformMatrix]);
const center = useCallback(() => {
const centerPoint = { x: width / 2, y: height / 2 };
const inverseCentroid = applyInverseToPoint(centerPoint);
translate({
translateX: inverseCentroid.x - centerPoint.x,
translateY: inverseCentroid.y - centerPoint.y,
});
}, [height, width, applyInverseToPoint, translate]);
const clear = useCallback(() => {
setTransformMatrix(identityMatrix());
}, [setTransformMatrix]);
useGesture(
{
onDragStart: ({ event }) => {
if (!(event instanceof KeyboardEvent)) dragStart(event);
},
onDrag: ({ event, pinching, cancel }) => {
if (pinching) {
cancel();
dragEnd();
} else if (!(event instanceof KeyboardEvent)) {
dragMove(event);
}
},
onDragEnd: dragEnd,
onPinch: handlePinch,
onWheel: ({ event }) => handleWheel(event),
},
{ target: containerRef, eventOptions: { passive: false }, drag: { filterTaps: true } },
);
const zoom: ProvidedZoom<ElementType> & ZoomState = {
initialTransformMatrix,
transformMatrix,
isDragging,
center,
clear,
scale,
translate,
translateTo,
setTranslate,
setTransformMatrix,
reset,
handleWheel,
handlePinch,
dragEnd,
dragMove,
dragStart,
toString,
invert,
toStringInvert,
applyToPoint,
applyInverseToPoint,
containerRef,
};
return <>{children(zoom)}</>;
}
export default Zoom; | the_stack |
import { DepartmentModel } from './../../models/department';
import { MessageModel } from '../../models/message';
import { Injectable, ElementRef } from '@angular/core';
import { Globals } from '../../app/utils/globals';
import { ConversationModel } from '../models/conversation';
import { LoggerInstance } from '../providers/logger/loggerInstance';
import { LoggerService } from '../providers/abstract/logger.service';
@Injectable()
export class Triggerhandler {
private el: ElementRef;
private windowContext;
private logger: LoggerService = LoggerInstance.getInstance()
constructor() { }
public setElement(el: ElementRef){
this.el = el
}
public setWindowContext(windowContext){
this.windowContext = windowContext
}
/**CONVERSATION-FOOTER.component */
public triggerBeforeSendMessageEvent(messageModel){
this.logger.debug(' ---------------- triggerBeforeSendMessageEvent ---------------- ', messageModel);
try {
const onBeforeMessageSend = new CustomEvent('onBeforeMessageSend', { detail: { message: messageModel } });
const windowContext = this.windowContext;
if (windowContext.tiledesk && windowContext.tiledesk.tiledeskroot) {
windowContext.tiledesk.tiledeskroot.dispatchEvent(onBeforeMessageSend);
this.windowContext = windowContext;
} else {
this.el.nativeElement.dispatchEvent(onBeforeMessageSend);
}
} catch (e) {
this.logger.error('[TRIGGER-HANDLER] > Error:' + e);
}
}
/**CONVERSATION-FOOTER.component */
public triggerAfterSendMessageEvent(messageSent: MessageModel){
this.logger.debug(' ---------------- triggerAfterSendMessageEvent ---------------- ', messageSent);
try {
const onAfterMessageSend = new CustomEvent('onAfterMessageSend', { detail: { message: messageSent } });
const windowContext = this.windowContext;
if (windowContext.tiledesk && windowContext.tiledesk.tiledeskroot) {
windowContext.tiledesk.tiledeskroot.dispatchEvent(onAfterMessageSend);
this.windowContext = windowContext;
} else {
this.el.nativeElement.dispatchEvent(onAfterMessageSend);
}
} catch (e) {
this.logger.error('[TRIGGER-HANDLER] > Error:' + e);
}
}
/**CONVERSATION.component */
public triggerOnNewConversationInit(detailObj: {}){
this.logger.debug(' ---------------- triggerOnNewConversationComponentInit ---------------- ', detailObj);
const onNewConversation = new CustomEvent('onNewConversationComponentInit', { detail: detailObj });
const windowContext = this.windowContext;
if (windowContext.tiledesk && windowContext.tiledesk.tiledeskroot) {
windowContext.tiledesk.tiledeskroot.dispatchEvent(onNewConversation);
this.windowContext = windowContext;
} else {
this.el.nativeElement.dispatchEvent(onNewConversation);
}
}
/**CONVERSATION.component */
public triggerBeforeMessageRender(detailObj: {}) {
//this.logger.debug(' ---------------- triggerBeforeMessageRender ---------------- ', detailObj]);
try {
const beforeMessageRender = new CustomEvent('beforeMessageRender', { detail: detailObj });
const windowContext = this.windowContext;
if (windowContext.tiledesk && windowContext.tiledesk.tiledeskroot) {
windowContext.tiledesk.tiledeskroot.dispatchEvent(beforeMessageRender);
this.windowContext = windowContext;
} else {
this.el.nativeElement.dispatchEvent(beforeMessageRender);
}
} catch (e) {
this.logger.error('[TRIGGER-HANDLER] > Error:' + e);
}
}
/**CONVERSATION.component */
public triggerAfterMessageRender(detailObj: {}) {
//this.logger.debug(' ---------------- triggerAfterMessageRender ---------------- ', detailObj]);
try {
const afterMessageRender = new CustomEvent('afterMessageRender', { detail: detailObj });
const windowContext = this.windowContext;
if (windowContext.tiledesk && windowContext.tiledesk.tiledeskroot) {
windowContext.tiledesk.tiledeskroot.dispatchEvent(afterMessageRender);
this.windowContext = windowContext;
} else {
this.el.nativeElement.dispatchEvent(afterMessageRender);
}
} catch (e) {
this.logger.error('[TRIGGER-HANDLER] > Error:' + e);
}
}
/**CONVERSATION.component */
public triggerOnMessageCreated(message: MessageModel) {
this.logger.debug(' ---------------- triggerOnMessageCreated ---------------- ', message);
const onMessageCreated = new CustomEvent('onMessageCreated', { detail: { message: message } });
const windowContext = this.windowContext;
if (windowContext.tiledesk && windowContext.tiledesk.tiledeskroot) {
windowContext.tiledesk.tiledeskroot.dispatchEvent(onMessageCreated);
this.windowContext = windowContext;
} else {
this.el.nativeElement.dispatchEvent(onMessageCreated);
}
}
/**APP-COMPONENT.component */
public triggerOnViewInit(detailObj: {}) {
this.logger.debug(' ---------------- triggerOnInit ---------------- ', detailObj);
const onInit = new CustomEvent('onInit', { detail: detailObj });
const windowContext = this.windowContext;
if (windowContext.tiledesk && windowContext.tiledesk.tiledeskroot) {
windowContext.tiledesk.tiledeskroot.dispatchEvent(onInit);
this.windowContext = windowContext;
} else {
this.el.nativeElement.dispatchEvent(onInit);
}
}
/**APP-COMPONENT.component */
public triggerOnOpenEvent(detailObj: {}) {
this.logger.debug(' ---------------- triggerOnOpenEvent ---------------- ', detailObj);
const onOpen = new CustomEvent('onOpen', { detail: detailObj });
const windowContext = this.windowContext;
if (windowContext.tiledesk && windowContext.tiledesk.tiledeskroot) {
windowContext.tiledesk.tiledeskroot.dispatchEvent(onOpen);
this.windowContext = windowContext;
} else {
this.el.nativeElement.dispatchEvent(onOpen);
}
}
/**APP-COMPONENT.component */
public triggerOnCloseEvent(detailObj: {}) {
this.logger.debug(' ---------------- triggerOnCloseEvent ---------------- ', detailObj);
const onClose = new CustomEvent('onClose', { detail: detailObj });
const windowContext = this.windowContext;
if (windowContext.tiledesk && windowContext.tiledesk.tiledeskroot) {
windowContext.tiledesk.tiledeskroot.dispatchEvent(onClose);
this.windowContext = windowContext;
} else {
this.el.nativeElement.dispatchEvent(onClose);
}
}
/**APP-COMPONENT.component */
public triggerOnOpenEyeCatcherEvent(detailObj: {}) {
this.logger.debug(' ---------------- triggerOnOpenEyeCatcherEvent ---------------- ', detailObj);
const onOpenEyeCatcher = new CustomEvent('onOpenEyeCatcher', { detail: detailObj });
const windowContext = this.windowContext;
if (windowContext.tiledesk && windowContext.tiledesk.tiledeskroot) {
windowContext.tiledesk.tiledeskroot.dispatchEvent(onOpenEyeCatcher);
this.windowContext = windowContext;
} else {
this.el.nativeElement.dispatchEvent(onOpenEyeCatcher);
}
}
/**APP-COMPONENT.component */
public triggerOnClosedEyeCatcherEvent() {
this.logger.debug(' ---------------- triggerOnClosedEyeCatcherEvent ---------------- ');
const onClosedEyeCatcher = new CustomEvent('onClosedEyeCatcher', { detail: { } });
const windowContext = this.windowContext;
if (windowContext.tiledesk && windowContext.tiledesk.tiledeskroot) {
windowContext.tiledesk.tiledeskroot.dispatchEvent(onClosedEyeCatcher);
this.windowContext = windowContext;
} else {
this.el.nativeElement.dispatchEvent(onClosedEyeCatcher);
}
}
/**APP-COMPONENT.component */
public triggerOnLoggedIn(detailObj: {}) {
this.logger.debug(' ---------------- triggerOnLoggedIn ---------------- ', detailObj);
const onLoggedIn = new CustomEvent('onLoggedIn', { detail: detailObj});
const windowContext = this.windowContext;
if (windowContext.tiledesk && windowContext.tiledesk.tiledeskroot) {
windowContext.tiledesk.tiledeskroot.dispatchEvent(onLoggedIn);
this.windowContext = windowContext;
} else {
this.el.nativeElement.dispatchEvent(onLoggedIn);
}
}
/**APP-COMPONENT.component */
public triggerOnLoggedOut(detailObj: {}) {
this.logger.debug(' ---------------- triggerOnLoggedOut ---------------- ', detailObj);
const onLoggedOut = new CustomEvent('onLoggedOut', { detail: detailObj});
const windowContext = this.windowContext;
if (windowContext.tiledesk && windowContext.tiledesk.tiledeskroot) {
windowContext.tiledesk.tiledeskroot.dispatchEvent(onLoggedOut);
this.windowContext = windowContext;
} else {
this.el.nativeElement.dispatchEvent(onLoggedOut);
}
}
/**APP-COMPONENT.component */
public triggerOnAuthStateChanged(detailObj: {}) {
this.logger.debug(' ---------------- triggerOnAuthStateChanged ---------------- ', detailObj);
const onAuthStateChanged = new CustomEvent('onAuthStateChanged', { detail: detailObj});
const windowContext = this.windowContext;
if (windowContext.tiledesk && windowContext.tiledesk.tiledeskroot) {
windowContext.tiledesk.tiledeskroot.dispatchEvent(onAuthStateChanged);
this.windowContext = windowContext;
} else {
this.el.nativeElement.dispatchEvent(onAuthStateChanged);
}
}
public triggerNewConversationEvent(detailObj: {}) {
this.logger.debug(' ---------------- triggerNewConversationEvent ---------------- ', detailObj);
const onNewConversation = new CustomEvent('onNewConversation', { detail: detailObj });
const windowContext = this.windowContext;
if (windowContext.tiledesk && windowContext.tiledesk.tiledeskroot) {
windowContext.tiledesk.tiledeskroot.dispatchEvent(onNewConversation);
this.windowContext = windowContext;
} else {
this.el.nativeElement.dispatchEvent(onNewConversation);
}
}
/**APP-COMPONENT.component */
public triggerLoadParamsEvent(detailObj: {}) {
this.logger.debug(' ---------------- triggerOnLoadParamsEvent ---------------- ', detailObj);
const onLoadParams = new CustomEvent('onLoadParams', { detail: detailObj });
const windowContext = this.windowContext;
if (windowContext.tiledesk && windowContext.tiledesk.tiledeskroot) {
windowContext.tiledesk.tiledeskroot.dispatchEvent(onLoadParams);
this.windowContext = windowContext;
} else {
this.el.nativeElement.dispatchEvent(onLoadParams);
}
}
/**APP-COMPONENT.component */
public triggerOnConversationUpdated(conversation: ConversationModel) {
this.logger.debug(' ---------------- triggerOnConversationUpdated ---------------- ', conversation);
try {
const triggerConversationUpdated = new CustomEvent('onConversationUpdated', { detail: { conversation: conversation } });
const windowContext = this.windowContext;
if (windowContext.tiledesk && windowContext.tiledesk.tiledeskroot) {
windowContext.tiledesk.tiledeskroot.dispatchEvent(triggerConversationUpdated);
this.windowContext = windowContext;
} else {
this.el.nativeElement.dispatchEvent(triggerConversationUpdated);
}
} catch (e) {
this.logger.error('[TRIGGER-HANDLER] > Error:' + e);
}
}
/**APP-COMPONENT.component */
public triggerOnCloseMessagePreview() {
this.logger.debug(' ---------------- triggerOnCloseMessagePreview ---------------- ');
try {
const triggerCloseMessagePreview = new CustomEvent('onCloseMessagePreview', { detail: { } });
const windowContext = this.windowContext;
if (windowContext.tiledesk && windowContext.tiledesk.tiledeskroot) {
windowContext.tiledesk.tiledeskroot.dispatchEvent(triggerCloseMessagePreview);
this.windowContext = windowContext;
} else {
this.el.nativeElement.dispatchEvent(triggerCloseMessagePreview);
}
} catch (e) {
this.logger.error('[TRIGGER-HANDLER] > Error:' + e);
}
}
/**SELECTION-DEPARTMENT.component */
public triggerOnbeforeDepartmentsFormRender(departments: DepartmentModel[]) {
this.logger.debug(' ---------------- triggerOnbeforeDepartmentsFormRender ---------------- ');
const onOpen = new CustomEvent('onBeforeDepartmentsFormRender', { detail: { departments: departments } });
const windowContext = this.windowContext;
if (windowContext.tiledesk && windowContext.tiledesk.tiledeskroot) {
windowContext.tiledesk.tiledeskroot.dispatchEvent(onOpen);
this.windowContext = windowContext;
} else {
this.el.nativeElement.dispatchEvent(onOpen);
}
}
/** */
public triggerGetImageUrlThumb(message: MessageModel) {
this.logger.debug(' ---------------- getImageUrlThumb ---------------- ');
try {
const triggerGetImageUrlThumb = new CustomEvent('getImageUrlThumb', { detail: { message: message } });
const windowContext = this.windowContext;
if (windowContext.tiledesk && windowContext.tiledesk.tiledeskroot) {
windowContext.tiledesk.tiledeskroot.dispatchEvent(triggerGetImageUrlThumb);
} else {
// this.el.nativeElement.dispatchEvent(triggerGetImageUrlThumb);
}
} catch (e) {
this.logger.error('[TRIGGER-HANDLER] > Error:' + e);
}
}
} | the_stack |
import { M2048Piece } from "./M2048Piece";
import { M2048Scene } from "./M2048Scene";
import { DIR } from "./M2048Constants";
const { ccclass, property, executeInEditMode } = cc._decorator;
@ccclass
@executeInEditMode
export class M2048Board extends cc.Component {
@property(cc.Integer)
private colsSum: number = 4;
@property(cc.Integer)
private rowsSum: number = 4;
@property(cc.Graphics)
private graphics: cc.Graphics = null; // 用来画棋盘
@property(cc.Prefab)
private piecePrefab: cc.Prefab = null; // 画不了文字,只能用prefab了
@property(cc.Node)
private pieceLayer: cc.Node = null;
private tileWidth: number = 0; // 一个方块的宽度
private startX: number = 0; // 棋盘左下角
private startY: number = 0;
private boardWidth: number = 0; // 棋盘节点宽高
private boardHeight: number = 0;
public pieceMap: Array<Array<M2048Piece>>;
private m2048Scene: M2048Scene = null;
protected onLoad() {
this.tileWidth = this.node.width / (this.colsSum + 1);
this.startX = this.tileWidth / 2;
this.startY = this.tileWidth / 2;
this.boardWidth = this.tileWidth * this.colsSum;
this.boardHeight = this.tileWidth * this.rowsSum;
this.graphics.clear();
// 画棋盘
this.graphics.strokeColor = cc.Color.BLACK;
for (let x = 0; x < this.colsSum + 1; x++) {
this.graphics.moveTo(this.startX + x * this.tileWidth, this.startY);
this.graphics.lineTo(this.startX + x * this.tileWidth, this.startY + this.boardHeight);
this.graphics.stroke();
}
for (let y = 0; y < this.rowsSum + 1; y++) {
this.graphics.moveTo(this.startX, this.startY + y * this.tileWidth);
this.graphics.lineTo(this.startX + this.boardWidth, this.startY + y * this.tileWidth);
this.graphics.stroke();
}
// 初始化数字位置
this.pieceLayer.removeAllChildren();
this.pieceMap = [];
for (let x = 0; x < this.colsSum; x++) {
this.pieceMap[x] = [];
for (let y = 0; y < this.rowsSum; y++) {
let piece = cc.instantiate(this.piecePrefab).getComponent(M2048Piece);
piece.node.parent = this.pieceLayer;
piece.node.x = this.startX + x * this.tileWidth + this.tileWidth / 2;
piece.node.y = this.startY + y * this.tileWidth + this.tileWidth / 2;
this.pieceMap[x][y] = piece;
piece.init(x, x, 0);
}
}
}
public init(m2048Scene: M2048Scene) {
this.m2048Scene = m2048Scene;
this.reset();
this.addListeners();
}
public reset() {
for (let x = 0; x < this.colsSum; x++) {
for (let y = 0; y < this.rowsSum; y++) {
this.pieceMap[x][y].n = 0;
}
}
for (let i = 0; i < 2; i++) {
this.newPiece();
}
}
newPiece() {
let zeroPieces = [];
for (let x = 0; x < this.colsSum; x++) {
for (let y = 0; y < this.rowsSum; y++) {
if (this.pieceMap[x][y].n === 0) {
zeroPieces.push(this.pieceMap[x][y]);
}
}
}
let n = Math.floor(Math.random() * zeroPieces.length);
zeroPieces[n].randomNumber();
}
judgeOver(): boolean {
for (let y = 0; y < this.rowsSum; y++) {
for (let x = 0; x < this.colsSum; x++) {
if (this.pieceMap[x][y].n === 0) {
return false;
}
if (x <= this.colsSum - 2 && this.pieceMap[x][y].n === this.pieceMap[x + 1][y].n) {
return false;
}
if (y <= this.rowsSum - 2 && this.pieceMap[x][y].n === this.pieceMap[x][y + 1].n) {
return false;
}
}
}
return true;
}
getMaxNLabel(): string {
let max = 2;
let str = "2";
for (let x = 0; x < this.colsSum; x++) {
for (let y = 0; y < this.rowsSum; y++) {
if (this.pieceMap[x][y].n > max) {
max = this.pieceMap[x][y].n;
str = this.pieceMap[x][y].nLabel.string;
}
}
}
return str;
}
slideLeft(): boolean {
//左滑F
//合并
let isMove = false;
for (let y = 0; y < this.rowsSum; y++) {
for (let x = 0; x < this.colsSum; x++) {
if (this.pieceMap[x][y].n === 0) {
continue;
}
for (let x0 = x + 1; x0 < this.colsSum; x0++) {
if (this.pieceMap[x0][y].n === 0) {
continue;
} else if (this.pieceMap[x][y].n === this.pieceMap[x0][y].n) {
this.pieceMap[x][y].n *= 2;
this.pieceMap[x0][y].n = 0;
isMove = true;
break;
} else {
break;
}
}
}
}
//移动
for (let y = 0; y < this.rowsSum; y++) {
for (let x = 0; x < this.colsSum; x++) {
if (this.pieceMap[x][y].n !== 0) {
continue;
}
for (let x0 = x + 1; x0 < this.rowsSum; x0++) {
if (this.pieceMap[x0][y].n === 0) {
continue;
} else {
this.pieceMap[x][y].n = this.pieceMap[x0][y].n;
this.pieceMap[x0][y].n = 0;
isMove = true;
break;
}
}
}
}
if (isMove) {
this.newPiece();
}
return isMove;
}
slideRight(): boolean {
//右滑
//合并
let isMove = false; //判断是否有tile移动
for (let y = 0; y < this.rowsSum; y++) {
for (let x = this.colsSum - 1; x >= 0; x--) {
if (this.pieceMap[x][y].n === 0) {
continue;
}
for (let x0 = x - 1; x0 >= 0; x0--) {
if (this.pieceMap[x0][y].n === 0) {
continue;
} else if (this.pieceMap[x][y].n === this.pieceMap[x0][y].n) {
this.pieceMap[x][y].n = this.pieceMap[x][y].n * 2;
this.pieceMap[x0][y].n = 0;
isMove = true;
break;
} else {
break;
}
}
}
}
//移动
for (let y = 0; y < this.rowsSum; y++) {
for (let x = this.colsSum - 1; x >= 0; x--) {
if (this.pieceMap[x][y].n !== 0) {
continue;
}
for (let x0 = x - 1; x0 >= 0; x0--) {
if (this.pieceMap[x0][y].n === 0) {
continue;
} else {
this.pieceMap[x][y].n = this.pieceMap[x0][y].n;
this.pieceMap[x0][y].n = 0;
isMove = true;
break;
}
}
}
}
//有tile移动才添加新的tile
if (isMove) {
this.newPiece();
}
return isMove;
}
slideDown(): boolean {
//下滑
//合并
let isMove = false;
for (let x = 0; x < this.colsSum; x++) {
for (let y = 0; y < this.rowsSum; y++) {
if (this.pieceMap[x][y].n === 0) {
continue;
}
for (let y0 = y + 1; y0 < 4; y0++) {
if (this.pieceMap[x][y0].n === 0) {
continue;
} else if (this.pieceMap[x][y].n === this.pieceMap[x][y0].n) {
this.pieceMap[x][y].n = this.pieceMap[x][y].n * 2;
this.pieceMap[x][y0].n = 0;
isMove = true;
break;
} else {
break;
}
}
}
}
//移动
for (let x = 0; x < this.colsSum; x++) {
for (let y = 0; y < this.rowsSum; y++) {
if (this.pieceMap[x][y].n !== 0) {
continue;
}
for (let y0 = y + 1; y0 < this.rowsSum; y0++) {
if (this.pieceMap[x][y0].n === 0) {
continue;
} else {
this.pieceMap[x][y].n = this.pieceMap[x][y0].n;
this.pieceMap[x][y0].n = 0;
isMove = true;
break;
}
}
}
}
if (isMove) {
this.newPiece();
}
return isMove;
}
slideUp(): boolean {
//上滑
//合并
let isMove = false;
for (let x = 0; x < this.colsSum; x++) {
for (let y = this.rowsSum - 1; y >= 0; y--) {
if (this.pieceMap[x][y].n === 0) {
continue;
}
for (let y0 = y - 1; y0 >= 0; y0--) {
if (this.pieceMap[x][y0].n === 0) {
continue;
} else if (this.pieceMap[x][y].n === this.pieceMap[x][y0].n) {
this.pieceMap[x][y].n = this.pieceMap[x][y].n * 2;
this.pieceMap[x][y0].n = 0;
isMove = true;
break;
} else {
break;
}
}
}
}
//移动
for (let x = 0; x < this.colsSum; x++) {
for (let y = this.rowsSum - 1; y >= 0; y--) {
if (this.pieceMap[x][y].n != 0) {
continue;
}
for (let y0 = y - 1; y0 >= 0; y0--) {
if (this.pieceMap[x][y0].n == 0) {
continue;
} else {
this.pieceMap[x][y].n = this.pieceMap[x][y0].n;
this.pieceMap[x][y0].n = 0;
isMove = true;
break;
}
}
}
}
if (isMove) {
this.newPiece();
}
return isMove;
}
private onTouched(event: cc.Event.EventTouch) {
let startPos = event.getStartLocation();
let endPos = event.getLocation();
let offsetX = endPos.x - startPos.x;
let offsetY = endPos.y - startPos.y;
if (Math.abs(offsetX) > Math.abs(offsetY)) {
if (offsetX > 40) {
this.m2048Scene.onBoardSlid(DIR.RIGHT);
} else if (offsetX < -40) {
this.m2048Scene.onBoardSlid(DIR.LEFT);
}
} else {
if (offsetY > 40) {
this.m2048Scene.onBoardSlid(DIR.UP);
} else if (offsetY < -40) {
this.m2048Scene.onBoardSlid(DIR.DOWN);
}
}
}
private onKey(event) {
switch (event.keyCode) {
case cc.KEY.up:
case cc.KEY.w:
this.m2048Scene.onBoardSlid(DIR.UP);
break;
case cc.KEY.down:
case cc.KEY.s:
this.m2048Scene.onBoardSlid(DIR.DOWN);
break;
case cc.KEY.left:
case cc.KEY.a:
this.m2048Scene.onBoardSlid(DIR.LEFT);
break;
case cc.KEY.right:
case cc.KEY.d:
this.m2048Scene.onBoardSlid(DIR.RIGHT);
break;
}
}
private addListeners() {
this.node.on(cc.Node.EventType.TOUCH_END, this.onTouched, this);
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKey, this);
}
private removeListeners() {
cc.systemEvent.off(cc.SystemEvent.EventType.KEY_DOWN, this.onKey, this);
}
} | the_stack |
import { ComponentPublicInstance, ref, shallowRef } from 'vue'
import { mount, VueWrapper } from '@vue/test-utils'
import { ElInput, ElSwitch } from 'element-plus'
import ProForm from '../src/Form/Form'
import type { IFormColumns, IFormMenuColumns } from '../src/Form/index'
const columns: IFormColumns = [
{
label: 'input',
prop: 'input',
component: 'el-input',
},
]
const _mount = (options: Record<string, unknown>) =>
mount(
{
components: { ProForm },
...options,
},
{
global: {
components: { ElInput, ElSwitch },
},
}
)
const buttonClass =
'.pro-form .el-form-item:last-child .el-form-item__content button'
const getFormList = (wrapper: VueWrapper<ComponentPublicInstance>) =>
wrapper.findAll('.pro-form .pro-form-item')
const getFormClassList = (wrapper: VueWrapper<ComponentPublicInstance>) =>
getFormList(wrapper).map((item) => item.classes())
const getLabelList = (wrapper: VueWrapper<ComponentPublicInstance>) =>
getFormList(wrapper).map((item) => item.find('.el-form-item__label').text())
const getComponentList = (wrapper: VueWrapper<ComponentPublicInstance>) =>
getFormList(wrapper).map((item) =>
item.find('.el-form-item__content div').classes()
)
const getFormBtnList = (wrapper: VueWrapper<ComponentPublicInstance>) =>
wrapper.findAll(buttonClass).map((item) => item.text())
const getFormContent = (
wrapper: VueWrapper<ComponentPublicInstance>,
className = ''
) =>
wrapper.find('.pro-form .pro-form-item .el-form-item__content ' + className)
describe('Form', () => {
afterEach(() => {
document.body.innerHTML = ''
})
test('columns', async () => {
const wrapper = await _mount({
template: '<pro-form v-model="form" :columns="columns" />',
setup() {
const form = ref({})
return { form, columns: ref([...columns]) }
},
})
const vm = (wrapper.vm as unknown) as { columns: IFormColumns }
expect(getFormList(wrapper)).toHaveLength(1)
expect(getLabelList(wrapper)).toContain('input')
expect(getComponentList(wrapper)[0]).toContain('el-input')
await vm.columns.push({
label: 'textarea',
prop: 'textarea',
component: 'el-input',
props: { type: 'textarea' },
})
expect(getFormList(wrapper)).toHaveLength(2)
expect(getLabelList(wrapper)).toContain('input')
expect(getLabelList(wrapper)).toContain('textarea')
expect(getComponentList(wrapper)[1]).toContain('el-textarea')
await vm.columns.splice(0, 1)
expect(getFormList(wrapper)).toHaveLength(1)
expect(getLabelList(wrapper)).not.toContain('input')
expect(getLabelList(wrapper)).toContain('textarea')
expect(getComponentList(wrapper)[0]).not.toContain('el-input')
expect(getComponentList(wrapper)[0]).toContain('el-textarea')
await (vm.columns[0].props = { type: 'text' })
expect(getFormList(wrapper)).toHaveLength(1)
expect(getComponentList(wrapper)[0]).not.toContain('el-textarea')
expect(getComponentList(wrapper)[0]).toContain('el-input')
await ((vm.columns[0].component = 'el-switch'),
(vm.columns[0].props = undefined))
expect(getComponentList(wrapper)[0]).not.toContain('el-input')
expect(getComponentList(wrapper)[0]).toContain('el-switch')
})
test('sub-form', async () => {
const wrapper = await _mount({
template: '<pro-form v-model="form" :columns="columns" />',
setup() {
const form = ref({})
const _columns = ref<IFormColumns>([
{
label: 'Date',
prop: 'date',
component: 'el-input',
},
{
label: 'User',
prop: 'user',
size: 'mini',
children: [
{
label: 'Name',
prop: 'name',
component: 'el-input',
},
{
label: 'Address',
prop: 'address',
component: 'el-input',
},
],
},
])
return { form, columns: _columns }
},
})
const vm = (wrapper.vm as unknown) as { columns: IFormColumns }
expect(getFormContent(wrapper, '.children-form').exists()).toBe(false)
expect(getFormContent(wrapper, '.el-button.is-circle').exists()).toBe(true)
await getFormContent(wrapper, '.el-button.is-circle').trigger('click')
expect(getFormContent(wrapper, '.children-form').exists()).toBe(true)
await (vm.columns = columns)
expect(getFormContent(wrapper, '.children-form').exists()).toBe(false)
expect(getFormContent(wrapper, '.el-button.is-circle').exists()).toBe(false)
})
test('slots', async () => {
const wrapper = await _mount({
template: `
<pro-form
v-model="form"
:columns="columns"
>
<template #slot-label>
slot-label
</template>
<template #slot="{ value, setValue }">
<el-input
:model-value="value"
calss="slot"
@input="e => setValue(e.taget.value)"
/>
</template>
<template #default>
<p class="default">default slot</p>
</template>
<template #menu-left>
<button>menu-left</button>
</template>
<template #menu-right>
<button>menu-right</button>
</template>
</pro-form>
`,
setup() {
const form = ref<{ slot: string }>({ slot: '' })
const _colums = ref<IFormColumns>([
{
label: 'Label',
prop: 'slot',
component: 'el-switch',
},
])
return { form, columns: _colums }
},
})
expect(getFormList(wrapper)).toHaveLength(1)
expect(getComponentList(wrapper)[0]).not.toContain('el-switch')
expect(getComponentList(wrapper)[0]).toContain('el-input')
expect(wrapper.find('label[for="slot"]').text()).toBe('slot-label')
expect(getFormBtnList(wrapper)).toContain('menu-left')
expect(getFormBtnList(wrapper)).toContain('menu-right')
expect(wrapper.find('.pro-form .default').text()).toBe('default slot')
})
test('modelValue', async () => {
interface Form {
input: string
switch: boolean
}
const wrapper = _mount({
template: '<pro-form v-model="form" :columns="columns" />',
setup() {
const form = ref<Form>({
input: '123',
switch: false,
})
const columns: IFormColumns<Form> = [
{
label: 'input',
prop: 'input',
component: 'el-input',
},
{
label: 'switch',
prop: 'switch',
component: 'el-switch',
},
]
return { form, columns }
},
})
const vm = (wrapper.vm as unknown) as {
form: Form
columns: IFormColumns
}
expect(getFormList(wrapper)).toHaveLength(2)
expect(wrapper.find('input').element.value).toBe('123')
expect(wrapper.find('.el-switch').classes()).not.toContain('is-checked')
await wrapper.find('.el-switch').trigger('click')
expect(vm.form.switch).toBeTruthy()
expect(wrapper.find('.el-switch').classes()).toContain('is-checked')
await wrapper.find('input').setValue('value')
expect(vm.form.input).toBe('value')
await (vm.form = { input: 'input', switch: false })
expect(wrapper.find('input').element.value).toBe('input')
expect(wrapper.find('.el-switch').classes()).not.toContain('is-checked')
})
test('menu', async () => {
const wrapper = await _mount({
template: '<pro-form v-model="form" :columns="columns" :menu="menu" />',
setup() {
const form = ref({})
const menu = ref<IFormMenuColumns>({})
return { form, columns, menu }
},
})
const vm = (wrapper.vm as unknown) as { menu: IFormMenuColumns }
expect(getFormBtnList(wrapper)).toContain('Submit')
expect(getFormBtnList(wrapper)).toContain('Reset')
await (vm.menu.submitText = 'submit')
expect(getFormBtnList(wrapper)).toContain('submit')
await (vm.menu.submitProps = { type: 'danger' })
expect(
wrapper
.find(
'.pro-form .el-form-item:last-child .el-form-item__content button.el-button--danger'
)
.exists()
).toBeTruthy()
await (vm.menu.reset = false)
expect(getFormBtnList(wrapper)).not.toContain('Reset')
})
test('grid layout', async () => {
const wrapper = await _mount({
template: '<pro-form v-model="form" :columns="columns" />',
setup() {
const form = ref({})
const columns = ref([
{
label: 'input1',
prop: 'input1',
component: 'el-input',
span: 12,
},
{
label: 'input2',
prop: 'input2',
component: 'el-input',
span: 8,
offset: 4,
},
{
label: 'input3',
prop: 'input3',
component: 'el-input',
span: 4,
push: 2,
pull: 2,
},
{
label: 'input3',
prop: 'input3',
component: 'el-input',
xs: {
span: 24,
},
md: {
span: 20,
push: 2,
pull: 2,
},
lg: {
span: 10,
push: 0,
pull: 0,
offset: 2,
},
},
])
return { form, columns }
},
})
const vm = (wrapper.vm as unknown) as { columns: IFormColumns }
expect(getFormList(wrapper)).toHaveLength(4)
expect(getFormClassList(wrapper)[0]).toContain('el-col')
expect(getFormClassList(wrapper)[0]).toContain('el-col-12')
expect(getFormClassList(wrapper)[1]).toContain('el-col')
expect(getFormClassList(wrapper)[1]).toContain('el-col-8')
expect(getFormClassList(wrapper)[1]).toContain('el-col-offset-4')
expect(getFormClassList(wrapper)[2]).toContain('el-col')
expect(getFormClassList(wrapper)[2]).toContain('el-col-4')
expect(getFormClassList(wrapper)[2]).toContain('el-col-push-2')
expect(getFormClassList(wrapper)[2]).toContain('el-col-pull-2')
expect(getFormClassList(wrapper)[3]).toContain('el-col')
expect(getFormClassList(wrapper)[3]).toContain('el-col-xs-24')
expect(getFormClassList(wrapper)[3]).toContain('el-col-md-20')
expect(getFormClassList(wrapper)[3]).toContain('el-col-md-push-2')
expect(getFormClassList(wrapper)[3]).toContain('el-col-md-pull-2')
expect(getFormClassList(wrapper)[3]).toContain('el-col-lg-10')
expect(getFormClassList(wrapper)[3]).toContain('el-col-lg-push-0')
expect(getFormClassList(wrapper)[3]).toContain('el-col-lg-pull-0')
expect(getFormClassList(wrapper)[3]).toContain('el-col-lg-offset-2')
await ((vm.columns[0].span = 8), (vm.columns[0].pull = 2))
expect(getFormClassList(wrapper)[0]).toContain('el-col-8')
expect(getFormClassList(wrapper)[0]).toContain('el-col-pull-2')
})
test('local component', async () => {
const wrapper = await _mount({
template: '<pro-form v-model="form" :columns="columns" />',
setup() {
const form = ref({})
const columns = shallowRef([
{
label: 'switch',
prop: 'switch',
component: ElSwitch,
},
])
return { form, columns }
},
})
const vm = (wrapper.vm as unknown) as { columns: IFormColumns }
expect(getFormList(wrapper)).toHaveLength(1)
expect(getLabelList(wrapper)).toContain('switch')
expect(getComponentList(wrapper)[0]).toContain('el-switch')
})
// test('event', async () => {
// const wrapper = await _mount({
// template: '<pro-form v-model="form" :columns="columns" />',
// setup() {
// const form = ref({})
// return { form, columns }
// },
// })
// await wrapper.find(buttonClass + ':nth-child(2)').trigger('click')
// await wrapper.find(buttonClass).trigger('click')
// expect(wrapper.emitted()).toHaveProperty('reset')
// expect(wrapper.emitted()).toHaveProperty('submit')
// })
}) | the_stack |
/*
* Copyright (c) 2016 - now David Sehnal, licensed under Apache 2.0, See LICENSE file for more info.
*/
namespace LiteMol.Visualization {
export enum CameraType {
Perspective,
Orthographic
}
import LA = Core.Geometry.LinearAlgebra
export class SlabControls {
//private width: number;
private height: number;
private touchSlabOn = false;
private touchStartPosition = { x: 0, y: 0 };
private touchPosition = { x: 0, y: 0 };
private radius: number = 0;
private slabWheelRate = 1 / 15;
private _planeDelta = new LiteMol.Core.Rx.Subject<number>();
private subs: (() => void)[] = [];
private enableWheel = false;
private mouseMoveDelta = 0;
private lastMousePosition: LA.Vector3 | undefined = void 0;
readonly planeDelta: LiteMol.Core.Rx.IObservable<number> = this._planeDelta;
updateSize(w: number, h: number) {/* this.width = w;*/ this.height = h; }
updateRadius(r: number) { this.radius = r; }
destroy() {
for (let s of this.subs) s();
this.subs = [];
this._planeDelta.onCompleted();
}
private handleMouseWheel(event: MouseWheelEvent) {
if (!this.enableWheel) return;
//if (!this.options.enableFrontClip) return;
if (event.stopPropagation) {
event.stopPropagation();
}
if (event.preventDefault) {
event.preventDefault();
}
let delta = 0;
if (event.wheelDelta) { // WebKit / Opera / Explorer 9
delta = event.wheelDelta;
} else if (event.detail) { // Firefox
delta = - event.detail;
}
//if (delta < -0.5) delta = -0.5;
//else if (delta > 0.5) delta = 0.5;
let sign = delta < 0 ? 1 : -1;
delta = this.radius * this.slabWheelRate * sign;
this._planeDelta.onNext(delta);
}
private touchstart(event: TouchEvent) {
switch (event.touches.length) {
case 3: {
this.touchStartPosition.x = 0;
this.touchStartPosition.y = 0;
for (let i = 0; i < 3; i++) {
this.touchStartPosition.x += event.touches[i].clientX / 3;
this.touchStartPosition.y += event.touches[i].clientY / 3;
}
this.touchSlabOn = true;
break;
}
default: this.touchSlabOn = false; break;
}
}
private touchend(event: TouchEvent) {
this.touchSlabOn = false;
}
private touchmove(event: TouchEvent) {
if (!this.touchSlabOn) return;
this.touchPosition.x = 0;
this.touchPosition.y = 0;
for (let i = 0; i < 3; i++) {
this.touchPosition.x += event.touches[i].clientX / 3;
this.touchPosition.y += event.touches[i].clientY / 3;
}
let delta = -5 * this.radius * (this.touchPosition.y - this.touchStartPosition.y) / this.height;
this.touchStartPosition.x = this.touchPosition.x;
this.touchStartPosition.y = this.touchPosition.y;
this._planeDelta.onNext(delta);
}
private mousemove(e: MouseEvent) {
if (!this.lastMousePosition) {
this.lastMousePosition = [e.clientX, e.clientY, 0];
return;
}
const pos = [e.clientX, e.clientY, 0];
this.mouseMoveDelta += LA.Vector3.distance(pos, this.lastMousePosition);
this.lastMousePosition = pos;
if (this.mouseMoveDelta > 15) this.enableWheel = true;
}
private mouseOut() {
this.mouseMoveDelta = 0;
this.lastMousePosition = void 0;
this.enableWheel = false;
}
constructor(element: HTMLElement) {
const events = {
wheel: (e: MouseWheelEvent) => this.handleMouseWheel(e),
touchStart: (e: TouchEvent) => this.touchstart(e),
touchEnd: (e: TouchEvent) => this.touchend(e),
touchMove: (e: TouchEvent) => this.touchmove(e),
mouseMove: (e: MouseEvent) => this.mousemove(e),
mouseOut: () => this.mouseOut()
};
element.addEventListener('mousewheel', events.wheel);
element.addEventListener('DOMMouseScroll', events.wheel); // firefox
element.addEventListener('mousemove', events.mouseMove);
element.addEventListener('mouseout', events.mouseOut);
element.addEventListener('touchstart', events.touchStart, false);
element.addEventListener('touchend', events.touchEnd, false);
element.addEventListener('touchmove', events.touchMove, false);
this.subs.push(() => element.removeEventListener('mousewheel', events.wheel));
this.subs.push(() => element.removeEventListener('mousemove', events.mouseMove));
this.subs.push(() => element.removeEventListener('mouseout', events.mouseOut));
this.subs.push(() => element.removeEventListener('DOMMouseScroll', events.wheel));
this.subs.push(() => element.removeEventListener('touchstart', events.touchStart, false));
this.subs.push(() => element.removeEventListener('touchend', events.touchEnd, false));
this.subs.push(() => element.removeEventListener('touchmove', events.touchMove, false));
}
}
export class Camera {
private camera: THREE.PerspectiveCamera | THREE.OrthographicCamera;
controls: CameraControls;
private slabControls: SlabControls;
fog = new THREE.Fog(0x0, 0, 500);
focusPoint = new THREE.Vector3(0, 0, 0);
focusRadius = 0;
targetDistance = 0;
nearPlaneDistance = 0;
nearPlaneDelta = 0;
fogEnabled = true;
fogDelta = 0;
fogFactor = 1.0;
static shouldInUpdateInclude(m: Model) {
return !isNaN(m.centroid.x) && m.getVisibility();
}
private updateFocus(models: Model[]) {
if (!models.length) return;
let sorted = models
.filter(m => Camera.shouldInUpdateInclude(m))
.sort(function (a, b) { return b.radius - a.radius });
if (!sorted.length) return;
let pivots = [sorted[0]];
let t = new THREE.Vector3();
for (let i = 1; i < sorted.length; i++) {
let a = sorted[i];
let include = true;
for (let p of pivots) {
let d = t.subVectors(a.centroid, p.centroid).length();
if (d < p.radius) {
include = false;
break;
}
}
if (include) {
pivots.push(a);
}
}
let center = this.focusPoint;
center.x = 0;
center.y = 0;
center.z = 0;
for (let p of pivots) {
center.add(p.centroid);
}
center.multiplyScalar(1 / pivots.length);
let radius = 0;
for (let m of sorted) {
radius = Math.max(radius, center.distanceTo(m.centroid) + m.radius);
}
this.focusRadius = radius;
this.slabControls.updateRadius(this.focusRadius);
}
private focus() {
this.controls.reset();
let target = this.focusPoint;
this.camera.position.set(target.x, target.y, target.z + 4 * this.focusRadius);
this.camera.lookAt(target);
this.controls.target.set(target.x, target.y, target.z);
this.cameraUpdated();
}
reset() {
this.nearPlaneDelta = 0;
this.fogDelta = 0;
this.updateFocus(this.scene.models.all);
this.focus();
}
snapshot() {
return this.controls.getState();
}
restore(state: any) {
this.controls.setState(state);
this.scene.forceRender();
}
focusOnModel(...models: Model[]) {
this.updateFocus(models);
this.nearPlaneDelta = 0;
this.fogDelta = 0;
this.controls.panAndMoveToDistance(this.focusPoint, this.focusRadius * 4);
}
focusOnPoint(center: { x: number; y: number; z: number }, radius: number) {
this.focusPoint.x = center.x;
this.focusPoint.y = center.y;
this.focusPoint.z = center.z;
this.focusRadius = Math.max(radius, 1);
this.slabControls.updateRadius(this.focusRadius);
this.nearPlaneDelta = 0;
this.fogDelta = 0;
this.controls.panAndMoveToDistance(this.focusPoint, this.focusRadius * 4);
}
move(target: { x: number; y: number; z: number }) {
this.controls.panTo(target);
}
updateSize(w: number, h: number) {
let camera = this.camera;
if (camera instanceof THREE.PerspectiveCamera) {
camera.aspect = w / h;
}
this.slabControls.updateSize(w, h);
this.camera.updateProjectionMatrix();
//this.controls.handleResize();
}
get position() {
return this.camera.position;
}
get object(): THREE.Camera {
return this.camera;
}
private unbindCamera: any;
dispose() {
if (this.slabControls) {
this.slabControls.destroy();
this.slabControls = <any>void 0;
}
if (this.unbindCamera) {
this.unbindCamera();
this.unbindCamera = void 0;
}
if (this.controls) {
this.controls.destroy();
this.controls = <any>void 0;
}
}
private planeDeltaUpdate(delta: number) {
let dist = this.computeNearDistance();
let near = dist + this.nearPlaneDelta + delta;
if (delta > 0 && near > this.targetDistance) delta = 0;
if (delta < 0 && near < 0.01) delta = 0;
this.nearPlaneDelta += delta;
this.fogDelta += delta;
this.cameraUpdated();
}
computeNearDistance() {
let dist = this.controls.target.distanceTo(this.camera.position);
if (dist > this.focusRadius) return dist - this.focusRadius;
return 0;
}
cameraUpdated() {
let options = this.scene.options;
this.fogEnabled = !!options.enableFog;
let camera = this.camera;
if (camera instanceof THREE.PerspectiveCamera) {
camera.fov = options.cameraFOV as number;
}
this.targetDistance = this.controls.target.distanceTo(this.camera.position);
let near = this.computeNearDistance() + this.nearPlaneDelta;
this.camera.near = Math.max(0.01, Math.min(near, this.targetDistance - 0.5));
if (options.enableFog) {
// if (dist + this.focusRadius - this.fogDelta < 1) {
// this.fogDelta = dist + this.focusRadius - 1;
// }
// let dist = 0;
// let fogNear = dist + this.focusRadius - this.fogDelta - this.camera.near;
// let fogFar = dist + 2 * this.focusRadius - this.fogDelta - this.camera.near;
let fogNear = this.targetDistance - this.camera.near + this.fogFactor * 1 * this.focusRadius - this.nearPlaneDelta;
let fogFar = this.targetDistance - this.camera.near + this.fogFactor * 2 * this.focusRadius - this.nearPlaneDelta;
//console.log(fogNear, fogFar);
this.fog.near = Math.max(fogNear, 0.1);
this.fog.far = Math.max(fogFar, 0.2);
} else {
this.fog.far = 1000001;
this.fog.near = 1000000;
}
this.camera.updateProjectionMatrix();
this.scene.forceRender();
for (let o of this.observers) o.call(null, this);
}
createCamera() {
if (this.scene.options.cameraType === CameraType.Perspective) {
this.camera = new THREE.PerspectiveCamera(
this.scene.options.cameraFOV,
this.scene.parentElement.clientWidth / this.scene.parentElement.clientHeight, 0.1, 1000000);
} else {
let sw = this.scene.parentElement.clientWidth, sh = this.scene.parentElement.clientHeight;
let w = 100, h = sh / sw * w;
this.camera = <any>new THREE.OrthographicCamera(0.5 * w / - 2, 0.5 * w / 2, h / 2, h / - 2, 0.1, 1000000);
}
if (this.controls) {
this.controls.camera = this.camera;
this.reset();
}
}
private setup() {
this.dispose();
this.createCamera();
this.controls = new CameraControls(this.camera, this.domElement, this.scene);
let cc = this.scene.options.clearColor;
this.fog.color.setRGB(cc!.r, cc!.g, cc!.b);
this.scene.scene.fog = this.fog;
let cameraUpdated = () => this.cameraUpdated();
this.slabControls = new SlabControls(this.domElement);
let deltaUpdate = this.slabControls.planeDelta.subscribe(delta => this.planeDeltaUpdate(delta));
this.controls.events.addEventListener('change', cameraUpdated);
this.unbindCamera = () => {
this.controls.events.removeEventListener('change', cameraUpdated);
deltaUpdate.dispose();
this.observers = [];
}
this.reset();
}
private observers: any[] = [];
observe(callback: (c:Camera) => void) {
this.observers.push(callback);
}
stopObserving(callback: (c:Camera) => void) {
this.observers = this.observers.filter(o => o !== callback);
}
constructor(
private scene: Scene,
private domElement: HTMLElement) {
this.setup();
}
}
} | the_stack |
import {
CmsEntry,
CmsEntryStorageOperations,
CmsEntryStorageOperationsCreateParams,
CmsEntryStorageOperationsCreateRevisionFromParams,
CmsEntryStorageOperationsDeleteParams,
CmsEntryStorageOperationsDeleteRevisionParams,
CmsEntryStorageOperationsGetByIdsParams,
CmsEntryStorageOperationsGetLatestByIdsParams,
CmsEntryStorageOperationsGetLatestRevisionParams,
CmsEntryStorageOperationsGetParams,
CmsEntryStorageOperationsGetPreviousRevisionParams,
CmsEntryStorageOperationsGetPublishedByIdsParams,
CmsEntryStorageOperationsGetRevisionParams,
CmsEntryStorageOperationsGetRevisionsParams,
CmsEntryStorageOperationsListParams,
CmsEntryStorageOperationsPublishParams,
CmsEntryStorageOperationsRequestChangesParams,
CmsEntryStorageOperationsRequestReviewParams,
CmsEntryStorageOperationsUnpublishParams,
CmsEntryStorageOperationsUpdateParams,
CmsModel,
CONTENT_ENTRY_STATUS
} from "@webiny/api-headless-cms/types";
import {
createElasticsearchQueryBody,
extractEntriesFromIndex,
prepareEntryToIndex
} from "~/helpers";
import { configurations } from "~/configurations";
import WebinyError from "@webiny/error";
import lodashCloneDeep from "lodash/cloneDeep";
import lodashOmit from "lodash/omit";
import { Entity } from "dynamodb-toolbox";
import { Client } from "@elastic/elasticsearch";
import { PluginsContainer } from "@webiny/plugins";
import { compress, decompress } from "@webiny/api-elasticsearch/compression";
import { batchWriteAll } from "@webiny/db-dynamodb/utils/batchWrite";
import { DataLoadersHandler } from "~/operations/entry/dataLoaders";
import {
createLatestSortKey,
createPartitionKey,
createPublishedSortKey,
createRevisionSortKey
} from "~/operations/entry/keys";
import { queryAll, queryOne, QueryOneParams } from "@webiny/db-dynamodb/utils/query";
import { createLimit } from "@webiny/api-elasticsearch/limit";
import { encodeCursor } from "@webiny/api-elasticsearch/cursors";
import { get as getRecord } from "@webiny/db-dynamodb/utils/get";
import { zeroPad } from "@webiny/utils";
import { cleanupItem } from "@webiny/db-dynamodb/utils/cleanup";
import { ElasticsearchSearchResponse } from "@webiny/api-elasticsearch/types";
const createType = (): string => {
return "cms.entry";
};
export const createLatestType = (): string => {
return `${createType()}.l`;
};
export const createPublishedType = (): string => {
return `${createType()}.p`;
};
const getEntryData = (entry: CmsEntry) => {
return {
...lodashOmit(entry, ["PK", "SK", "published", "latest"]),
TYPE: createType(),
__type: createType()
};
};
const getESLatestEntryData = async (plugins: PluginsContainer, entry: CmsEntry) => {
return compress(plugins, {
...getEntryData(entry),
latest: true,
TYPE: createLatestType(),
__type: createLatestType()
});
};
const getESPublishedEntryData = async (plugins: PluginsContainer, entry: CmsEntry) => {
return compress(plugins, {
...getEntryData(entry),
published: true,
TYPE: createPublishedType(),
__type: createPublishedType()
});
};
interface ElasticsearchDbRecord {
index: string;
data: Record<string, string>;
}
export interface CreateEntriesStorageOperationsParams {
entity: Entity<any>;
esEntity: Entity<any>;
elasticsearch: Client;
plugins: PluginsContainer;
}
export const createEntriesStorageOperations = (
params: CreateEntriesStorageOperationsParams
): CmsEntryStorageOperations => {
const { entity, esEntity, elasticsearch, plugins } = params;
const dataLoaders = new DataLoadersHandler({
entity
});
const create = async (model: CmsModel, params: CmsEntryStorageOperationsCreateParams) => {
const { entry, storageEntry } = params;
const isPublished = entry.status === "published";
const locked = isPublished ? true : entry.locked;
const esEntry = prepareEntryToIndex({
plugins,
model,
entry: lodashCloneDeep({ ...entry, locked }),
storageEntry: lodashCloneDeep({ ...storageEntry, locked })
});
const { index: esIndex } = configurations.es({
model
});
const esLatestData = await getESLatestEntryData(plugins, esEntry);
const esPublishedData = await getESPublishedEntryData(plugins, esEntry);
const revisionKeys = {
PK: createPartitionKey({
id: entry.id,
locale: model.locale,
tenant: model.tenant
}),
SK: createRevisionSortKey(entry)
};
const latestKeys = {
PK: createPartitionKey({
id: entry.id,
locale: model.locale,
tenant: model.tenant
}),
SK: createLatestSortKey()
};
const publishedKeys = {
PK: createPartitionKey({
id: entry.id,
locale: model.locale,
tenant: model.tenant
}),
SK: createPublishedSortKey()
};
const items = [
entity.putBatch({
...storageEntry,
locked,
...revisionKeys,
TYPE: createType()
}),
entity.putBatch({
...storageEntry,
locked,
...latestKeys,
TYPE: createLatestType()
})
];
if (isPublished) {
items.push(
entity.putBatch({
...storageEntry,
locked,
...publishedKeys,
TYPE: createPublishedType()
})
);
}
try {
await batchWriteAll({
table: entity.table,
items
});
dataLoaders.clearAll({
model
});
} catch (ex) {
throw new WebinyError(
ex.message || "Could not insert entry data into the DynamoDB table.",
ex.code || "CREATE_ENTRY_ERROR",
{
error: ex,
entry,
storageEntry
}
);
}
const esItems = [
esEntity.putBatch({
...latestKeys,
index: esIndex,
data: esLatestData
})
];
if (isPublished) {
esItems.push(
esEntity.putBatch({
...publishedKeys,
index: esIndex,
data: esPublishedData
})
);
}
try {
await batchWriteAll({
table: esEntity.table,
items: esItems
});
} catch (ex) {
throw new WebinyError(
ex.message || "Could not insert entry data into the Elasticsearch DynamoDB table.",
ex.code || "CREATE_ES_ENTRY_ERROR",
{
error: ex,
entry,
esEntry
}
);
}
return storageEntry;
};
const createRevisionFrom = async (
model: CmsModel,
params: CmsEntryStorageOperationsCreateRevisionFromParams
) => {
const { entry, storageEntry } = params;
const revisionKeys = {
PK: createPartitionKey({
id: entry.id,
locale: model.locale,
tenant: model.tenant
}),
SK: createRevisionSortKey(entry)
};
const latestKeys = {
PK: createPartitionKey({
id: entry.id,
locale: model.locale,
tenant: model.tenant
}),
SK: createLatestSortKey()
};
const esEntry = prepareEntryToIndex({
plugins,
model,
entry: lodashCloneDeep(entry),
storageEntry: lodashCloneDeep(storageEntry)
});
const esLatestData = await getESLatestEntryData(plugins, esEntry);
const items = [
entity.putBatch({
...storageEntry,
TYPE: createType(),
...revisionKeys
}),
entity.putBatch({
...storageEntry,
TYPE: createLatestType(),
...latestKeys
})
];
const { index } = configurations.es({
model
});
try {
await batchWriteAll({
table: entity.table,
items
});
dataLoaders.clearAll({
model
});
} catch (ex) {
throw new WebinyError(
ex.message || "Could not create revision from given entry in the DynamoDB table.",
ex.code || "CREATE_REVISION_ERROR",
{
error: ex,
entry,
storageEntry
}
);
}
/**
* Update the "latest" entry item in the Elasticsearch
*/
try {
await esEntity.put({
...latestKeys,
index,
data: esLatestData
});
} catch (ex) {
throw new WebinyError(
ex.message || "Could not update latest entry in the DynamoDB Elasticsearch table.",
ex.code || "CREATE_REVISION_ERROR",
{
error: ex,
entry
}
);
}
/**
* There are no modifications on the entry created so just return the data.
*/
return storageEntry;
};
const update = async (model: CmsModel, params: CmsEntryStorageOperationsUpdateParams) => {
const { entry, storageEntry } = params;
const isPublished = entry.status === "published";
const locked = isPublished ? true : entry.locked;
const revisionKeys = {
PK: createPartitionKey({
id: entry.id,
locale: model.locale,
tenant: model.tenant
}),
SK: createRevisionSortKey(entry)
};
const latestKeys = {
PK: createPartitionKey({
id: entry.id,
locale: model.locale,
tenant: model.tenant
}),
SK: createLatestSortKey()
};
const publishedKeys = {
PK: createPartitionKey({
id: entry.id,
locale: model.locale,
tenant: model.tenant
}),
SK: createPublishedSortKey()
};
/**
* We need the latest entry to check if it needs to be updated.
*/
const [latestStorageEntry] = await dataLoaders.getLatestRevisionByEntryId({
model,
ids: [entry.id]
});
const [publishedStorageEntry] = await dataLoaders.getPublishedRevisionByEntryId({
model,
ids: [entry.id]
});
const items = [
entity.putBatch({
...storageEntry,
locked,
...revisionKeys,
TYPE: createType()
})
];
if (isPublished) {
items.push(
entity.putBatch({
...storageEntry,
locked,
...publishedKeys,
TYPE: createPublishedType()
})
);
}
const esItems = [];
const { index: esIndex } = configurations.es({
model
});
/**
* If the latest entry is the one being updated, we need to create a new latest entry records.
*/
let elasticsearchLatestData: any = null;
if (latestStorageEntry && latestStorageEntry.id === entry.id) {
/**
* First we update the regular DynamoDB table
*/
items.push(
entity.putBatch({
...storageEntry,
...latestKeys,
TYPE: createLatestSortKey()
})
);
/**
* And then update the Elasticsearch table to propagate changes to the Elasticsearch
*/
const esEntry = prepareEntryToIndex({
plugins,
model,
entry: lodashCloneDeep({
...entry,
locked
}),
storageEntry: lodashCloneDeep({
...storageEntry,
locked
})
});
elasticsearchLatestData = await getESLatestEntryData(plugins, esEntry);
esItems.push(
esEntity.putBatch({
...latestKeys,
index: esIndex,
data: elasticsearchLatestData
})
);
}
let elasticsearchPublishedData = null;
if (isPublished && publishedStorageEntry && publishedStorageEntry.id === entry.id) {
if (!elasticsearchLatestData) {
/**
* And then update the Elasticsearch table to propagate changes to the Elasticsearch
*/
const esEntry = prepareEntryToIndex({
plugins,
model,
entry: lodashCloneDeep({
...entry,
locked
}),
storageEntry: lodashCloneDeep({
...storageEntry,
locked
})
});
elasticsearchPublishedData = await getESPublishedEntryData(plugins, esEntry);
} else {
elasticsearchPublishedData = {
...elasticsearchLatestData,
published: true,
TYPE: createPublishedType(),
__type: createPublishedType()
};
delete elasticsearchPublishedData.latest;
}
esItems.push(
esEntity.putBatch({
...publishedKeys,
index: esIndex,
data: elasticsearchPublishedData
})
);
}
try {
await batchWriteAll({
table: entity.table,
items
});
dataLoaders.clearAll({
model
});
} catch (ex) {
throw new WebinyError(
ex.message || "Could not update entry DynamoDB records.",
ex.code || "UPDATE_ENTRY_ERROR",
{
error: ex,
entry,
storageEntry
}
);
}
if (esItems.length === 0) {
return storageEntry;
}
try {
await batchWriteAll({
table: esEntity.table,
items: esItems
});
} catch (ex) {
throw new WebinyError(
ex.message || "Could not update entry DynamoDB Elasticsearch records.",
ex.code || "UPDATE_ES_ENTRY_ERROR",
{
error: ex,
entry
}
);
}
return storageEntry;
};
const deleteEntry = async (model: CmsModel, params: CmsEntryStorageOperationsDeleteParams) => {
const { entry } = params;
const partitionKey = createPartitionKey({
id: entry.id,
locale: model.locale,
tenant: model.tenant
});
const items = await queryAll<CmsEntry>({
entity,
partitionKey,
options: {
gte: " "
}
});
const esItems = await queryAll<CmsEntry>({
entity: esEntity,
partitionKey,
options: {
gte: " "
}
});
const deleteItems = items.map(item => {
return entity.deleteBatch({
PK: item.PK,
SK: item.SK
});
});
const deleteEsItems = esItems.map(item => {
return esEntity.deleteBatch({
PK: item.PK,
SK: item.SK
});
});
try {
await batchWriteAll({
table: entity.table,
items: deleteItems
});
dataLoaders.clearAll({
model
});
} catch (ex) {
throw new WebinyError(
ex.message || "Could not delete entry records from DynamoDB table.",
ex.code || "DELETE_ENTRY_ERROR",
{
error: ex,
entry
}
);
}
try {
await batchWriteAll({
table: esEntity.table,
items: deleteEsItems
});
} catch (ex) {
throw new WebinyError(
ex.message || "Could not delete entry records from DynamoDB Elasticsearch table.",
ex.code || "DELETE_ENTRY_ERROR",
{
error: ex,
entry
}
);
}
};
const deleteRevision = async (
model: CmsModel,
params: CmsEntryStorageOperationsDeleteRevisionParams
) => {
const { entry, latestEntry, latestStorageEntry } = params;
const partitionKey = createPartitionKey({
id: entry.id,
locale: model.locale,
tenant: model.tenant
});
const { index } = configurations.es({
model
});
/**
* We need published entry to delete it if necessary.
*/
const [publishedStorageEntry] = await dataLoaders.getPublishedRevisionByEntryId({
model,
ids: [entry.id]
});
/**
* We need to delete all existing records of the given entry revision.
*/
const items = [
/**
* Delete records of given entry revision.
*/
entity.deleteBatch({
PK: partitionKey,
SK: createRevisionSortKey(entry)
})
];
const esItems = [];
/**
* If revision we are deleting is the published one as well, we need to delete those records as well.
*/
if (publishedStorageEntry && entry.id === publishedStorageEntry.id) {
items.push(
entity.deleteBatch({
PK: partitionKey,
SK: createPublishedSortKey()
})
);
esItems.push(
entity.deleteBatch({
PK: partitionKey,
SK: createPublishedSortKey()
})
);
}
if (latestEntry && latestStorageEntry) {
const esEntry = prepareEntryToIndex({
plugins,
model,
entry: lodashCloneDeep(latestEntry),
storageEntry: lodashCloneDeep(latestStorageEntry)
});
const esLatestData = await getESLatestEntryData(plugins, esEntry);
/**
* In the end we need to set the new latest entry
*/
items.push(
entity.putBatch({
...latestStorageEntry,
PK: partitionKey,
SK: createLatestSortKey(),
TYPE: createLatestType()
})
);
esItems.push(
esEntity.putBatch({
PK: partitionKey,
SK: createLatestSortKey(),
index,
data: esLatestData
})
);
}
try {
await batchWriteAll({
table: entity.table,
items
});
dataLoaders.clearAll({
model
});
} catch (ex) {
throw new WebinyError(
ex.message || "Could not batch write entry records to DynamoDB table.",
ex.code || "DELETE_REVISION_ERROR",
{
error: ex,
entry,
latestEntry,
latestStorageEntry
}
);
}
if (esItems.length === 0) {
return;
}
try {
await batchWriteAll({
table: esEntity.table,
items: esItems
});
} catch (ex) {
throw new WebinyError(
ex.message ||
"Could not batch write entry records to DynamoDB Elasticsearch table.",
ex.code || "DELETE_REVISION_ERROR",
{
error: ex,
entry,
latestEntry,
latestStorageEntry
}
);
}
};
const list = async (model: CmsModel, params: CmsEntryStorageOperationsListParams) => {
const limit = createLimit(params.limit, 50);
const { index } = configurations.es({
model
});
try {
const result = await elasticsearch.indices.exists({
index
});
if (!result || !result.body) {
return {
hasMoreItems: false,
totalCount: 0,
cursor: null,
items: []
};
}
} catch (ex) {
throw new WebinyError(
"Could not determine if Elasticsearch index exists.",
"ELASTICSEARCH_INDEX_CHECK_ERROR",
{
error: ex,
index
}
);
}
const body = createElasticsearchQueryBody({
model,
args: {
...params,
limit
},
plugins,
parentPath: "values"
});
let response: ElasticsearchSearchResponse;
try {
response = await elasticsearch.search({
index,
body
});
} catch (ex) {
throw new WebinyError(ex.message, ex.code || "ELASTICSEARCH_ERROR", {
error: ex,
index,
body
});
}
const { hits, total } = response.body.hits;
const items = extractEntriesFromIndex({
plugins,
model,
entries: hits.map(item => item._source)
});
const hasMoreItems = items.length > limit;
if (hasMoreItems) {
/**
* Remove the last item from results, we don't want to include it.
*/
items.pop();
}
/**
* Cursor is the `sort` value of the last item in the array.
* https://www.elastic.co/guide/en/elasticsearch/reference/current/paginate-search-results.html#search-after
*/
const cursor = items.length > 0 ? encodeCursor(hits[items.length - 1].sort) || null : null;
return {
hasMoreItems,
totalCount: total.value,
cursor,
items
};
};
const get = async (model: CmsModel, params: CmsEntryStorageOperationsGetParams) => {
const { items } = await list(model, {
...params,
limit: 1
});
return items.shift() || null;
};
const publish = async (model: CmsModel, params: CmsEntryStorageOperationsPublishParams) => {
const { entry, storageEntry } = params;
/**
* We need currently published entry to check if need to remove it.
*/
const [publishedStorageEntry] = await dataLoaders.getPublishedRevisionByEntryId({
model,
ids: [entry.id]
});
const revisionKeys = {
PK: createPartitionKey({
id: entry.id,
locale: model.locale,
tenant: model.tenant
}),
SK: createRevisionSortKey(entry)
};
const latestKeys = {
PK: createPartitionKey({
id: entry.id,
locale: model.locale,
tenant: model.tenant
}),
SK: createLatestSortKey()
};
const publishedKeys = {
PK: createPartitionKey({
id: entry.id,
locale: model.locale,
tenant: model.tenant
}),
SK: createPublishedSortKey()
};
let latestEsEntry: ElasticsearchDbRecord | null = null;
try {
latestEsEntry = await getRecord<ElasticsearchDbRecord>({
entity: esEntity,
keys: latestKeys
});
} catch (ex) {
throw new WebinyError(
ex.message || "Could not read Elasticsearch latest or published data.",
ex.code || "PUBLISH_BATCH_READ",
{
error: ex,
latestKeys: latestKeys,
publishedKeys: publishedKeys
}
);
}
const items = [
entity.putBatch({
...storageEntry,
...revisionKeys,
TYPE: createType()
})
];
const esItems = [];
const { index } = configurations.es({
model
});
if (publishedStorageEntry && publishedStorageEntry.id !== entry.id) {
/**
* If there is a `published` entry already, we need to set it to `unpublished`. We need to
* execute two updates: update the previously published entry's status and the published entry record.
* DynamoDB does not support `batchUpdate` - so here we load the previously published
* entry's data to update its status within a batch operation. If, hopefully,
* they introduce a true update batch operation, remove this `read` call.
*/
const [previouslyPublishedEntry] = await dataLoaders.getRevisionById({
model,
ids: [publishedStorageEntry.id]
});
items.push(
/**
* Update currently published entry (unpublish it)
*/
entity.putBatch({
...previouslyPublishedEntry,
status: CONTENT_ENTRY_STATUS.UNPUBLISHED,
savedOn: entry.savedOn,
TYPE: createType(),
PK: createPartitionKey(publishedStorageEntry),
SK: createRevisionSortKey(publishedStorageEntry)
})
);
}
/**
* Update the helper item in DB with the new published entry
*/
items.push(
entity.putBatch({
...storageEntry,
...publishedKeys,
TYPE: createPublishedType()
})
);
/**
* We need the latest entry to check if it needs to be updated as well in the Elasticsearch.
*/
const [latestStorageEntry] = await dataLoaders.getLatestRevisionByEntryId({
model,
ids: [entry.id]
});
if (latestStorageEntry && latestStorageEntry.id === entry.id) {
items.push(
entity.putBatch({
...storageEntry,
...latestKeys
})
);
}
/**
* If we are publishing the latest revision, let's also update the latest revision's status in ES.
*/
if (latestEsEntry && latestStorageEntry && latestStorageEntry.id === entry.id) {
/**
* Need to decompress the data from Elasticsearch DynamoDB table.
*/
const latestEsEntryDataDecompressed: CmsEntry = (await decompress(
plugins,
latestEsEntry.data
)) as any;
esItems.push(
esEntity.putBatch({
index,
PK: createPartitionKey(latestEsEntryDataDecompressed),
SK: createLatestSortKey(),
data: {
...latestEsEntryDataDecompressed,
status: CONTENT_ENTRY_STATUS.PUBLISHED,
locked: true,
savedOn: entry.savedOn,
publishedOn: entry.publishedOn
}
})
);
}
const preparedEntryData = prepareEntryToIndex({
plugins,
model,
entry: lodashCloneDeep(entry),
storageEntry: lodashCloneDeep(storageEntry)
});
/**
* Update the published revision entry in ES.
*/
const esLatestData = await getESPublishedEntryData(plugins, preparedEntryData);
esItems.push(
esEntity.putBatch({
...publishedKeys,
index,
data: esLatestData
})
);
/**
* Finally, execute regular table batch.
*/
try {
await batchWriteAll({
table: entity.table,
items
});
dataLoaders.clearAll({
model
});
} catch (ex) {
throw new WebinyError(
ex.message || "Could not store publish entry records in DynamoDB table.",
ex.code || "PUBLISH_ERROR",
{
error: ex,
entry,
latestStorageEntry,
publishedStorageEntry
}
);
}
/**
* And Elasticsearch table batch.
*/
try {
await batchWriteAll({
table: esEntity.table,
items: esItems
});
} catch (ex) {
throw new WebinyError(
ex.message ||
"Could not store publish entry records in DynamoDB Elasticsearch table.",
ex.code || "PUBLISH_ES_ERROR",
{
error: ex,
entry,
latestStorageEntry,
publishedStorageEntry
}
);
}
return storageEntry;
};
const unpublish = async (model: CmsModel, params: CmsEntryStorageOperationsUnpublishParams) => {
const { entry, storageEntry } = params;
/**
* We need the latest entry to check if it needs to be updated.
*/
const [latestStorageEntry] = await dataLoaders.getLatestRevisionByEntryId({
model,
ids: [entry.id]
});
const partitionKey = createPartitionKey({
id: entry.id,
locale: model.locale,
tenant: model.tenant
});
const items = [
entity.deleteBatch({
PK: partitionKey,
SK: createPublishedSortKey()
}),
entity.putBatch({
...storageEntry,
PK: partitionKey,
SK: createRevisionSortKey(entry),
TYPE: createType()
})
];
const esItems = [
esEntity.deleteBatch({
PK: partitionKey,
SK: createPublishedSortKey()
})
];
/**
* If we are unpublishing the latest revision, let's also update the latest revision entry's status in ES.
*/
if (latestStorageEntry.id === entry.id) {
const { index } = configurations.es({
model
});
const preparedEntryData = prepareEntryToIndex({
plugins,
model,
entry: lodashCloneDeep(entry),
storageEntry: lodashCloneDeep(storageEntry)
});
const esLatestData = await getESLatestEntryData(plugins, preparedEntryData);
esItems.push(
esEntity.putBatch({
PK: partitionKey,
SK: createLatestSortKey(),
index,
data: esLatestData
})
);
}
/**
* Finally, execute regular table batch.
*/
try {
await batchWriteAll({
table: entity.table,
items
});
dataLoaders.clearAll({
model
});
} catch (ex) {
throw new WebinyError(
ex.message || "Could not store unpublished entry records in DynamoDB table.",
ex.code || "UNPUBLISH_ERROR",
{
entry,
storageEntry
}
);
}
/**
* And Elasticsearch table batch.
*/
try {
await batchWriteAll({
table: esEntity.table,
items: esItems
});
} catch (ex) {
throw new WebinyError(
ex.message ||
"Could not store unpublished entry records in DynamoDB Elasticsearch table.",
ex.code || "UNPUBLISH_ERROR",
{
entry,
storageEntry
}
);
}
return storageEntry;
};
const requestReview = async (
model: CmsModel,
params: CmsEntryStorageOperationsRequestReviewParams
) => {
const { entry, storageEntry } = params;
/**
* We need the latest entry to check if it needs to be updated.
*/
const [latestStorageEntry] = await dataLoaders.getLatestRevisionByEntryId({
model,
ids: [entry.id]
});
const partitionKey = createPartitionKey({
id: entry.id,
locale: model.locale,
tenant: model.tenant
});
/**
* If we updated the latest version, then make sure the changes are propagated to ES too.
*/
let esLatestData = null;
const { index } = configurations.es({
model
});
if (latestStorageEntry && latestStorageEntry.id === entry.id) {
const preparedEntryData = prepareEntryToIndex({
plugins,
model,
entry: lodashCloneDeep(entry),
storageEntry: lodashCloneDeep(storageEntry)
});
esLatestData = await getESLatestEntryData(plugins, preparedEntryData);
}
try {
await entity.put({
...storageEntry,
PK: partitionKey,
SK: createRevisionSortKey(entry),
TYPE: createType()
});
dataLoaders.clearAll({
model
});
} catch (ex) {
throw new WebinyError(
ex.message || "Could not store request review entry record into DynamoDB table.",
ex.code || "REQUEST_REVIEW_ERROR",
{
entry,
storageEntry,
latestStorageEntry
}
);
}
/**
* No need to proceed further if nothing to put into Elasticsearch.
*/
if (!esLatestData) {
return storageEntry;
}
try {
await esEntity.put({
PK: partitionKey,
SK: createLatestSortKey(),
index,
data: esLatestData
});
} catch (ex) {
throw new WebinyError(
ex.message ||
"Could not store request review entry record into DynamoDB Elasticsearch table.",
ex.code || "REQUEST_REVIEW_ERROR",
{
entry,
storageEntry,
latestStorageEntry
}
);
}
return storageEntry;
};
const requestChanges = async (
model: CmsModel,
params: CmsEntryStorageOperationsRequestChangesParams
) => {
const { entry, storageEntry } = params;
/**
* We need the latest entry to check if it needs to be updated.
*/
const [latestStorageEntry] = await dataLoaders.getLatestRevisionByEntryId({
model,
ids: [entry.id]
});
const partitionKey = createPartitionKey({
id: entry.id,
locale: model.locale,
tenant: model.tenant
});
const items = [
entity.putBatch({
...storageEntry,
PK: partitionKey,
SK: createRevisionSortKey(entry),
TYPE: createType()
})
];
/**
* If we updated the latest version, then make sure the changes are propagated to ES too.
*/
const { index } = configurations.es({
model
});
let esLatestData = null;
if (latestStorageEntry && latestStorageEntry.id === entry.id) {
items.push(
entity.putBatch({
...storageEntry,
PK: partitionKey,
SK: createLatestSortKey(),
TYPE: createLatestType()
})
);
const preparedEntryData = prepareEntryToIndex({
plugins,
model,
entry: lodashCloneDeep(entry),
storageEntry: lodashCloneDeep(storageEntry)
});
esLatestData = await getESLatestEntryData(plugins, preparedEntryData);
}
try {
await batchWriteAll({
table: entity.table,
items
});
dataLoaders.clearAll({
model
});
} catch (ex) {
throw new WebinyError(
ex.message || "Could not store request changes entry record into DynamoDB table.",
ex.code || "REQUEST_CHANGES_ERROR",
{
entry,
latestStorageEntry
}
);
}
/**
* No need to proceed further if nothing to put into Elasticsearch.
*/
if (!esLatestData) {
return storageEntry;
}
try {
await esEntity.put({
PK: partitionKey,
SK: createLatestSortKey(),
index,
data: esLatestData
});
} catch (ex) {
throw new WebinyError(
ex.message ||
"Could not store request changes entry record into DynamoDB Elasticsearch table.",
ex.code || "REQUEST_CHANGES_ERROR",
{
entry,
latestStorageEntry
}
);
}
return storageEntry;
};
const getLatestRevisionByEntryId = async (
model: CmsModel,
params: CmsEntryStorageOperationsGetLatestRevisionParams
) => {
const result = await dataLoaders.getLatestRevisionByEntryId({
model,
ids: [params.id]
});
return result.shift() || null;
};
const getPublishedRevisionByEntryId = async (
model: CmsModel,
params: CmsEntryStorageOperationsGetLatestRevisionParams
) => {
const result = await dataLoaders.getPublishedRevisionByEntryId({
model,
ids: [params.id]
});
return result.shift() || null;
};
const getRevisionById = async (
model: CmsModel,
params: CmsEntryStorageOperationsGetRevisionParams
) => {
const result = await dataLoaders.getRevisionById({
model,
ids: [params.id]
});
return result.shift() || null;
};
const getRevisions = async (
model: CmsModel,
params: CmsEntryStorageOperationsGetRevisionsParams
) => {
return await dataLoaders.getAllEntryRevisions({
model,
ids: [params.id]
});
};
const getByIds = async (model: CmsModel, params: CmsEntryStorageOperationsGetByIdsParams) => {
return dataLoaders.getRevisionById({
model,
ids: params.ids
});
};
const getLatestByIds = async (
model: CmsModel,
params: CmsEntryStorageOperationsGetLatestByIdsParams
) => {
return dataLoaders.getLatestRevisionByEntryId({
model,
ids: params.ids
});
};
const getPublishedByIds = async (
model: CmsModel,
params: CmsEntryStorageOperationsGetPublishedByIdsParams
) => {
return dataLoaders.getPublishedRevisionByEntryId({
model,
ids: params.ids
});
};
const getPreviousRevision = async (
model: CmsModel,
params: CmsEntryStorageOperationsGetPreviousRevisionParams
) => {
const { tenant, locale } = model;
const { entryId, version } = params;
const queryParams: QueryOneParams = {
entity,
partitionKey: createPartitionKey({
tenant,
locale,
id: entryId
}),
options: {
lt: `REV#${zeroPad(version)}`,
/**
* We need to have extra checks because DynamoDB will return published or latest record if there is no REV# record.
*/
filters: [
{
attr: "TYPE",
eq: createType()
},
{
attr: "version",
lt: version
}
],
reverse: true
}
};
try {
const result = await queryOne<CmsEntry>(queryParams);
return cleanupItem(entity, result);
} catch (ex) {
throw new WebinyError(
ex.message || "Could not get previous version of given entry.",
ex.code || "GET_PREVIOUS_VERSION_ERROR",
{
...params,
error: ex,
partitionKey: queryParams.partitionKey,
options: queryParams.options,
model
}
);
}
};
return {
create,
createRevisionFrom,
update,
delete: deleteEntry,
deleteRevision,
get,
publish,
unpublish,
requestReview,
requestChanges,
list,
getLatestRevisionByEntryId,
getPublishedRevisionByEntryId,
getRevisionById,
getRevisions,
getByIds,
getLatestByIds,
getPublishedByIds,
getPreviousRevision
};
}; | the_stack |
import * as assert from "assert";
import * as Azure from "azure-storage";
import { configLogger } from "../../../src/common/Logger";
import TableServer from "../../../src/table/TableServer";
import {
HeaderConstants,
TABLE_API_VERSION
} from "../../../src/table/utils/constants";
import {
EMULATOR_ACCOUNT_NAME,
getUniqueName,
overrideRequest,
restoreBuildRequestOptions
} from "../../testutils";
import {
HOST,
PROTOCOL,
PORT,
createConnectionStringForTest,
createTableServerForTest
} from "./table.entity.test.utils";
// Set true to enable debug log
configLogger(false);
// For convenience, we have a switch to control the use
// of a local Azurite instance, otherwise we need an
// ENV VAR called AZURE_TABLE_STORAGE added to mocha
// script or launch.json containing
// Azure Storage Connection String (using SAS or Key).
const testLocalAzuriteInstance = true;
describe("table APIs test", () => {
let server: TableServer;
const tableService = Azure.createTableService(
createConnectionStringForTest(testLocalAzuriteInstance)
);
tableService.enableGlobalHttpAgent = true;
let tableName: string = getUniqueName("table");
const requestOverride = { headers: {} };
before(async () => {
overrideRequest(requestOverride, tableService);
server = createTableServerForTest();
tableName = getUniqueName("table");
await server.start();
});
after(async () => {
restoreBuildRequestOptions(tableService);
tableService.removeAllListeners();
await server.close();
});
it("createTable, prefer=return-no-content, accept=application/json;odata=minimalmetadata @loki", (done) => {
/* Azure Storage Table SDK doesn't support customize Accept header and Prefer header,
thus we workaround this by override request headers to test following 3 OData levels responses.
- application/json;odata=nometadata
- application/json;odata=minimalmetadata
- application/json;odata=fullmetadata
*/
requestOverride.headers = {
Prefer: "return-no-content",
accept: "application/json;odata=minimalmetadata"
};
tableService.createTable(tableName, (error, result, response) => {
if (!error) {
assert.strictEqual(result.TableName, tableName);
assert.strictEqual(result.statusCode, 204);
const headers = response.headers!;
assert.strictEqual(headers["x-ms-version"], TABLE_API_VERSION);
assert.deepStrictEqual(response.body, "");
}
done();
});
});
it("createTable, prefer=return-content, accept=application/json;odata=fullmetadata @loki", (done) => {
/* Azure Storage Table SDK doesn't support customize Accept header and Prefer header,
thus we workaround this by override request headers to test following 3 OData levels responses.
- application/json;odata=nometadata
- application/json;odata=minimalmetadata
- application/json;odata=fullmetadata
*/
requestOverride.headers = {
Prefer: "return-content",
accept: "application/json;odata=fullmetadata"
};
tableService.createTable(tableName, (error, result, response) => {
if (!error) {
assert.strictEqual(result.TableName, tableName);
assert.strictEqual(result.statusCode, 201);
const headers = response.headers!;
assert.strictEqual(headers["x-ms-version"], TABLE_API_VERSION);
const bodies = response.body! as any;
assert.deepStrictEqual(bodies.TableName, tableName);
assert.deepStrictEqual(
bodies["odata.type"],
`${EMULATOR_ACCOUNT_NAME}.Tables`
);
assert.deepStrictEqual(
bodies["odata.metadata"],
`${PROTOCOL}://${HOST}:${PORT}/${EMULATOR_ACCOUNT_NAME}/$metadata#Tables/@Element`
);
assert.deepStrictEqual(
bodies["odata.id"],
`${PROTOCOL}://${HOST}:${PORT}/${EMULATOR_ACCOUNT_NAME}/Tables(${tableName})`
);
assert.deepStrictEqual(
bodies["odata.editLink"],
`Tables(${tableName})`
);
}
done();
});
});
it("createTable, prefer=return-content, accept=application/json;odata=minimalmetadata @loki", (done) => {
// TODO
done();
});
it("createTable, prefer=return-content, accept=application/json;odata=nometadata @loki", (done) => {
// TODO
done();
});
it("queryTable, accept=application/json;odata=fullmetadata @loki", (done) => {
/* Azure Storage Table SDK doesn't support customize Accept header and Prefer header,
thus we workaround this by override request headers to test following 3 OData levels responses.
- application/json;odata=nometadata
- application/json;odata=minimalmetadata
- application/json;odata=fullmetadata
*/
requestOverride.headers = {
accept: "application/json;odata=fullmetadata"
};
tableService.listTablesSegmented(
null as any,
{ maxResults: 20 },
(error, result, response) => {
assert.deepStrictEqual(error, null);
assert.strictEqual(response.statusCode, 200);
const headers = response.headers!;
assert.strictEqual(headers["x-ms-version"], TABLE_API_VERSION);
const bodies = response.body! as any;
assert.deepStrictEqual(
bodies["odata.metadata"],
`${PROTOCOL}://${HOST}:${PORT}/${EMULATOR_ACCOUNT_NAME}/$metadata#Tables`
);
assert.ok(bodies.value[0].TableName);
assert.ok(bodies.value[0]["odata.type"]);
assert.ok(bodies.value[0]["odata.id"]);
assert.ok(bodies.value[0]["odata.editLink"]);
done();
}
);
});
it("queryTable, accept=application/json;odata=minimalmetadata @loki", (done) => {
/* Azure Storage Table SDK doesn't support customize Accept header and Prefer header,
thus we workaround this by override request headers to test following 3 OData levels responses.
- application/json;odata=nometadata
- application/json;odata=minimalmetadata
- application/json;odata=fullmetadata
*/
requestOverride.headers = {
accept: "application/json;odata=minimalmetadata"
};
tableService.listTablesSegmented(null as any, (error, result, response) => {
if (!error) {
assert.strictEqual(response.statusCode, 200);
const headers = response.headers!;
assert.strictEqual(headers["x-ms-version"], TABLE_API_VERSION);
const bodies = response.body! as any;
assert.deepStrictEqual(
bodies["odata.metadata"],
`${PROTOCOL}://${HOST}:${PORT}/${EMULATOR_ACCOUNT_NAME}/$metadata#Tables`
);
assert.ok(bodies.value[0].TableName);
}
done();
});
});
it("queryTable, accept=application/json;odata=nometadata @loki", (done) => {
/* Azure Storage Table SDK doesn't support customize Accept header and Prefer header,
thus we workaround this by override request headers to test following 3 OData levels responses.
- application/json;odata=nometadata
- application/json;odata=minimalmetadata
- application/json;odata=fullmetadata
*/
requestOverride.headers = {
accept: "application/json;odata=nometadata"
};
tableService.listTablesSegmented(null as any, (error, result, response) => {
if (!error) {
assert.strictEqual(response.statusCode, 200);
const headers = response.headers!;
assert.strictEqual(headers["x-ms-version"], TABLE_API_VERSION);
const bodies = response.body! as any;
assert.ok(bodies.value[0].TableName);
}
done();
});
});
it("deleteTable that exists, @loki", (done) => {
/*
https://docs.microsoft.com/en-us/rest/api/storageservices/delete-table
*/
requestOverride.headers = {};
const tableToDelete = getUniqueName("table") + "del";
tableService.createTable(tableToDelete, (error, result, response) => {
if (!error) {
tableService.deleteTable(tableToDelete, (deleteError, deleteResult) => {
if (!deleteError) {
// no body expected, we expect 204 no content on successful deletion
assert.strictEqual(deleteResult.statusCode, 204);
} else {
assert.ifError(deleteError);
}
done();
});
} else {
assert.fail("Test failed to create the table");
done();
}
});
});
it("deleteTable that does not exist, @loki", (done) => {
// https://docs.microsoft.com/en-us/rest/api/storageservices/delete-table
requestOverride.headers = {};
const tableToDelete = tableName + "causeerror";
tableService.deleteTable(tableToDelete, (error, result) => {
assert.strictEqual(result.statusCode, 404); // no body expected, we expect 404
const storageError = error as any;
assert.strictEqual(storageError.code, "ResourceNotFound");
done();
});
});
it("createTable with invalid version, @loki", (done) => {
requestOverride.headers = { [HeaderConstants.X_MS_VERSION]: "invalid" };
tableService.createTable("test", (error, result) => {
assert.strictEqual(result.statusCode, 400);
done();
});
});
it("Should have a valid OData Metadata value when inserting a table, @loki", (done) => {
requestOverride.headers = {
Prefer: "return-content",
accept: "application/json;odata=fullmetadata"
};
const newTableName: string = getUniqueName("table");
tableService.createTable(newTableName, (error, result, response) => {
if (
!error &&
result !== undefined &&
response !== undefined &&
response.body !== undefined
) {
const body = response.body as object;
const meta: string = body["odata.metadata" as keyof object];
// service response for this operation ends with /@Element
assert.strictEqual(meta.endsWith("/@Element"), true);
done();
} else {
assert.ifError(error);
done();
}
});
});
it("SetAccessPolicy should work @loki", (done) => {
const tableAcl = {
"MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=": {
Permissions: "raud",
Expiry: new Date("2018-12-31T11:22:33.4567890Z"),
Start: new Date("2017-12-31T11:22:33.4567890Z")
},
"policy2": {
Permissions: "a",
Expiry: new Date("2030-11-31T11:22:33.4567890Z"),
Start: new Date("2017-12-31T11:22:33.4567890Z")
}
};
tableService.createTable(tableName + "setACL", (error) => {
if (error) {
assert.ifError(error);
}
// a random id used to test whether response returns the client id sent in request
const setClientRequestId = "b86e2b01-a7b5-4df2-b190-205a0c24bd36";
// tslint:disable-next-line: no-shadowed-variable
tableService.setTableAcl(tableName + "setACL", tableAcl, {clientRequestId: setClientRequestId}, (error, result, response) => {
if (error) {
assert.ifError(error);
}
if (response.headers) {
assert.strictEqual(
response.headers["x-ms-client-request-id"],
setClientRequestId
);
}
// tslint:disable-next-line: no-shadowed-variable
tableService.getTableAcl(tableName + "setACL", {clientRequestId: setClientRequestId}, (error, result, response) => {
if (error) {
assert.ifError(error);
}
if (response.headers) {
assert.strictEqual(
response.headers["x-ms-client-request-id"],
setClientRequestId
);
}
assert.deepStrictEqual(result.signedIdentifiers, tableAcl);
done();
});
});
});
});
it("setAccessPolicy negative @loki", (done) => {
const tableAcl = {
"MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=": {
Permissions: "rwdl",
Expiry: new Date("2018-12-31T11:22:33.4567890Z"),
Start: new Date("2017-12-31T11:22:33.4567890Z")
},
"policy2": {
Permissions: "a",
Expiry: new Date("2030-11-31T11:22:33.4567890Z"),
Start: new Date("2017-12-31T11:22:33.4567890Z")
}
};
tableService.createTable(tableName + "setACLNeg", (error) => {
if (error) {
assert.ifError(error);
}
// tslint:disable-next-line: no-shadowed-variable
tableService.setTableAcl(tableName + "setACLNeg", tableAcl, (error) => {
assert.ok(error);
done();
});
});
});
}); | the_stack |
import { LokiEventEmitter } from "./event_emitter";
import { Collection } from "./collection";
import { Doc, StorageAdapter } from "../../common/types";
import { IComparatorMap } from "./comparators";
import { IRangedIndexFactoryMap } from "./ranged_indexes";
import { ILokiOperatorPackageMap } from "./operator_packages";
export declare class Loki extends LokiEventEmitter {
filename: string;
private databaseVersion;
private engineVersion;
_collections: Collection[];
private _env;
private _serializationMethod;
private _destructureDelimiter;
private _persistenceMethod;
private _persistenceAdapter;
private _throttledSaves;
private _throttledSaveRunning;
private _throttledSavePending;
private _autosave;
private _autosaveInterval;
private _autosaveRunning;
private _autosaveHandler;
/**
* Constructs the main database class.
* @param {string} filename - name of the file to be saved to
* @param {object} [options={}] - options
* @param {Loki.Environment} [options.env] - the javascript environment
* @param {Loki.SerializationMethod} [options.serializationMethod=NORMAL] - the serialization method
* @param {string} [options.destructureDelimiter="$<\n"] - string delimiter used for destructured serialization
* @param {IComparatorMap} [options.comparatorMap] allows injecting or overriding registered comparators
* @param {IRangedIndexFactoryMap} [options.rangedIndexFactoryMap] allows injecting or overriding registered ranged index factories
* @param {ILokiOperatorPackageMap} [options.lokiOperatorPackageMap] allows injecting or overriding registered loki operator packages
*/
constructor(filename?: string, options?: Loki.Options);
/**
* configures options related to database persistence.
*
* @param {Loki.PersistenceOptions} [options={}] - options
* @param {adapter} [options.adapter=auto] - an instance of a loki persistence adapter
* @param {boolean} [options.autosave=false] - enables autosave
* @param {int} [options.autosaveInterval=5000] - time interval (in milliseconds) between saves (if dirty)
* @param {boolean} [options.autoload=false] - enables autoload on loki instantiation
* @param {object} options.inflate - options that are passed to loadDatabase if autoload enabled
* @param {boolean} [options.throttledSaves=true] - if true, it batches multiple calls to to saveDatabase reducing number of
* disk I/O operations and guaranteeing proper serialization of the calls. Default value is true.
* @param {Loki.PersistenceMethod} options.persistenceMethod - a persistence method which should be used (FS_STORAGE, LOCAL_STORAGE...)
* @returns {Promise} a Promise that resolves after initialization and (if enabled) autoloading the database
*/
initializePersistence(options?: Loki.PersistenceOptions): Promise<void>;
/**
* Copies 'this' database into a new Loki instance. Object references are shared to make lightweight.
* @param {object} options - options
* @param {boolean} options.removeNonSerializable - nulls properties not safe for serialization.
*/
copy(options?: Loki.CopyOptions): Loki;
/**
* Adds a collection to the database.
* @param {string} name - name of collection to add
* @param {object} [options={}] - options to configure collection with.
* @param {array} [options.unique=[]] - array of property names to define unique constraints for
* @param {array} [options.exact=[]] - array of property names to define exact constraints for
* @param {array} [options.indices=[]] - array property names to define binary indexes for
* @param {boolean} [options.asyncListeners=false] - whether listeners are called asynchronously
* @param {boolean} [options.disableMeta=false] - set to true to disable meta property on documents
* @param {boolean} [options.disableChangesApi=true] - set to false to enable Changes Api
* @param {boolean} [options.disableDeltaChangesApi=true] - set to false to enable Delta Changes API (requires Changes API, forces cloning)
* @param {boolean} [options.clone=false] - specify whether inserts and queries clone to/from user
* @param {string} [options.cloneMethod=CloneMethod.DEEP] - the clone method
* @param {number} [options.ttl=] - age of document (in ms.) before document is considered aged/stale
* @param {number} [options.ttlInterval=] - time interval for clearing out 'aged' documents; not set by default
* @returns {Collection} a reference to the collection which was just added
*/
addCollection<TData extends object = object, TNested extends object = object>(name: string, options?: Collection.Options<TData, TNested>): Collection<TData, TNested>;
loadCollection(collection: Collection): void;
/**
* Retrieves reference to a collection by name.
* @param {string} name - name of collection to look up
* @returns {Collection} Reference to collection in database by that name, or null if not found
*/
getCollection<TData extends object = object, TNested extends object = object>(name: string): Collection<TData, TNested>;
/**
* Renames an existing loki collection
* @param {string} oldName - name of collection to rename
* @param {string} newName - new name of collection
* @returns {Collection} reference to the newly renamed collection
*/
renameCollection<TData extends object = object, TNested extends object = object>(oldName: string, newName: string): Collection<TData, TNested>;
listCollections(): {
name: string;
count: number;
}[];
/**
* Removes a collection from the database.
* @param {string} collectionName - name of collection to remove
*/
removeCollection(collectionName: string): void;
/**
* Serialize database to a string which can be loaded via {@link Loki#loadJSON}
*
* @returns {string} Stringified representation of the loki database.
*/
serialize(options?: Loki.SerializeOptions): string | string[];
toJSON(): Loki.Serialized;
/**
* Database level destructured JSON serialization routine to allow alternate serialization methods.
* Internally, Loki supports destructuring via loki "serializationMethod' option and
* the optional LokiPartitioningAdapter class. It is also available if you wish to do
* your own structured persistence or data exchange.
*
* @param {object} options - output format options for use externally to loki
* @param {boolean} [options.partitioned=false] - whether db and each collection are separate
* @param {int} options.partition - can be used to only output an individual collection or db (-1)
* @param {boolean} [options.delimited=true] - whether subitems are delimited or subarrays
* @param {string} options.delimiter - override default delimiter
*
* @returns {string|Array} A custom, restructured aggregation of independent serializations.
*/
serializeDestructured(options?: Loki.SerializeDestructuredOptions): string | string[];
/**
* Collection level utility method to serialize a collection in a 'destructured' format
*
* @param {object} options - used to determine output of method
* @param {int} options.delimited - whether to return single delimited string or an array
* @param {string} options.delimiter - (optional) if delimited, this is delimiter to use
* @param {int} options.collectionIndex - specify which collection to serialize data for
*
* @returns {string|array} A custom, restructured aggregation of independent serializations for a single collection.
*/
serializeCollection(options?: {
delimited?: boolean;
collectionIndex?: number;
delimiter?: string;
}): string | string[];
/**
* Database level destructured JSON deserialization routine to minimize memory overhead.
* Internally, Loki supports destructuring via loki "serializationMethod' option and
* the optional LokiPartitioningAdapter class. It is also available if you wish to do
* your own structured persistence or data exchange.
*
* @param {string|array} destructuredSource - destructured json or array to deserialize from
* @param {object} options - source format options
* @param {boolean} [options.partitioned=false] - whether db and each collection are separate
* @param {int} options.partition - can be used to deserialize only a single partition
* @param {boolean} [options.delimited=true] - whether subitems are delimited or subarrays
* @param {string} options.delimiter - override default delimiter
*
* @returns {object|array} An object representation of the deserialized database, not yet applied to 'this' db or document array
*/
deserializeDestructured(destructuredSource: string | string[], options?: Loki.SerializeDestructuredOptions): any;
/**
* Collection level utility function to deserializes a destructured collection.
*
* @param {string|string[]} destructuredSource - destructured representation of collection to inflate
* @param {object} options - used to describe format of destructuredSource input
* @param {int} [options.delimited=false] - whether source is delimited string or an array
* @param {string} options.delimiter - if delimited, this is delimiter to use (if other than default)
*
* @returns {Array} an array of documents to attach to collection.data.
*/
deserializeCollection<T extends object = object>(destructuredSource: string | string[], options?: Loki.DeserializeCollectionOptions): Doc<T>[];
/**
* Inflates a loki database from a serialized JSON string
*
* @param {string} serializedDb - a serialized loki database string
* @param {object} options - apply or override collection level settings
* @param {boolean} options.retainDirtyFlags - whether collection dirty flags will be preserved
*/
loadJSON(serializedDb: string | string[], options?: Collection.DeserializeOptions): void;
/**
* Inflates a loki database from a JS object
*
* @param {object} dbObject - a serialized loki database object
* @param {object} options - apply or override collection level settings
* @param {boolean} options.retainDirtyFlags - whether collection dirty flags will be preserved
*/
loadJSONObject(dbObject: Loki, options?: Collection.DeserializeOptions): void;
loadJSONObject(dbObject: Loki.Serialized, options?: Collection.DeserializeOptions): void;
/**
* Emits the close event. In autosave scenarios, if the database is dirty, this will save and disable timer.
* Does not actually destroy the db.
*
* @returns {Promise} a Promise that resolves after closing the database succeeded
*/
close(): Promise<void>;
/**-------------------------+
| Changes API |
+--------------------------*/
/**
* The Changes API enables the tracking the changes occurred in the collections since the beginning of the session,
* so it's possible to create a differential dataset for synchronization purposes (possibly to a remote db)
*/
/**
* (Changes API) : takes all the changes stored in each
* collection and creates a single array for the entire database. If an array of names
* of collections is passed then only the included collections will be tracked.
*
* @param {Array} [arrayOfCollectionNames=] - array of collection names. No arg means all collections are processed.
* @returns {Array} array of changes
* @see private method _createChange() in Collection
*/
generateChangesNotification(arrayOfCollectionNames?: string[]): Collection.Change[];
/**
* (Changes API) - stringify changes for network transmission
* @returns {string} string representation of the changes
*/
serializeChanges(collectionNamesArray?: string[]): string;
/**
* (Changes API) : clears all the changes in all collections.
*/
clearChanges(): void;
/**
* Wait for throttledSaves to complete and invoke your callback when drained or duration is met.
*
* @param {object} options - configuration options
* @param {boolean} [options.recursiveWait=true] - if after queue is drained, another save was kicked off, wait for it
* @param {boolean} [options.recursiveWaitLimit=false] - limit our recursive waiting to a duration
* @param {number} [options.recursiveWaitLimitDuration=2000] - cutoff in ms to stop recursively re-draining
* @param {Date} [options.started=now()] - the start time of the recursive wait duration
* @returns {Promise} a Promise that resolves when save queue is drained, it is passed a sucess parameter value
*/
throttledSaveDrain(options?: Loki.ThrottledDrainOptions): Promise<void>;
/**
* Internal load logic, decoupled from throttling/contention logic
*
* @param {object} options - an object containing inflation options for each collection
* @param {boolean} ignore_not_found - does not raise an error if database is not found
* @returns {Promise} a Promise that resolves after the database is loaded
*/
private _loadDatabase(options?, ignore_not_found?);
/**
* Handles manually loading from an adapter storage (such as fs-storage)
* This method utilizes loki configuration options (if provided) to determine which
* persistence method to use, or environment detection (if configuration was not provided).
* To avoid contention with any throttledSaves, we will drain the save queue first.
*
* If you are configured with autosave, you do not need to call this method yourself.
*
* @param {object} [options={}] - if throttling saves and loads, this controls how we drain save queue before loading
* @param {boolean} [options.recursiveWait=true] wait recursively until no saves are queued
* @param {boolean} [options.recursiveWaitLimit=false] limit our recursive waiting to a duration
* @param {number} [options.recursiveWaitLimitDelay=2000] cutoff in ms to stop recursively re-draining
* @param {Date} [options.started=now()] - the start time of the recursive wait duration
* @returns {Promise} a Promise that resolves after the database is loaded
*/
loadDatabase(options?: Loki.LoadDatabaseOptions): Promise<void>;
private _saveDatabase();
/**
* Handles manually saving to an adapter storage (such as fs-storage)
* This method utilizes loki configuration options (if provided) to determine which
* persistence method to use, or environment detection (if configuration was not provided).
*
* If you are configured with autosave, you do not need to call this method yourself.
*
* @returns {Promise} a Promise that resolves after the database is persisted
*/
saveDatabase(): Promise<void>;
/**
* Handles deleting a database from the underlying storage adapter
*
* @returns {Promise} a Promise that resolves after the database is deleted
*/
deleteDatabase(): Promise<void>;
/****************
* Autosave API
****************/
/**
* Check whether any collections are "dirty" meaning we need to save the (entire) database
* @returns {boolean} - true if database has changed since last autosave, otherwise false
*/
private _autosaveDirty();
/**
* Resets dirty flags on all collections.
*/
private _autosaveClearFlags();
/**
* Starts periodically saves to the underlying storage adapter.
*/
private _autosaveEnable();
/**
* Stops the autosave interval timer.
*/
private _autosaveDisable();
}
export declare namespace Loki {
interface Options {
env?: Environment;
serializationMethod?: SerializationMethod;
destructureDelimiter?: string;
comparatorMap?: IComparatorMap;
rangedIndexFactoryMap?: IRangedIndexFactoryMap;
lokiOperatorPackageMap?: ILokiOperatorPackageMap;
}
interface PersistenceOptions {
adapter?: StorageAdapter;
autosave?: boolean;
autosaveInterval?: number;
autoload?: boolean;
throttledSaves?: boolean;
persistenceMethod?: Loki.PersistenceMethod;
inflate?: any;
}
interface CopyOptions {
removeNonSerializable?: boolean;
}
interface SerializeOptions {
serializationMethod?: SerializationMethod;
}
interface SerializeDestructuredOptions {
partitioned?: boolean;
partition?: number;
delimited?: boolean;
delimiter?: string;
}
interface DeserializeCollectionOptions {
partitioned?: boolean;
delimited?: boolean;
delimiter?: string;
}
interface ThrottledDrainOptions {
recursiveWait?: boolean;
recursiveWaitLimit?: boolean;
recursiveWaitLimitDuration?: number;
started?: Date;
}
interface Serialized {
_env: Environment;
_serializationMethod: SerializationMethod;
_autosave: boolean;
_autosaveInterval: number;
_collections: Collection[];
databaseVersion: number;
engineVersion: number;
filename: string;
_persistenceAdapter: StorageAdapter;
_persistenceMethod: PersistenceMethod;
_throttledSaves: boolean;
}
type LoadDatabaseOptions = Collection.DeserializeOptions & ThrottledDrainOptions;
type SerializationMethod = "normal" | "pretty" | "destructured";
type PersistenceMethod = "fs-storage" | "local-storage" | "indexed-storage" | "memory-storage" | "adapter";
type Environment = "NATIVESCRIPT" | "NODEJS" | "CORDOVA" | "BROWSER" | "MEMORY";
} | the_stack |
import { Mat3 } from "../math/Mat3";
import { Mat4 } from "../math/Mat4";
import { Vec2 } from "../math/Vec2";
import { Vec3 } from "../math/Vec3";
import { Vec4 } from "../math/Vec4";
import { TypedArray } from "./types";
var _vector = new Vec3();
export class BufferAttribute {
name: string;
array: TypedArray;
itemSize: number;
// usage: Usage;
updateRange: { offset: number; count: number };
version: number;
normalized: boolean;
count: number;
readonly isBufferAttribute: true = true;
/**
*
* @param array {BufferArray} Buffer数据
* @param itemSize 单元长度,vec3是3,vec4是4
* @param normalized
*/
constructor(array: TypedArray, itemSize: number, normalized?: boolean) {
this.name = '';
this.array = array;
this.itemSize = itemSize;
this.count = array !== undefined ? array.length / itemSize : 0;
this.normalized = normalized === true;
// this.usage = StaticDrawUsage;
this.updateRange = { offset: 0, count: - 1 };
this.version = 0;
}
set needsUpdate(value: boolean) {
if (value === true)
this.version++;
}
onUploadCallback?: () => void;
onUpload(callback: () => void): this {
this.onUploadCallback = callback;
return this;
}
setUsage(usage: any): this {
return this
}
copy(source: BufferAttribute): this {
this.name = source.name;
this.array = new (source.array as unknown as any).constructor(source.array);
this.itemSize = source.itemSize;
this.count = source.count;
this.normalized = source.normalized;
// this.usage = source.usage;
return this;
}
copyAt(index1: number, attribute: BufferAttribute, index2: number) {
index1 *= this.itemSize;
index2 *= attribute.itemSize;
for (var i = 0, l = this.itemSize; i < l; i++) {
this.array[index1 + i] = attribute.array[index2 + i];
}
return this;
}
copyArray(array: ArrayLike<number>) {
this.array.set(array);
return this;
}
copyColorsArray(colors: { r: number; g: number; b: number }[]) {
var array = this.array, offset = 0;
for (var i = 0, l = colors.length; i < l; i++) {
var color = colors[i];
// if (color === undefined) {
// console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
// color = new Color();
// }
// array[offset++] = color.r;
// array[offset++] = color.g;
// array[offset++] = color.b;
}
return this;
}
copyVec2sArray(vectors: { x: number; y: number }[]) {
var array = this.array, offset = 0;
for (var i = 0, l = vectors.length; i < l; i++) {
var vector = vectors[i];
if (vector === undefined) {
console.warn('THREE.BufferAttribute.copyVec2sArray(): vector is undefined', i);
vector = new Vec2();
}
array[offset++] = vector.x;
array[offset++] = vector.y;
}
return this;
}
copyVec3sArray(vectors: { x: number; y: number; z: number }[]) {
var array = this.array, offset = 0;
for (var i = 0, l = vectors.length; i < l; i++) {
var vector = vectors[i];
if (vector === undefined) {
console.warn('THREE.BufferAttribute.copyVec3sArray(): vector is undefined', i);
vector = new Vec3();
}
array[offset++] = vector.x;
array[offset++] = vector.y;
array[offset++] = vector.z;
}
return this;
}
copyVec4sArray(vectors: { x: number; y: number; z: number; w: number }[]) {
var array = this.array, offset = 0;
for (var i = 0, l = vectors.length; i < l; i++) {
var vector = vectors[i];
if (vector === undefined) {
console.warn('THREE.BufferAttribute.copyVec4sArray(): vector is undefined', i);
vector = new Vec4();
}
array[offset++] = vector.x;
array[offset++] = vector.y;
array[offset++] = vector.z;
array[offset++] = vector.w;
}
return this;
}
applyMat3(m: Mat3) {
for (var i = 0, l = this.count; i < l; i++) {
_vector.x = this.getX(i);
_vector.y = this.getY(i);
_vector.z = this.getZ(i);
_vector.applyMat3(m);
this.setXYZ(i, _vector.x, _vector.y, _vector.z);
}
return this;
}
applyMat4(m: Mat4) {
for (var i = 0, l = this.count; i < l; i++) {
_vector.x = this.getX(i);
_vector.y = this.getY(i);
_vector.z = this.getZ(i);
_vector.applyMat4(m);
this.setXYZ(i, _vector.x, _vector.y, _vector.z);
}
return this;
}
applyNormalMat(m: Mat3) {
for (var i = 0, l = this.count; i < l; i++) {
_vector.x = this.getX(i);
_vector.y = this.getY(i);
_vector.z = this.getZ(i);
_vector.applyNormalMat(m);
this.setXYZ(i, _vector.x, _vector.y, _vector.z);
}
return this;
}
transformDirection(m: Mat4) {
for (var i = 0, l = this.count; i < l; i++) {
_vector.x = this.getX(i);
_vector.y = this.getY(i);
_vector.z = this.getZ(i);
_vector.transformDirection(m);
this.setXYZ(i, _vector.x, _vector.y, _vector.z);
}
return this;
}
set(value: ArrayLike<number>, offset: number) {
if (offset === undefined) offset = 0;
this.array.set(value, offset);
return this;
}
getX(index: number) {
return this.array[index * this.itemSize];
}
setX(index: number, x: number) {
this.array[index * this.itemSize] = x;
return this;
}
getY(index: number) {
return this.array[index * this.itemSize + 1];
}
setY(index: number, y: number) {
this.array[index * this.itemSize + 1] = y;
return this;
}
getZ(index: number) {
return this.array[index * this.itemSize + 2];
}
setZ(index: number, z: number) {
this.array[index * this.itemSize + 2] = z;
return this;
}
getW(index: number) {
return this.array[index * this.itemSize + 3];
}
setW(index: number, w: number) {
this.array[index * this.itemSize + 3] = w;
return this;
}
setXY(index: number, x: number, y: number) {
index *= this.itemSize;
this.array[index + 0] = x;
this.array[index + 1] = y;
return this;
}
setXYZ(index: number, x: number, y: number, z: number) {
index *= this.itemSize;
this.array[index + 0] = x;
this.array[index + 1] = y;
this.array[index + 2] = z;
return this;
}
setXYZW(index: number, x: number, y: number, z: number, w: number) {
index *= this.itemSize;
this.array[index + 0] = x;
this.array[index + 1] = y;
this.array[index + 2] = z;
this.array[index + 3] = w;
return this;
}
clone(): BufferAttribute {
return new BufferAttribute(this.array, this.itemSize).copy(this);
}
toJSON(): {
itemSize: number,
type: string,
array: number[],
normalized: boolean
} {
return {
itemSize: this.itemSize,
type: this.array.constructor.name,
array: Array.prototype.slice.call(this.array),
normalized: this.normalized
};
}
}
export class Int8BufferAttribute extends BufferAttribute {
constructor(array: any, itemSize: number, normalized: boolean = false) {
if (Array.isArray(array))
array = new Int8Array(array)
super(new Int8Array(array), itemSize, normalized);
}
}
export class Uint8BufferAttribute extends BufferAttribute {
constructor(array: any, itemSize: number, normalized: boolean = false) {
if (Array.isArray(array))
array = new Uint8Array(array)
super(array, itemSize, normalized);
}
}
export class Uint8ClampedBufferAttribute extends BufferAttribute {
constructor(array: any, itemSize: number, normalized: boolean = false) {
if (Array.isArray(array))
array = new Uint8ClampedArray(array)
super(array, itemSize, normalized);
}
}
export class Int16BufferAttribute extends BufferAttribute {
constructor(array: any, itemSize: number, normalized: boolean = false) {
if (Array.isArray(array))
array = new Int16Array(array)
super(array, itemSize, normalized);
}
}
export class Uint16BufferAttribute extends BufferAttribute {
constructor(array: any, itemSize: number, normalized: boolean = false) {
if (Array.isArray(array))
array = new Uint16Array(array)
super(array, itemSize)
}
}
export class Int32BufferAttribute extends BufferAttribute {
constructor(array: any, itemSize: number, normalized: boolean = false) {
if (Array.isArray(array))
array = new Int32Array(array)
super(array, itemSize, normalized);
}
}
export class Uint32BufferAttribute extends BufferAttribute {
constructor(array: any, itemSize: number, normalized: boolean = false) {
if (Array.isArray(array))
array = new Uint32Array(array)
super(array, itemSize, normalized);
}
}
export class Float32BufferAttribute extends BufferAttribute {
constructor(array: any, itemSize: number, normalized: boolean = false) {
if (Array.isArray(array))
array = new Float32Array(array)
super(array, itemSize, normalized);
}
}
export class Float64BufferAttribute extends BufferAttribute {
constructor(array: any, itemSize: number, normalized: boolean = false) {
if (Array.isArray(array))
array = new Float64Array(array)
super(array, itemSize, normalized);
}
} | the_stack |
// TODO: expose walk as method for general purpose
import { Gex } from 'gex'
import {
Matcher,
MatchValue,
GexMatcher,
IntervalMatcher,
} from './lib/matchers'
module.exports = function (custom: any) {
return new (Patrun as any)(custom)
}
function Patrun(custom: any) {
custom = custom || {}
var self: any = {}
var top: any = {}
let matchers: Matcher[] = []
if (custom.gex) {
matchers.push(new GexMatcher())
}
if (custom.interval) {
matchers.push(new IntervalMatcher())
}
// Provide internal search order structure
self.top = function () {
return top
}
self.add = function (pat: any, data: any) {
pat = { ...pat }
var customizer =
'function' === typeof custom ? custom.call(self, pat, data) : null
var keys = Object.keys(pat)
.filter((key) => null != pat[key])
.sort()
keys.forEach(function (key) {
pat[key] = String(pat[key])
})
var keymap: any = top
var valmap: any
// Partial matches return next wider match - see partial-match test.
// Traverse the key path (keys are ordered), insert preserves order.
for (var i = 0; i < keys.length; i++) {
// console.log('L', i, keys.length)
var key = keys[i]
var fix = pat[key]
let mv: MatchValue | undefined = matchers.reduce(
(m, t) => m || t.make(key, fix),
undefined
)
// if (mv) mv.val$ = fix
valmap = keymap.v
// console.log('S0',key,fix,keymap,valmap)
// An existing key
if (valmap && key == keymap.k) {
// console.log('S1-a')
// add_mv(keymap, key, mv)
if (mv) {
var g = (keymap.g = keymap.g || {})
var ga = (g[key] = g[key] || [])
mv = (ga.find((gmv: MatchValue) => gmv.same(mv)) ||
(ga.push(mv), mv)) as MatchValue
keymap = mv.keymap || (mv.keymap = {})
} else {
keymap = valmap[fix] || (valmap[fix] = {})
}
}
// End of key path reached, so this is a new key, ordered last
else if (!keymap.k) {
keymap.k = key
keymap.v = {}
if (mv) {
var g = (keymap.g = keymap.g || {})
var ga = (g[key] = g[key] || [])
mv = (ga.find((gmv: MatchValue) => gmv.same(mv)) ||
(ga.push(mv), mv)) as MatchValue
keymap = mv.keymap || (mv.keymap = {})
} else {
keymap = keymap.v[fix] = {}
}
}
// Insert key orders before next existing key in path, so insert
else if (key < keymap.k) {
// console.log('S1-c', key, keymap.k)
var s = keymap.s
var g = keymap.g
keymap.s = {
k: keymap.k,
// sk: keymap.sk,
v: keymap.v,
}
if (s) {
keymap.s.s = s
}
if (g) {
keymap.s.g = g
}
if (keymap.g) {
keymap.g = {}
}
keymap.k = key
keymap.v = {}
if (mv) {
var g = (keymap.g = keymap.g || {})
var ga = (g[key] = g[key] || [])
mv = (ga.find((gmv: MatchValue) => gmv.same(mv)) ||
(ga.push(mv), mv)) as MatchValue
keymap = mv.keymap || (mv.keymap = {})
} else {
keymap = keymap.v[fix] = {}
}
}
// Follow star path
else {
keymap = keymap.s || (keymap.s = {})
// NOTE: current key is still not inserted
i--
}
}
if (void 0 !== data && keymap) {
keymap.d = data
if (customizer) {
keymap.f =
'function' === typeof customizer ? customizer : customizer.find
keymap.r =
'function' === typeof customizer.remove ? customizer.remove : void 0
}
}
return self
}
self.findexact = function (pat: any) {
return self.find(pat, true)
}
self.find = function (pat: any, exact: any, collect: any) {
if (null == pat) return null
var keymap: any = top
var data: any = void 0 === top.d ? null : top.d
var finalfind = top.f
var key = null
var stars = []
var foundkeys: any = {}
var patlen = Object.keys(pat).length
var collection = []
if (void 0 !== top.d) {
collection.push(top.d)
}
do {
key = keymap.k
if (keymap.v) {
var val = pat[key]
// Matching operation is either string equality (by prop lookup)
// or gex match.
var nextkeymap = keymap.v[val]
if (!nextkeymap && keymap.g && keymap.g[key]) {
var ga = keymap.g[key]
for (var gi = 0; gi < ga.length; gi++) {
if (ga[gi].match(val)) {
nextkeymap = ga[gi].keymap
break
}
}
}
if (nextkeymap) {
foundkeys[key] = true
if (keymap.s) {
stars.push(keymap.s)
}
data = void 0 === nextkeymap.d ? (exact ? null : data) : nextkeymap.d
if (collect && void 0 !== nextkeymap.d) {
collection.push(nextkeymap.d)
}
finalfind = nextkeymap.f
keymap = nextkeymap
}
// no match found for this value, follow star trail
else {
keymap = keymap.s
}
} else {
keymap = null
}
if (
null == keymap &&
0 < stars.length &&
(null == data || (collect && !exact))
) {
keymap = stars.pop()
}
} while (keymap)
if (exact) {
if (Object.keys(foundkeys).length !== patlen) {
data = null
}
} else {
// If there's root data, return as a catch all
if (null == data && void 0 !== top.d) {
data = top.d
}
}
if (finalfind) {
data = finalfind.call(self, pat, data)
}
return collect ? collection : data
}
self.remove = function (pat: any) {
var keymap = top
var data = null
var key
var path = []
do {
key = keymap.k
// console.log('keymap v g', keymap.v, keymap.g)
if (keymap.v || keymap.g) {
if (keymap.v) {
var nextkeymap = keymap.v[pat[key]]
if (nextkeymap) {
path.push({ km: keymap, v: pat[key] })
}
}
if (null == nextkeymap && keymap.g) {
let mvs: MatchValue[] = keymap.g[key] || []
for (let mvi = 0; mvi < mvs.length; mvi++) {
// TODO: should parse!
if (mvs[mvi].fix === pat[key]) {
path.push({ km: keymap, v: pat[key], mv: mvs[mvi] })
nextkeymap = mvs[mvi].keymap
break
}
}
}
if (nextkeymap) {
data = nextkeymap.d
keymap = nextkeymap
} else {
keymap = keymap.s
}
} else {
keymap = null
}
} while (keymap)
if (void 0 !== data) {
var part = path[path.length - 1]
if (part && part.km && part.km.v) {
var point = part.km.v[part.v] || (part.mv && part.mv.keymap)
if (point && (!point.r || point.r(pat, point.d))) {
delete point.d
}
}
}
}
// values can be verbatim, glob, or array of globs
self.list = function (pat: any, exact: boolean) {
pat = pat || {}
function descend(keymap: any, match: any, missing: any, acc: any) {
if (keymap.v) {
var key = keymap.k
var gexval = Gex(
pat ? (null == pat[key] ? (exact ? null : '*') : pat[key]) : '*'
)
var itermatch = { ...match }
var itermissing = { ...missing }
var nextkeymap
for (var val in keymap.v) {
if (
val === pat[key] ||
(!exact && null == pat[key]) ||
gexval.on(val)
) {
var valitermatch = { ...itermatch }
valitermatch[key] = val
var valitermissing = { ...itermissing }
delete valitermissing[key]
nextkeymap = keymap.v[val]
if (
0 === Object.keys(valitermissing).length &&
nextkeymap &&
nextkeymap.d
) {
acc.push({
match: valitermatch,
data: nextkeymap.d,
find: nextkeymap.f,
})
}
if (nextkeymap && null != nextkeymap.v) {
descend(
nextkeymap,
{ ...valitermatch },
{ ...valitermissing },
acc
)
}
}
}
nextkeymap = keymap.s
if (nextkeymap) {
descend(nextkeymap, { ...itermatch }, { ...itermissing }, acc)
}
}
}
var acc = []
if (top.d) {
acc.push({
match: {},
data: top.d,
find: top.f,
})
}
descend(top, {}, { ...pat }, acc)
return acc
}
self.toString = function (first: any, second: any) {
var tree = true === first ? true : !!second
var dstr =
'function' === typeof first
? first
: function (d: any) {
return 'function' === typeof d ? '<' + d.name + '>' : '<' + d + '>'
}
function indent(o: any, d: any) {
for (var i = 0; i < d; i++) {
o.push(' ')
}
}
var str: any[] = []
function walk(n: any, o: any, d: any, vs: any) {
var vsc
if (void 0 !== n.d) {
o.push(' ' + dstr(n.d))
str.push(vs.join(', ') + ' -> ' + dstr(n.d))
}
if (n.k) {
o.push('\n')
indent(o, d)
o.push(n.k + ':')
}
if (n.v || n.s || n.g) {
d++
}
if (n.v) {
// d++
var pa = Object.keys(n.v).sort()
for (var pi = 0; pi < pa.length; pi++) {
var p = pa[pi]
o.push('\n')
indent(o, d)
o.push(p + ' ->')
vsc = vs.slice()
vsc.push(n.k + '=' + p)
walk(n.v[p], o, d + 1, vsc)
}
}
if (n.g) {
var pa = Object.keys(n.g).sort()
for (var pi = 0; pi < pa.length; pi++) {
var mvs = n.g[pa[pi]]
for (var mvi = 0; mvi < mvs.length; mvi++) {
var mv = mvs[mvi]
o.push('\n')
indent(o, d)
o.push(mv.fix + ' ~>')
vsc = vs.slice()
vsc.push(n.k + '~' + mv.fix)
walk(mv.keymap, o, d + 1, vsc)
}
}
}
if (n.s) {
o.push('\n')
indent(o, d)
o.push('|')
vsc = vs.slice()
walk(n.s, o, d + 1, vsc)
}
}
var o: any = []
walk(top, o, 0, [])
return tree ? o.join('') : str.join('\n')
}
self.inspect = self.toString
self.toJSON = function (indent: any) {
return JSON.stringify(
top,
function (key: any, val: any) {
if ('function' === typeof val) return '[Function]'
return val
},
indent
)
}
return self
} | the_stack |
import { BigNumber } from "bignumber.js";
import { Observable, from, defer, of, throwError, concat } from "rxjs";
import {
skip,
take,
reduce,
mergeMap,
map,
filter,
concatMap,
} from "rxjs/operators";
import type {
Account,
CryptoCurrency,
SyncConfig,
} from "@ledgerhq/live-common/lib/types";
import {
fromAccountRaw,
encodeAccountId,
decodeAccountId,
emptyHistoryCache,
} from "@ledgerhq/live-common/lib/account";
import { asDerivationMode } from "@ledgerhq/live-common/lib/derivation";
import {
getAccountBridge,
getCurrencyBridge,
} from "@ledgerhq/live-common/lib/bridge";
import {
findCryptoCurrencyByKeyword,
findCryptoCurrencyById,
getCryptoCurrencyById,
} from "@ledgerhq/live-common/lib/currencies";
import {
runDerivationScheme,
getDerivationScheme,
} from "@ledgerhq/live-common/lib/derivation";
import { makeBridgeCacheSystem } from "@ledgerhq/live-common/lib/bridge/cache";
import getAppAndVersion from "@ledgerhq/live-common/lib/hw/getAppAndVersion";
import { withDevice } from "@ledgerhq/live-common/lib/hw/deviceAccess";
import { delay } from "@ledgerhq/live-common/lib/promise";
import { jsonFromFile } from "./stream";
import { shortAddressPreview } from "@ledgerhq/live-common/lib/account/helpers";
import fs from "fs";
export const deviceOpt = {
name: "device",
alias: "d",
type: String,
descOpt: "usb path",
desc: "provide a specific HID path of a device",
};
export const currencyOpt = {
name: "currency",
alias: "c",
type: String,
desc: "Currency name or ticker. If not provided, it will be inferred from the device.",
};
const localCache = {};
const cache = makeBridgeCacheSystem({
saveData(c, d) {
localCache[c.id] = d;
return Promise.resolve();
},
getData(c) {
return Promise.resolve(localCache[c.id]);
},
});
export type ScanCommonOpts = Partial<{
device: string;
id: string[];
xpub: string[];
file: string;
appjsonFile: string;
currency: string;
scheme: string;
index: number;
length: number;
paginateOperations: number;
}>;
export const scanCommonOpts = [
deviceOpt,
{
name: "xpub",
type: String,
desc: "use an xpub (alternatively to --device) [DEPRECATED: prefer use of id]",
multiple: true,
},
{
name: "id",
type: String,
desc: "restore an account id (or a partial version of an id) (alternatively to --device)",
multiple: true,
},
{
name: "file",
type: String,
typeDesc: "filename",
desc: "use a JSON account file or '-' for stdin (alternatively to --device)",
},
{
name: "appjsonFile",
type: String,
typeDesc: "filename",
desc: "use a desktop app.json (alternatively to --device)",
},
currencyOpt,
{
name: "scheme",
alias: "s",
type: String,
desc: "if provided, filter the derivation path that are scanned by a given sceme. Providing '' empty string will only use the default standard derivation scheme.",
},
{
name: "index",
alias: "i",
type: Number,
desc: "select the account by index",
},
{
name: "length",
alias: "l",
type: Number,
desc: "set the number of accounts after the index. Defaults to 1 if index was provided, Infinity otherwise.",
},
{
name: "paginateOperations",
type: Number,
desc: "if defined, will paginate operations",
},
];
export const inferManagerApp = (keyword: string): string => {
try {
const currency = findCryptoCurrencyByKeyword(keyword);
if (!currency || !currency.managerAppName) return keyword;
return currency.managerAppName;
} catch (e) {
return keyword;
}
};
const implTypePerFamily = {
tron: "js",
ripple: "js",
ethereum: "js",
polkadot: "js",
bitcoin: "js",
};
const possibleImpls = {
js: 1,
libcore: 1,
mock: 1,
};
export const inferCurrency = <
T extends {
device: string;
currency: string;
file: string;
xpub: string[];
id: string[];
}
>({
device,
currency,
file,
xpub,
id,
}: Partial<T>) => {
if (currency) {
return defer(() => of(findCryptoCurrencyByKeyword(currency)));
}
if (file || xpub || id) {
return of(undefined);
}
return withDevice(device || "")((t) =>
from(
getAppAndVersion(t)
.then(
(r) => findCryptoCurrencyByKeyword(r.name),
() => undefined
)
.then((r) => delay(500).then(() => r))
)
);
};
function requiredCurrency(cur) {
if (!cur) throw new Error("--currency is required");
return cur;
}
const prepareCurrency = (fn) => (observable) =>
observable.pipe(
concatMap((item) => {
const maybeCurrency = fn(item);
return maybeCurrency
? from(cache.prepareCurrency(maybeCurrency).then(() => item))
: of(item);
})
);
export function scan(arg: ScanCommonOpts): Observable<Account> {
const {
device,
id: idArray,
xpub: xpubArray,
file,
appjsonFile,
scheme,
index,
length,
paginateOperations,
} = arg;
const syncConfig: SyncConfig = {
paginationConfig: {
operations: undefined,
},
};
if (typeof paginateOperations === "number") {
syncConfig.paginationConfig.operations = paginateOperations;
}
if (typeof appjsonFile === "string") {
const appjsondata = appjsonFile
? JSON.parse(fs.readFileSync(appjsonFile, "utf-8"))
: {
data: {
accounts: [],
},
};
if (typeof appjsondata.data.accounts === "string") {
return throwError(
new Error("encrypted ledger live data is not supported")
);
}
return from(
appjsondata.data.accounts.map((a) => fromAccountRaw(a.data))
).pipe(
skip(index || 0) as any,
take(length === undefined ? (index !== undefined ? 1 : Infinity) : length)
);
}
if (typeof file === "string") {
return jsonFromFile(file).pipe(
map(fromAccountRaw),
prepareCurrency((a) => a.currency),
concatMap((account: Account) =>
getAccountBridge(account, null)
.sync(account, syncConfig)
.pipe(reduce((a, f: (arg: any) => any) => f(a), account))
)
) as Observable<Account>;
}
return inferCurrency(arg).pipe(
mergeMap((cur: CryptoCurrency | null | undefined) => {
let ids = idArray;
if (xpubArray) {
console.warn("Usage of --xpub is deprecated. Prefer usage of `--id`");
ids = (ids || []).concat(xpubArray);
}
// TODO this should be a "inferAccountId" that needs to look at available impl and do same logic as in bridge.. + we should accept full id as param
// we kill the --xpub to something else too (--id)
// Restore from ids
if (ids) {
// Infer the full ids
const fullIds: string[] = ids.map((id) => {
try {
// preserve if decodeAccountId don't fail
decodeAccountId(id);
return id;
} catch (e) {
const splitted = id.split(":");
const findAndEat = (predicate) => {
const res = splitted.find(predicate);
if (typeof res === "string") {
splitted.splice(splitted.indexOf(res), 1);
return res;
}
};
const currencyId =
findAndEat((s) => findCryptoCurrencyById(s)) ||
requiredCurrency(cur).id;
const currency = getCryptoCurrencyById(currencyId);
const type =
findAndEat((s) => possibleImpls[s]) ||
implTypePerFamily[currency.family] ||
"libcore";
const version = findAndEat((s) => s.match(/^\d+$/)) || "1";
const derivationMode = asDerivationMode(
findAndEat((s) => {
try {
return asDerivationMode(s);
} catch (e) {
// this is therefore not a derivation mode
}
}) ??
scheme ??
""
);
if (splitted.length === 0) {
throw new Error(
"invalid id='" + id + "': missing xpub or address part"
);
}
if (splitted.length > 1) {
throw new Error(
"invalid id='" +
id +
"': couldn't understand which of these are the xpub or address part: " +
splitted.join(" | ")
);
}
const xpubOrAddress = splitted[0];
return encodeAccountId({
type,
version,
currencyId,
xpubOrAddress,
derivationMode,
});
}
});
return from(
fullIds.map((id) => {
const { derivationMode, xpubOrAddress, currencyId } =
decodeAccountId(id);
const currency = getCryptoCurrencyById(currencyId);
const scheme = getDerivationScheme({
derivationMode,
currency,
});
const index = 0;
const freshAddressPath = runDerivationScheme(scheme, currency, {
account: index,
node: 0,
address: 0,
});
const account: Account = {
type: "Account",
name:
currency.name +
" " +
(derivationMode || "legacy") +
" " +
shortAddressPreview(xpubOrAddress),
xpub: xpubOrAddress,
seedIdentifier: xpubOrAddress,
starred: true,
used: true,
swapHistory: [],
id,
derivationMode,
currency,
unit: currency.units[0],
index,
freshAddress: xpubOrAddress,
freshAddressPath,
freshAddresses: [],
creationDate: new Date(),
lastSyncDate: new Date(0),
blockHeight: 0,
balance: new BigNumber(0),
spendableBalance: new BigNumber(0),
operationsCount: 0,
operations: [],
pendingOperations: [],
balanceHistoryCache: emptyHistoryCache,
};
return account;
})
).pipe(
prepareCurrency((a: Account) => a.currency),
concatMap((account: Account) =>
getAccountBridge(account, null)
.sync(account, syncConfig)
.pipe(reduce((a: Account, f: any) => f(a), account))
)
);
}
const currency = requiredCurrency(cur);
// otherwise we just scan for accounts
return concat(
of(currency).pipe(prepareCurrency((a) => a)),
getCurrencyBridge(currency).scanAccounts({
currency,
deviceId: device || "",
scheme: scheme && asDerivationMode(scheme),
syncConfig,
})
).pipe(
filter((e: any) => e.type === "discovered"),
map((e) => e.account)
);
}),
skip(index || 0),
take(length === undefined ? (index !== undefined ? 1 : Infinity) : length)
);
} | the_stack |
import { ReadStream, WriteStream } from 'fs';
import {
Disposable,
FileSavedEvent,
HandleableErrorEvent,
HistoryTransactionOptions,
HistoryTraversalOptions,
TextEditOptions,
} from '../../../index';
import {
FindMarkerOptions,
Marker,
MarkerLayer,
Point,
PointCompatible,
Range,
RangeCompatible,
TextChange,
} from './text-buffer';
export * from './display-marker';
export * from './display-marker-layer';
export * from './helpers';
export * from './marker';
export * from './marker-layer';
export * from './point';
export * from './range';
/**
* A mutable text container with undo/redo support and the ability to
* annotate logical regions in the text.
*/
export class TextBuffer {
/** The unique identifier for this buffer. */
readonly id: string;
/** The number of retainers for the buffer. */
readonly refcount: number;
/** Whether or not the bufffer has been destroyed. */
readonly destroyed: boolean;
/** Create a new buffer backed by the given file path. */
static load(filePath: string | TextBufferFileBackend, params?: BufferLoadOptions): Promise<TextBuffer>;
/**
* Create a new buffer backed by the given file path. For better performance,
* use TextBuffer.load instead.
*/
static loadSync(filePath: string, params?: BufferLoadOptions): TextBuffer;
/**
* Restore a TextBuffer based on an earlier state created using the
* TextBuffer::serialize method.
*/
static deserialize(params: object): Promise<TextBuffer>;
/** Create a new buffer with the given starting text. */
constructor(text: string);
/** Create a new buffer with the given params. */
constructor(params?: {
/** The initial string text of the buffer. */
text?: string | undefined;
/**
* A function that returns a Boolean indicating whether the buffer should
* be destroyed if its file is deleted.
*/
shouldDestroyOnFileDelete?(): boolean;
});
/** Returns a plain javascript object representation of the TextBuffer. */
serialize(options?: { markerLayers?: boolean | undefined; history?: boolean | undefined }): object;
/** Returns the unique identifier for this buffer. */
getId(): string;
// Event Subscription
/**
* Invoke the given callback synchronously before the content of the buffer
* changes.
*/
onWillChange(callback: (event: BufferChangingEvent) => void): Disposable;
/**
* Invoke the given callback synchronously when the content of the buffer
* changes. You should probably not be using this in packages.
*/
onDidChange(callback: (event: BufferChangedEvent) => void): Disposable;
/**
* Invoke the given callback synchronously when a transaction finishes with
* a list of all the changes in the transaction.
*/
onDidChangeText(callback: (event: BufferStoppedChangingEvent) => void): Disposable;
/**
* Invoke the given callback asynchronously following one or more changes after
* ::getStoppedChangingDelay milliseconds elapse without an additional change.
*/
onDidStopChanging(callback: (event: BufferStoppedChangingEvent) => void): Disposable;
/**
* Invoke the given callback when the in-memory contents of the buffer become
* in conflict with the contents of the file on disk.
*/
onDidConflict(callback: () => void): Disposable;
/** Invoke the given callback if the value of ::isModified changes. */
onDidChangeModified(callback: (modified: boolean) => void): Disposable;
/**
* Invoke the given callback when all marker ::onDidChange observers have been
* notified following a change to the buffer.
*/
onDidUpdateMarkers(callback: () => void): Disposable;
onDidCreateMarker(callback: (marker: Marker) => void): Disposable;
/** Invoke the given callback when the value of ::getPath changes. */
onDidChangePath(callback: (path: string) => void): Disposable;
/** Invoke the given callback when the value of ::getEncoding changes. */
onDidChangeEncoding(callback: (encoding: string) => void): Disposable;
/**
* Invoke the given callback before the buffer is saved to disk. If the
* given callback returns a promise, then the buffer will not be saved until
* the promise resolves.
*/
onWillSave(callback: () => Promise<void> | void): Disposable;
/** Invoke the given callback after the buffer is saved to disk. */
onDidSave(callback: (event: FileSavedEvent) => void): Disposable;
/** Invoke the given callback after the file backing the buffer is deleted. */
onDidDelete(callback: () => void): Disposable;
/**
* Invoke the given callback before the buffer is reloaded from the contents
* of its file on disk.
*/
onWillReload(callback: () => void): Disposable;
/**
* Invoke the given callback after the buffer is reloaded from the contents
* of its file on disk.
*/
onDidReload(callback: () => void): Disposable;
/** Invoke the given callback when the buffer is destroyed. */
onDidDestroy(callback: () => void): Disposable;
/** Invoke the given callback when there is an error in watching the file. */
onWillThrowWatchError(callback: (errorObject: HandleableErrorEvent) => void): Disposable;
/**
* Get the number of milliseconds that will elapse without a change before
* ::onDidStopChanging observers are invoked following a change.
*/
getStoppedChangingDelay(): number;
// File Details
/**
* Determine if the in-memory contents of the buffer differ from its contents
* on disk.
* If the buffer is unsaved, always returns true unless the buffer is empty.
*/
isModified(): boolean;
/**
* Determine if the in-memory contents of the buffer conflict with the on-disk
* contents of its associated file.
*/
isInConflict(): boolean;
/** Get the path of the associated file. */
getPath(): string | undefined;
/** Set the path for the buffer's associated file. */
setPath(filePath: string): void;
/** Experimental: Set a custom {TextBufferFileBackend} object as the buffer's backing store. */
setFile(fileBackend: TextBufferFileBackend): void;
/** Sets the character set encoding for this buffer. */
setEncoding(encoding: string): void;
/** Returns the string encoding of this buffer. */
getEncoding(): string;
/** Get the path of the associated file. */
getUri(): string;
// Reading Text
/** Determine whether the buffer is empty. */
isEmpty(): boolean;
/**
* Get the entire text of the buffer. Avoid using this unless you know that
* the buffer's text is reasonably short.
*/
getText(): string;
/** Get the text in a range. */
getTextInRange(range: RangeCompatible): string;
/** Get the text of all lines in the buffer, without their line endings. */
getLines(): string[];
/** Get the text of the last line of the buffer, without its line ending. */
getLastLine(): string;
/**
* Get the text of the line at the given 0-indexed row, without its line ending.
* @param row A number representing the row.
*/
lineForRow(row: number): string | undefined;
/** Get the line ending for the given 0-indexed row. */
lineEndingForRow(row: number): string | undefined;
/**
* Get the length of the line for the given 0-indexed row, without its line
* ending.
*/
lineLengthForRow(row: number): number;
/** Determine if the given row contains only whitespace. */
isRowBlank(row: number): boolean;
/**
* Given a row, find the first preceding row that's not blank.
* Returns a number or null if there's no preceding non-blank row.
*/
previousNonBlankRow(startRow: number): number | null;
/**
* Given a row, find the next row that's not blank.
* Returns a number or null if there's no next non-blank row.
*/
nextNonBlankRow(startRow: number): number | null;
/**
* Return true if the buffer contains any astral-plane Unicode characters that
* are encoded as surrogate pairs.
*/
hasAstral(): boolean;
// Mutating Text
/** Replace the entire contents of the buffer with the given text. */
setText(text: string): Range;
/**
* Replace the current buffer contents by applying a diff based on the
* given text.
*/
setTextViaDiff(text: string): void;
/** Set the text in the given range. */
setTextInRange(range: RangeCompatible, text: string, options?: TextEditOptions): Range;
/** Insert text at the given position. */
insert(position: PointCompatible, text: string, options?: TextEditOptions): Range;
/** Append text to the end of the buffer. */
append(text: string, options?: TextEditOptions): Range;
/** Delete the text in the given range. */
delete(range: RangeCompatible): Range;
/**
* Delete the line associated with a specified 0-indexed row.
* @param row A number representing the row to delete.
*/
deleteRow(row: number): Range;
/**
* Delete the lines associated with the specified 0-indexed row range.
*
* If the row range is out of bounds, it will be clipped. If the `startRow`
* is greater than the `endRow`, they will be reordered.
*/
deleteRows(startRow: number, endRow: number): Range;
// Markers
/** Create a layer to contain a set of related markers. */
addMarkerLayer(options?: { maintainHistory?: boolean | undefined; persistent?: boolean | undefined; role?: string | undefined }): MarkerLayer;
/**
* Get a MarkerLayer by id.
* Returns a MarkerLayer or undefined if no layer exists with the given id.
*/
getMarkerLayer(id: string): MarkerLayer | undefined;
/** Get the default MarkerLayer. */
getDefaultMarkerLayer(): MarkerLayer;
/** Create a marker with the given range in the default marker layer. */
markRange(
range: RangeCompatible,
properties?: {
reversed?: boolean | undefined;
invalidate?: 'never' | 'surround' | 'overlap' | 'inside' | 'touch' | undefined;
exclusive?: boolean | undefined;
},
): Marker;
/** Create a marker at the given position with no tail in the default marker layer. */
markPosition(
position: PointCompatible,
options?: {
invalidate?: 'never' | 'surround' | 'overlap' | 'inside' | 'touch' | undefined;
exclusive?: boolean | undefined;
},
): Marker;
/** Get all existing markers on the default marker layer. */
getMarkers(): Marker[];
/** Get an existing marker by its id from the default marker layer. */
getMarker(id: number): Marker;
/** Find markers conforming to the given parameters in the default marker layer. */
findMarkers(params: FindMarkerOptions): Marker[];
/** Get the number of markers in the default marker layer. */
getMarkerCount(): number;
// History
/**
* Undo the last operation. If a transaction is in progress, aborts it.
* @return A boolean of whether or not a change was made.
*/
undo(options?: HistoryTraversalOptions): boolean;
/**
* Redo the last operation.
* @return A boolean of whether or not a change was made.
*/
redo(options?: HistoryTraversalOptions): boolean;
/** Batch multiple operations as a single undo/redo step. */
transact<T>(
optionsOrInterval: number | ({ groupingInterval?: number | undefined } & HistoryTransactionOptions),
fn: () => T,
): T;
/** Batch multiple operations as a single undo/redo step. */
transact<T>(fn: () => T): T;
/**
* Abort the currently running transaction.
*
* Only intended to be called within the `fn` option to `::transact`.
*/
abortTransaction(): void;
/** Clear the undo stack. */
clearUndoStack(): void;
/**
* Create a pointer to the current state of the buffer for use with
* `::revertToCheckpoint` and `::groupChangesSinceCheckpoint`.
* @return A checkpoint ID value.
*/
createCheckpoint(options?: HistoryTransactionOptions): number;
/**
* Revert the buffer to the state it was in when the given checkpoint was created.
* @return A boolean indicating whether the operation succeeded.
*/
revertToCheckpoint(checkpoint: number, options?: HistoryTraversalOptions): boolean;
/**
* Group all changes since the given checkpoint into a single transaction for
* purposes of undo/redo.
* @return A boolean indicating whether the operation succeeded.
*/
groupChangesSinceCheckpoint(checkpoint: number, options?: HistoryTransactionOptions): boolean;
/**
* Group the last two text changes for purposes of undo/redo.
*
* This operation will only succeed if there are two changes on the undo stack.
* It will not group past the beginning of an open transaction.
* @return A boolean indicating whether the operation succeeded.
*/
groupLastChanges(): boolean;
/**
* Returns a list of changes since the given checkpoint.
* If the given checkpoint is no longer present in the undo history, this method
* will return an empty Array.
*/
getChangesSinceCheckpoint(
checkpoint: number,
): Array<{
/** A Point representing where the change started. */
start: Point;
/** A Point representing the replaced extent. */
oldExtent: Point;
/** A Point representing the replacement extent. */
newExtent: Point;
/** A String representing the replacement text. */
newText: string;
}>;
// Search and Replace
/**
* Scan regular expression matches in the entire buffer, calling the given
* iterator function on each match.
*/
scan(regex: RegExp, iterator: (params: BufferScanResult) => void): void;
/**
* Scan regular expression matches in the entire buffer, calling the given
* iterator function on each match.
*/
scan(regex: RegExp, options: ScanContextOptions, iterator: (params: ContextualBufferScanResult) => void): void;
/**
* Scan regular expression matches in the entire buffer in reverse order,
* calling the given iterator function on each match.
*/
backwardsScan(regex: RegExp, iterator: (params: BufferScanResult) => void): void;
/**
* Scan regular expression matches in the entire buffer in reverse order,
* calling the given iterator function on each match.
*/
backwardsScan(
regex: RegExp,
options: ScanContextOptions,
iterator: (params: ContextualBufferScanResult) => void,
): void;
/**
* Scan regular expression matches in a given range , calling the given
* iterator function on each match.
*/
scanInRange(regex: RegExp, range: RangeCompatible, iterator: (params: BufferScanResult) => void): void;
/**
* Scan regular expression matches in a given range , calling the given
* iterator function on each match.
*/
scanInRange(
regex: RegExp,
range: RangeCompatible,
options: ScanContextOptions,
iterator: (params: ContextualBufferScanResult) => void,
): void;
/**
* Scan regular expression matches in a given range in reverse order,
* calling the given iterator function on each match.
*/
backwardsScanInRange(regex: RegExp, range: RangeCompatible, iterator: (params: BufferScanResult) => void): void;
/**
* Scan regular expression matches in a given range in reverse order,
* calling the given iterator function on each match.
*/
backwardsScanInRange(
regex: RegExp,
range: RangeCompatible,
options: ScanContextOptions,
iterator: (params: ContextualBufferScanResult) => void,
): void;
/** Replace all regular expression matches in the entire buffer. */
replace(regex: RegExp, replacementText: string): number;
// Buffer Range Details
/** Get the range spanning from [0, 0] to ::getEndPosition. */
getRange(): Range;
/** Get the number of lines in the buffer. */
getLineCount(): number;
/** Get the last 0-indexed row in the buffer. */
getLastRow(): number;
/** Get the first position in the buffer, which is always [0, 0]. */
getFirstPosition(): Point;
/** Get the maximal position in the buffer, where new text would be appended. */
getEndPosition(): Point;
/** Get the length of the buffer's text. */
getLength(): number;
/** Get the length of the buffer in characters. */
getMaxCharacterIndex(): number;
/**
* Get the range for the given row.
* @param row A number representing a 0-indexed row.
* @param includeNewline A boolean indicating whether or not to include the
* newline, which results in a range that extends to the start of the next line.
* (default: false)
*/
rangeForRow(row: number, includeNewline?: boolean): Range;
/**
* Convert a position in the buffer in row/column coordinates to an absolute
* character offset, inclusive of line ending characters.
*/
characterIndexForPosition(position: PointCompatible): number;
/**
* Convert an absolute character offset, inclusive of newlines, to a position
* in the buffer in row/column coordinates.
*/
positionForCharacterIndex(offset: number): Point;
/** Clip the given range so it starts and ends at valid positions. */
clipRange(range: RangeCompatible): Range;
/** Clip the given point so it is at a valid position in the buffer. */
clipPosition(position: PointCompatible): Point;
// Buffer Operations
/** Save the buffer. */
save(): Promise<void>;
/** Save the buffer at a specific path. */
saveAs(filePath: string): Promise<void>;
/** Reload the buffer's contents from disk. */
reload(): void;
/** Destroy the buffer, even if there are retainers for it. */
destroy(): void;
/** Returns whether or not this buffer is alive. */
isAlive(): boolean;
/** Returns whether or not this buffer has been destroyed. */
isDestroyed(): boolean;
/** Returns whether or not this buffer has a retainer. */
isRetained(): boolean;
/**
* Places a retainer on the buffer, preventing its destruction until the
* final retainer has called ::release().
*/
retain(): TextBuffer;
/**
* Releases a retainer on the buffer, destroying the buffer if there are
* no additional retainers.
*/
release(): TextBuffer;
/** Identifies if the buffer belongs to multiple editors. */
hasMultipleEditors(): boolean;
}
export interface TextBufferFileBackend {
/** A {Function} that returns the {String} path to the file. */
getPath(): string;
/**
* A {Function} that returns a `Readable` stream
* that can be used to load the file's content.
*/
createReadStream(): ReadStream;
/**
* A {Function} that returns a `Writable` stream
* that can be used to save content to the file.
*/
createWriteStream(): WriteStream;
/** A {Function} that returns a {Boolean}, true if the file exists, false otherwise. */
existsSync(): boolean;
/**
* A {Function} that invokes its callback argument
* when the file changes. The method should return a {Disposable} that
* can be used to prevent further calls to the callback.
*/
onDidChange?(callback: () => void): Disposable;
/**
* A {Function} that invokes its callback argument
* when the file is deleted. The method should return a {Disposable} that
* can be used to prevent further calls to the callback.
*/
onDidDelete?(callback: () => void): Disposable;
/**
* A {Function} that invokes its callback argument
* when the file is renamed. The method should return a {Disposable} that
* can be used to prevent further calls to the callback.
*/
onDidRename?(callback: () => void): Disposable;
}
export interface BufferChangingEvent {
/** Range of the old text. */
oldRange: Range;
}
export interface BufferChangedEvent {
/**
* An array of objects summarizing the aggregated changes that occurred
* during the transaction.
*/
changes: Array<{
/**
* The Range of the deleted text in the contents of the buffer as it existed
* before the batch of changes reported by this event.
*/
oldRange: Range;
/** The Range of the inserted text in the current contents of the buffer. */
newRange: Range;
}>;
/** Range of the old text. */
oldRange: Range;
/** Range of the new text. */
newRange: Range;
/** String containing the text that was replaced. */
oldText: string;
/** String containing the text that was inserted. */
newText: string;
}
export interface BufferStoppedChangingEvent {
changes: TextChange[];
}
export interface BufferLoadOptions {
/** The file's encoding. */
encoding?: string | undefined;
/**
* A function that returns a boolean indicating whether the buffer should
* be destroyed if its file is deleted.
*/
shouldDestroyOnFileDelete?(): boolean;
}
export interface BufferScanResult {
buffer: TextBuffer;
lineText: string;
match: RegExpExecArray;
matchText: string;
range: Range;
replace(replacementText: string): void;
stop(): void;
stopped: boolean;
}
export interface ContextualBufferScanResult extends BufferScanResult {
leadingContextLines: string[];
trailingContextLines: string[];
}
export interface ScanContextOptions {
/** The number of lines before the matched line to include in the results object. */
leadingContextLineCount?: number | undefined;
/** The number of lines after the matched line to include in the results object. */
trailingContextLineCount?: number | undefined;
} | the_stack |
declare module 'ui-neumorphism' {
export import Avatar = __UINeumorphism.Avatar
export import Alert = __UINeumorphism.Alert
export import Badge = __UINeumorphism.Badge
export import Fab = __UINeumorphism.Fab
export import Button = __UINeumorphism.Button
export import IconButton = __UINeumorphism.IconButton
export import ToggleButton = __UINeumorphism.ToggleButton
export import ToggleButtonGroup = __UINeumorphism.ToggleButtonGroup
export import Typography = __UINeumorphism.Typography
export import Subtitle2 = __UINeumorphism.Subtitle2
export import Subtitle1 = __UINeumorphism.Subtitle1
export import Overline = __UINeumorphism.Overline
export import Caption = __UINeumorphism.Caption
export import Body2 = __UINeumorphism.Body2
export import Body1 = __UINeumorphism.Body1
export import H6 = __UINeumorphism.H6
export import H5 = __UINeumorphism.H5
export import H4 = __UINeumorphism.H4
export import H3 = __UINeumorphism.H3
export import H2 = __UINeumorphism.H2
export import H1 = __UINeumorphism.H1
export import CardContent = __UINeumorphism.CardContent
export import CardHeader = __UINeumorphism.CardHeader
export import CardAction = __UINeumorphism.CardAction
export import CardMedia = __UINeumorphism.CardMedia
export import Card = __UINeumorphism.Card
// export import List = __UINeumorphism.List
// export import ListItem = __UINeumorphism.ListItem
// export import ListItemGroup = __UINeumorphism.ListItemGroup
export import Chip = __UINeumorphism.Chip
export import TabItems = __UINeumorphism.TabItems
export import TabItem = __UINeumorphism.TabItem
export import Tabs = __UINeumorphism.Tabs
export import Tab = __UINeumorphism.Tab
export import ProgressCircular = __UINeumorphism.ProgressCircular
export import ProgressLinear = __UINeumorphism.ProgressLinear
export import CarouselItem = __UINeumorphism.CarouselItem
export import Carousel = __UINeumorphism.Carousel
export import Parallax = __UINeumorphism.Parallax
export import Tooltip = __UINeumorphism.Tooltip
export import Divider = __UINeumorphism.Divider
export import Spacer = __UINeumorphism.Spacer
export import Dialog = __UINeumorphism.Dialog
export import Table = __UINeumorphism.Table
// export import Form = __UINeumorphism.Form
export import Radio = __UINeumorphism.Radio
export import RadioGroup = __UINeumorphism.RadioGroup
export import TextField = __UINeumorphism.TextField
export import TextArea = __UINeumorphism.TextArea
export import Switch = __UINeumorphism.Switch
// export import Slider = __UINeumorphism.Slider
export import Checkbox = __UINeumorphism.Checkbox
export import Checkbox = __UINeumorphism.Grow
export import Checkbox = __UINeumorphism.Fade
export import Checkbox = __UINeumorphism.Slide
export import Checkbox = __UINeumorphism.SlideCarousel
export import overrideThemeVariables = __UINeumorphism.overrideThemeVariables
}
declare namespace __UINeumorphism {
namespace propTypes {
type sizes = 'small' | 'medium' | 'large'
type position = 'top' | 'right' | 'bottom' | 'left'
type context_color = 'success' | 'info' | 'warning' | 'error'
}
export interface DefaultProps {
dark?: Boolean
className?: String
style?: React.CSSProperties
}
export interface DefaultDimensionProps {
width?: Number
height?: Number
minWidth?: Number
maxWidth?: Number
minHeight?: Number
maxHeight?: Number
}
export interface MouseEvents {
onClick?: Function
onMouseUp?: Function
onMouseOut?: Function
onMouseMove?: Function
onMouseDown?: Function
onMouseOver?: Function
onMouseEnter?: Function
onMouseLeave?: Function
}
// Typography
export interface TypographyTypeProps extends DefaultProps {
component?: String
disabled?: Boolean
secondary?: Boolean
}
export interface TypographyProps extends TypographyTypeProps {
type?: String
}
export class Typography extends React.Component<TypographyProps> {}
export class Subtitle2 extends React.Component<TypographyTypeProps> {}
export class Subtitle1 extends React.Component<TypographyTypeProps> {}
export class Overline extends React.Component<TypographyTypeProps> {}
export class Caption extends React.Component<TypographyTypeProps> {}
export class Body2 extends React.Component<TypographyTypeProps> {}
export class Body1 extends React.Component<TypographyTypeProps> {}
export class H6 extends React.Component<TypographyTypeProps> {}
export class H5 extends React.Component<TypographyTypeProps> {}
export class H4 extends React.Component<TypographyTypeProps> {}
export class H3 extends React.Component<TypographyTypeProps> {}
export class H2 extends React.Component<TypographyTypeProps> {}
export class H1 extends React.Component<TypographyTypeProps> {}
//Card
interface CommonCardProps extends DefaultDimensionProps {
flat?: Boolean
inset?: Boolean
rounded?: Boolean
outlined?: Boolean
bordered?: Boolean
elevation?: Number
}
export interface CardProps extends DefaultProps, CommonCardProps {
loading?: Boolean
disabled?: Boolean
}
export class Card extends React.Component<CardProps> {}
interface CardContentCommonProps {
rounded?: Boolean
disabled?: Boolean
}
export interface CardHeaderProps
extends DefaultProps,
CardContentCommonProps {
title?: React.ReactNode
avatar?: React.ReactNode
action?: React.ReactNode
subtitle?: React.ReactNode
}
export class CardHeader extends React.Component<CardHeaderProps> {}
export interface CardMediaProps extends DefaultProps, CardContentCommonProps {
src?: String
title?: String
height?: Number
}
export class CardMedia extends React.Component<CardMediaProps> {}
export interface CardContentProps
extends DefaultProps,
CardContentCommonProps {}
export class CardContent extends React.Component<CardContentProps> {}
export class CardAction extends React.Component<CardContentProps> {}
// Chip
export interface ChipProps extends DefaultProps {
link?: String
color?: String
flat?: Boolean
label?: Boolean
active?: Boolean
closable?: Boolean
outlined?: Boolean
bordered?: Boolean
onAction?: Function
size?: propTypes.sizes
append?: React.ReactNode
action?: React.ReactNode
prepend?: React.ReactNode
closeIcon?: React.ReactNode
type?: propTypes.context_color
}
export class Chip extends React.Component<ChipProps> {}
// Alert
export interface AlertProps extends DefaultProps, CommonCardProps {
dense?: Boolean
color?: String
closable?: Boolean
icon?: React.ReactNode
closeIcon?: React.ReactNode
border?: propTypes.position
type?: propTypes.context_color
}
export class Alert extends React.Component<AlertProps> {}
// Avatar
export interface AvatarProps extends DefaultProps {
alt?: String
src?: String
color?: String
square?: Boolean
bgColor?: String
rounded?: Boolean
size?: propTypes.sizes | Number
}
export class Avatar extends React.Component<AvatarProps> {}
// Badge
export interface BadgeProps extends DefaultProps {
max?: Number
dot?: Boolean
left?: Boolean
label?: String
color?: String
inline?: Boolean
bottom?: Boolean
square?: Boolean
bgColor?: String
overlap?: Boolean
visible?: Boolean
bordered?: Boolean
noPadding?: Boolean
borderColor?: String
content?: React.ReactNode
}
export class Badge extends React.Component<BadgeProps> {}
// Button
interface CommonButtonProps {
color?: String
bgColor?: String
rounded?: Boolean
noPress?: Boolean
bordered?: Boolean
disabled?: Boolean
size?: propTypes.sizes
}
export interface ButtonProps
extends DefaultProps,
MouseEvents,
CommonButtonProps {
text?: Boolean
block?: Boolean
active?: Boolean
outlined?: Boolean
depressed?: Boolean
}
export class Button extends React.Component<ButtonProps> {}
// Fab
export interface FabProps
extends DefaultProps,
MouseEvents,
CommonButtonProps {
top?: Boolean
left?: Boolean
right?: Boolean
fixed?: Boolean
bottom?: Boolean
absolute?: Boolean
animation?: Boolean
}
export class Fab extends React.Component<FabProps> {}
// IconButton
export interface IconButtonProps
extends DefaultProps,
MouseEvents,
CommonButtonProps {
text?: Boolean
active?: Boolean
outlined?: Boolean
}
export class IconButton extends React.Component<IconButtonProps> {}
// ToggleButton
export interface ToggleButtonProps
extends DefaultProps,
MouseEvents,
CommonButtonProps {
value?: any
text?: Boolean
outlined?: Boolean
selected?: Boolean
}
export class ToggleButton extends React.Component<ToggleButtonProps> {}
export interface ToggleButtonGroupProps extends DefaultProps {
value?: any
multiple?: Boolean
mandatory?: Boolean
}
export class ToggleButtonGroup extends React.Component<
ToggleButtonGroupProps
> {}
// Tabs
export interface TabsProps extends DefaultProps {
value?: Number
color?: String
rounded?: Boolean
disabled?: Boolean
outlined?: Boolean
onClick?: Function
onChange?: Function
underlined?: Boolean
}
export class Tabs extends React.Component<TabsProps> {}
export interface TabProps extends DefaultProps {
onClick?: Function
onMouseOut?: Function
onMouseOver?: Function
}
export class Tab extends React.Component<TabProps> {}
export interface TabItemsProps extends DefaultProps {
value?: Number
height?: Number
reverse?: Boolean
onChange?: Function
}
export class TabItems extends React.Component<TabItemsProps> {}
export class TabItem extends React.Component<DefaultProps> {}
// Progress
interface CommonProgressProps {
value?: Number
color?: String
indeterminate?: Boolean
}
export interface ProgressCircularProps
extends DefaultProps,
CommonProgressProps {
size?: Number
flat?: Boolean
width?: Number
rotate?: Number
label?: String
elevated?: Boolean
}
export class ProgressCircular extends React.Component<
ProgressCircularProps
> {}
export interface ProgressLinearProps
extends DefaultProps,
CommonProgressProps {
height?: Number
active?: Boolean
striped?: Boolean
bordered?: Boolean
fillHeight?: Boolean
}
export class ProgressLinear extends React.Component<ProgressLinearProps> {}
//Carousel
export interface CarouselProps extends DefaultProps {
value?: Number
cycle?: Boolean
height?: Number
reverse?: Boolean
interval?: Number
vertical?: Boolean
onChange: Function
showArrows?: Boolean
continuous?: Boolean
hideDelimiters?: Boolean
nextIcon?: React.ReactNode
prevIcon?: React.ReactNode
showArrowsOnHover?: Boolean
delimiterIcon?: React.ReactNode
activeDelimiterIcon?: React.ReactNode
}
export class Carousel extends React.Component<CarouselProps> {}
export class CarouselItem extends React.Component<DefaultProps> {}
//Parallax
export interface ParallaxProps extends DefaultProps {
alt?: String
src?: String
speed?: Number
height?: Number
containerId?: String
}
export class Parallax extends React.Component<ParallaxProps> {}
//Tooltip
export interface TooltipProps extends DefaultProps, DefaultDimensionProps {
top?: Boolean
left?: Boolean
inset?: Boolean
right?: Boolean
bottom?: Boolean
visible?: Boolean
transitionProps?: Object
content: React.ReactNode
}
export class Tooltip extends React.Component<TooltipProps> {}
//Divider
export interface DividerProps extends DefaultProps {
dense?: Boolean
elevated?: Boolean
}
export class Divider extends React.Component<DividerProps> {}
//Spacer
export class Spacer extends React.Component<DefaultProps> {}
//Dialog
export interface DialogProps extends DefaultProps, DefaultDimensionProps {
visible?: Boolean
onClose?: Function
persistent?: Boolean
}
export class Dialog extends React.Component<DialogProps> {}
//Table
export interface TableProps extends DefaultProps {
flat?: Boolean
items?: Array
dense?: Boolean
headers?: Array
outlined?: Boolean
noHeaders?: Boolean
actions?: React.ReactNode
description?: React.ReactNode
}
export class Table extends React.Component<TableProps> {}
//SelectionControl
interface CommonSelectionControlProps {
value?: any
id?: String
color?: String
disabled?: Boolean
onChange?: Function
}
interface SelectionControlProps
extends MouseEvents,
CommonSelectionControlProps {
name?: String
label?: String
checked?: Boolean
required?: Boolean
}
//Radio
export interface RadioProps extends DefaultProps, SelectionControlProps {}
export class Radio extends React.Component<RadioProps> {}
//RadioGroup
export interface RadioGroupProps
extends DefaultProps,
CommonSelectionControlProps {
vertical?: Boolean
onChange?: Function
children: React.ReactNode
}
export class RadioGroup extends React.Component<RadioGroupProps> {}
//Switch
export interface SwitchProps extends DefaultProps, SelectionControlProps {}
export class Switch extends React.Component<SwitchProps> {}
//Checkbox
export interface CheckboxProps extends DefaultProps, SelectionControlProps {}
export class Checkbox extends React.Component<CheckboxProps> {}
//TextField
export interface TextFieldProps extends DefaultProps {
id?: String
name?: String
type?: String
hint?: String
rules?: Array
value?: String
width?: Number
dense?: Boolean
height?: Number
counter?: Number
rounded?: Boolean
loading?: Boolean
readonly?: Boolean
disabled?: Boolean
outlined?: Boolean
bordered?: Boolean
autofocus?: Boolean
clearable?: Boolean
hideExtra?: Boolean
uncontrolled?: Boolean
placeholder?: String
onBlur?: Function
onFocus?: Function
onInput?: Function
onKeyUp?: Function
onChange?: Function
onKeyDown?: Function
label?: React.ReactNode
append?: React.ReactNode
prepend?: React.ReactNode
inputStyles?: React.CSSProperties
}
export class TextField extends React.Component<TextFieldProps> {}
//TextArea
export interface TextAreaProps extends TextFieldProps {
autoExpand?: Boolean
}
export class TextArea extends React.Component<TextAreaProps> {}
// Transitions
export interface TransitionProps {
duration?: Number
}
export class Fade extends React.Component<TransitionProps> {}
export interface GrowProps extends TransitionProps {
origin?: Number
}
export class Grow extends React.Component<GrowProps> {}
export interface SlideProps extends GrowProps {
axis?: String
reverse?: Boolean
}
export class Slide extends React.Component<SlideProps> {}
export class SlideCarousel extends React.Component<SlideProps> {}
// Functions
export function overrideThemeVariables(themeObject: Object) {}
} | the_stack |
import glob from "glob";
import { kebabCase, memoize, noop } from "lodash/fp";
import type { DiContainer } from "@ogre-tools/injectable";
import { createContainer } from "@ogre-tools/injectable";
import { Environments, setLegacyGlobalDiForExtensionApi } from "../extensions/as-legacy-globals-for-extension-api/legacy-global-di-for-extension-api";
import appNameInjectable from "./app-paths/app-name/app-name.injectable";
import registerChannelInjectable from "./app-paths/register-channel/register-channel.injectable";
import writeJsonFileInjectable from "../common/fs/write-json-file.injectable";
import readJsonFileInjectable from "../common/fs/read-json-file.injectable";
import readFileInjectable from "../common/fs/read-file.injectable";
import directoryForBundledBinariesInjectable from "../common/app-paths/directory-for-bundled-binaries/directory-for-bundled-binaries.injectable";
import loggerInjectable from "../common/logger.injectable";
import spawnInjectable from "./child-process/spawn.injectable";
import extensionsStoreInjectable from "../extensions/extensions-store/extensions-store.injectable";
import type { ExtensionsStore } from "../extensions/extensions-store/extensions-store";
import fileSystemProvisionerStoreInjectable from "../extensions/extension-loader/file-system-provisioner-store/file-system-provisioner-store.injectable";
import type { FileSystemProvisionerStore } from "../extensions/extension-loader/file-system-provisioner-store/file-system-provisioner-store";
import clusterStoreInjectable from "../common/cluster-store/cluster-store.injectable";
import type { ClusterStore } from "../common/cluster-store/cluster-store";
import type { Cluster } from "../common/cluster/cluster";
import userStoreInjectable from "../common/user-store/user-store.injectable";
import type { UserStore } from "../common/user-store";
import getAbsolutePathInjectable from "../common/path/get-absolute-path.injectable";
import { getAbsolutePathFake } from "../common/test-utils/get-absolute-path-fake";
import joinPathsInjectable from "../common/path/join-paths.injectable";
import { joinPathsFake } from "../common/test-utils/join-paths-fake";
import hotbarStoreInjectable from "../common/hotbars/store.injectable";
import type { GetDiForUnitTestingOptions } from "../test-utils/get-dis-for-unit-testing";
import isAutoUpdateEnabledInjectable from "./is-auto-update-enabled.injectable";
import appEventBusInjectable from "../common/app-event-bus/app-event-bus.injectable";
import { EventEmitter } from "../common/event-emitter";
import type { AppEvent } from "../common/app-event-bus/event-bus";
import commandLineArgumentsInjectable from "./utils/command-line-arguments.injectable";
import initializeExtensionsInjectable from "./start-main-application/runnables/initialize-extensions.injectable";
import lensResourcesDirInjectable from "../common/vars/lens-resources-dir.injectable";
import registerFileProtocolInjectable from "./electron-app/features/register-file-protocol.injectable";
import environmentVariablesInjectable from "../common/utils/environment-variables.injectable";
import setupIpcMainHandlersInjectable from "./electron-app/runnables/setup-ipc-main-handlers/setup-ipc-main-handlers.injectable";
import setupLensProxyInjectable from "./start-main-application/runnables/setup-lens-proxy.injectable";
import setupRunnablesForAfterRootFrameIsReadyInjectable from "./start-main-application/runnables/setup-runnables-for-after-root-frame-is-ready.injectable";
import setupSentryInjectable from "./start-main-application/runnables/setup-sentry.injectable";
import setupShellInjectable from "./start-main-application/runnables/setup-shell.injectable";
import setupSyncingOfWeblinksInjectable from "./start-main-application/runnables/setup-syncing-of-weblinks.injectable";
import stopServicesAndExitAppInjectable from "./stop-services-and-exit-app.injectable";
import trayInjectable from "./tray/tray.injectable";
import applicationMenuInjectable from "./menu/application-menu.injectable";
import isDevelopmentInjectable from "../common/vars/is-development.injectable";
import setupSystemCaInjectable from "./start-main-application/runnables/setup-system-ca.injectable";
import setupDeepLinkingInjectable from "./electron-app/runnables/setup-deep-linking.injectable";
import exitAppInjectable from "./electron-app/features/exit-app.injectable";
import getCommandLineSwitchInjectable from "./electron-app/features/get-command-line-switch.injectable";
import requestSingleInstanceLockInjectable from "./electron-app/features/request-single-instance-lock.injectable";
import disableHardwareAccelerationInjectable from "./electron-app/features/disable-hardware-acceleration.injectable";
import shouldStartHiddenInjectable from "./electron-app/features/should-start-hidden.injectable";
import getElectronAppPathInjectable from "./app-paths/get-electron-app-path/get-electron-app-path.injectable";
import setElectronAppPathInjectable from "./app-paths/set-electron-app-path/set-electron-app-path.injectable";
import setupMainWindowVisibilityAfterActivationInjectable from "./electron-app/runnables/setup-main-window-visibility-after-activation.injectable";
import setupDeviceShutdownInjectable from "./electron-app/runnables/setup-device-shutdown.injectable";
import setupApplicationNameInjectable from "./electron-app/runnables/setup-application-name.injectable";
import setupRunnablesBeforeClosingOfApplicationInjectable from "./electron-app/runnables/setup-runnables-before-closing-of-application.injectable";
import showMessagePopupInjectable from "./electron-app/features/show-message-popup.injectable";
import clusterFramesInjectable from "../common/cluster-frames.injectable";
import type { ClusterFrameInfo } from "../common/cluster-frames";
import { observable } from "mobx";
import waitForElectronToBeReadyInjectable from "./electron-app/features/wait-for-electron-to-be-ready.injectable";
import setupListenerForCurrentClusterFrameInjectable from "./start-main-application/lens-window/current-cluster-frame/setup-listener-for-current-cluster-frame.injectable";
import ipcMainInjectable from "./app-paths/register-channel/ipc-main/ipc-main.injectable";
import createElectronWindowForInjectable from "./start-main-application/lens-window/application-window/create-electron-window-for.injectable";
import setupRunnablesAfterWindowIsOpenedInjectable from "./electron-app/runnables/setup-runnables-after-window-is-opened.injectable";
import sendToChannelInElectronBrowserWindowInjectable from "./start-main-application/lens-window/application-window/send-to-channel-in-electron-browser-window.injectable";
import broadcastMessageInjectable from "../common/ipc/broadcast-message.injectable";
import getElectronThemeInjectable from "./electron-app/features/get-electron-theme.injectable";
import syncThemeFromOperatingSystemInjectable from "./electron-app/features/sync-theme-from-operating-system.injectable";
import platformInjectable from "../common/vars/platform.injectable";
export function getDiForUnitTesting(opts: GetDiForUnitTestingOptions = {}) {
const {
doGeneralOverrides = false,
} = opts;
const di = createContainer();
setLegacyGlobalDiForExtensionApi(di, Environments.main);
for (const filePath of getInjectableFilePaths()) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const injectableInstance = require(filePath).default;
di.register({
...injectableInstance,
aliases: [injectableInstance, ...(injectableInstance.aliases || [])],
});
}
di.preventSideEffects();
if (doGeneralOverrides) {
di.override(hotbarStoreInjectable, () => ({ load: () => {} }));
di.override(userStoreInjectable, () => ({ startMainReactions: () => {} }) as UserStore);
di.override(extensionsStoreInjectable, () => ({ isEnabled: (opts) => (void opts, false) }) as ExtensionsStore);
di.override(clusterStoreInjectable, () => ({ getById: (id) => (void id, {}) as Cluster }) as ClusterStore);
di.override(fileSystemProvisionerStoreInjectable, () => ({}) as FileSystemProvisionerStore);
overrideOperatingSystem(di);
overrideRunnablesHavingSideEffects(di);
overrideElectronFeatures(di);
di.override(isDevelopmentInjectable, () => false);
di.override(environmentVariablesInjectable, () => ({}));
di.override(commandLineArgumentsInjectable, () => []);
di.override(clusterFramesInjectable, () => observable.map<string, ClusterFrameInfo>());
di.override(stopServicesAndExitAppInjectable, () => () => {});
di.override(lensResourcesDirInjectable, () => "/irrelevant");
di.override(trayInjectable, () => ({ start: () => {}, stop: () => {} }));
di.override(applicationMenuInjectable, () => ({ start: () => {}, stop: () => {} }));
// TODO: Remove usages of globally exported appEventBus to get rid of this
di.override(appEventBusInjectable, () => new EventEmitter<[AppEvent]>());
di.override(appNameInjectable, () => "some-app-name");
di.override(registerChannelInjectable, () => () => undefined);
di.override(directoryForBundledBinariesInjectable, () => "some-bin-directory");
di.override(broadcastMessageInjectable, () => (channel) => {
throw new Error(`Tried to broadcast message to channel "${channel}" over IPC without explicit override.`);
});
di.override(spawnInjectable, () => () => {
return {
stderr: { on: jest.fn(), removeAllListeners: jest.fn() },
stdout: { on: jest.fn(), removeAllListeners: jest.fn() },
on: jest.fn(),
} as never;
});
di.override(writeJsonFileInjectable, () => () => {
throw new Error("Tried to write JSON file to file system without specifying explicit override.");
});
di.override(readJsonFileInjectable, () => () => {
throw new Error("Tried to read JSON file from file system without specifying explicit override.");
});
di.override(readFileInjectable, () => () => {
throw new Error("Tried to read file from file system without specifying explicit override.");
});
di.override(loggerInjectable, () => ({
warn: noop,
debug: noop,
error: noop,
info: noop,
silly: noop,
}));
}
return di;
}
const getInjectableFilePaths = memoize(() => [
...glob.sync("./**/*.injectable.{ts,tsx}", { cwd: __dirname }),
...glob.sync("../extensions/**/*.injectable.{ts,tsx}", { cwd: __dirname }),
...glob.sync("../common/**/*.injectable.{ts,tsx}", { cwd: __dirname }),
]);
// TODO: Reorganize code in Runnables to get rid of requirement for override
const overrideRunnablesHavingSideEffects = (di: DiContainer) => {
[
initializeExtensionsInjectable,
setupIpcMainHandlersInjectable,
setupLensProxyInjectable,
setupRunnablesForAfterRootFrameIsReadyInjectable,
setupSentryInjectable,
setupShellInjectable,
setupSyncingOfWeblinksInjectable,
setupSystemCaInjectable,
setupListenerForCurrentClusterFrameInjectable,
setupRunnablesAfterWindowIsOpenedInjectable,
].forEach((injectable) => {
di.override(injectable, () => ({ run: () => {} }));
});
};
const overrideOperatingSystem = (di: DiContainer) => {
di.override(platformInjectable, () => "darwin");
di.override(getAbsolutePathInjectable, () => getAbsolutePathFake);
di.override(joinPathsInjectable, () => joinPathsFake);
};
const overrideElectronFeatures = (di: DiContainer) => {
di.override(setupMainWindowVisibilityAfterActivationInjectable, () => ({
run: () => {},
}));
di.override(setupDeviceShutdownInjectable, () => ({
run: () => {},
}));
di.override(setupDeepLinkingInjectable, () => ({ run: () => {} }));
di.override(exitAppInjectable, () => () => {});
di.override(setupApplicationNameInjectable, () => ({ run: () => {} }));
di.override(setupRunnablesBeforeClosingOfApplicationInjectable, () => ({ run: () => {} }));
di.override(getCommandLineSwitchInjectable, () => () => "irrelevant");
di.override(requestSingleInstanceLockInjectable, () => () => true);
di.override(disableHardwareAccelerationInjectable, () => () => {});
di.override(shouldStartHiddenInjectable, () => true);
di.override(showMessagePopupInjectable, () => () => {});
di.override(waitForElectronToBeReadyInjectable, () => () => Promise.resolve());
di.override(ipcMainInjectable, () => ({}));
di.override(getElectronThemeInjectable, () => () => "dark");
di.override(syncThemeFromOperatingSystemInjectable, () => ({ start: () => {}, stop: () => {} }));
di.override(createElectronWindowForInjectable, () => () => async () => ({
show: () => {},
close: () => {},
send: (arg) => {
const sendFake = di.inject(sendToChannelInElectronBrowserWindowInjectable) as any;
sendFake(null, arg);
},
}));
di.override(
getElectronAppPathInjectable,
() => (name: string) => `some-electron-app-path-for-${kebabCase(name)}`,
);
di.override(setElectronAppPathInjectable, () => () => {});
di.override(isAutoUpdateEnabledInjectable, () => () => false);
di.override(registerFileProtocolInjectable, () => () => {});
}; | the_stack |
import { Cordova, CordovaProperty, AwesomeCordovaNativePlugin, Plugin } from '@awesome-cordova-plugins/core';
import { Injectable } from '@angular/core';
export interface Licenses {
ios: string;
android: string;
}
export enum BarcodeType {
None = 1,
QRCode = 2,
DataMatrix = 3,
UPCE = 4,
UPCA = 5,
EAN8 = 6,
EAN13 = 7,
Code128 = 8,
Code39 = 9,
ITF = 10,
Aztec = 11,
PDF417 = 12,
}
export enum RecognizerResultState {
empty = 1,
uncertain = 2,
valid = 3,
}
export enum MrtdDocumentType {
Unknown = 1,
IdentityCard = 2,
Passport = 3,
Visa = 4,
GreenCard = 5,
MalaysianPassIMM13P = 6,
}
export enum EudlCountry {
UK = 1,
Germany = 2,
Austria = 3,
Automatic = 4,
}
export enum DocumentFaceDetectorType {
TD1 = 1,
TD2 = 2,
PassportsAndVisas = 3,
}
export enum UsdlKeys {
DocumentType = 0,
StandardVersionNumber = 1,
CustomerFamilyName = 2,
CustomerFirstName = 3,
CustomerFullName = 4,
DateOfBirth = 5,
Sex = 6,
EyeColor = 7,
AddressStreet = 8,
AddressCity = 9,
AddressJurisdictionCode = 10,
AddressPostalCode = 11,
FullAddress = 12,
Height = 13,
HeightIn = 14,
HeightCm = 15,
CustomerMiddleName = 16,
HairColor = 17,
NameSuffix = 18,
AKAFullName = 19,
AKAFamilyName = 20,
AKAGivenName = 21,
AKASuffixName = 22,
WeightRange = 23,
WeightPounds = 24,
WeightKilograms = 25,
CustomerIdNumber = 26,
FamilyNameTruncation = 27,
FirstNameTruncation = 28,
MiddleNameTruncation = 29,
PlaceOfBirth = 30,
AddressStreet2 = 31,
RaceEthnicity = 32,
NamePrefix = 33,
CountryIdentification = 34,
ResidenceStreetAddress = 35,
ResidenceStreetAddress2 = 36,
ResidenceCity = 37,
ResidenceJurisdictionCode = 38,
ResidencePostalCode = 39,
ResidenceFullAddress = 40,
Under18 = 41,
Under19 = 42,
Under21 = 43,
SocialSecurityNumber = 44,
AKASocialSecurityNumber = 45,
AKAMiddleName = 46,
AKAPrefixName = 47,
OrganDonor = 48,
Veteran = 49,
AKADateOfBirth = 50,
IssuerIdentificationNumber = 51,
DocumentExpirationDate = 52,
JurisdictionVersionNumber = 53,
JurisdictionVehicleClass = 54,
JurisdictionRestrictionCodes = 55,
JurisdictionEndorsementCodes = 56,
DocumentIssueDate = 57,
FederalCommercialVehicleCodes = 58,
IssuingJurisdiction = 59,
StandardVehicleClassification = 60,
IssuingJurisdictionName = 61,
StandardEndorsementCode = 62,
StandardRestrictionCode = 63,
JurisdictionVehicleClassificationDescription = 64,
JurisdictionEndorsmentCodeDescription = 65,
JurisdictionRestrictionCodeDescription = 66,
InventoryControlNumber = 67,
CardRevisionDate = 68,
DocumentDiscriminator = 69,
LimitedDurationDocument = 70,
AuditInformation = 71,
ComplianceType = 72,
IssueTimestamp = 73,
PermitExpirationDate = 74,
PermitIdentifier = 75,
PermitIssueDate = 76,
NumberOfDuplicates = 77,
HAZMATExpirationDate = 78,
MedicalIndicator = 79,
NonResident = 80,
UniqueCustomerId = 81,
DataDiscriminator = 82,
DocumentExpirationMonth = 83,
DocumentNonexpiring = 84,
SecurityVersion = 85,
}
export interface ImageExtensionFactors {
upFactor: number;
rightFactor: number;
downFactor: number;
leftFactor: number;
}
export interface Date {
day: string;
month: string;
year: string;
}
export interface DateCtor {
new (nativeDate: Date): Date;
}
export interface Point {
x: string;
y: string;
}
export interface PointCtor {
new (nativePoint: Point): Point;
}
export interface Quadrilateral {
upperLeft: string;
upperRight: string;
lowerLeft: string;
lowerRight: string;
}
export interface QuadrilateralCtor {
new (nativeQuad: Quadrilateral): Quadrilateral;
}
export interface OverlaySettings {
overlaySettingsType: string;
}
export type BarcodeOverlaySettings = OverlaySettings;
export interface BarcodeOverlaySettingsCtor {
new (): BarcodeOverlaySettings;
}
export type DocumentOverlaySettings = OverlaySettings;
export interface DocumentOverlaySettingsCtor {
new (): DocumentOverlaySettings;
}
export interface DocumentVerificationOverlaySettings extends OverlaySettings {
firstSideSplashMessage: string;
secondSideSplashMessage: string;
scanningDoneSplashMessage: string;
firstSideInstructions: string;
secondSideInstructions: string;
glareMessage: string;
}
export interface DocumentVerificationOverlaySettingsCtor {
new (): DocumentVerificationOverlaySettings;
}
export interface BlinkCardOverlaySettings extends OverlaySettings {
glareMessage: string;
}
export interface BlinkCardOverlaySettingsCtor {
new (): BlinkCardOverlaySettings;
}
export interface RecognizerResult {
resultState: RecognizerResultState;
}
export interface RecognizerResultCtor<T extends RecognizerResult> {
new (nativeResult: any): T;
}
export interface Recognizer<T extends RecognizerResult = any> {
recognizerType: string;
result: T;
createResultFromNative(nativeResult: any): T;
}
export interface RecognizerCtor<T extends Recognizer> {
new (): T;
}
export interface RecognizerCollection {
recognizerArray: Recognizer[];
allowMultipleResults: boolean;
// sic
milisecondsBeforeTimeout: number;
}
export interface RecognizerCollectionCtor {
new (recognizerCollection: Recognizer[]): RecognizerCollection;
}
export interface BarcodeRecognizerResult extends RecognizerResult {
barcodeType: BarcodeType;
rawData: string;
stringData: string;
uncertain: boolean;
}
export type BarcodeRecognizerResultCtor = RecognizerResultCtor<BarcodeRecognizerResult>;
export interface BarcodeRecognizer extends Recognizer<BarcodeRecognizerResult> {
autoScaleDetection: boolean;
nullQuietZoneAllowed: boolean;
readCode39AsExtendedData: boolean;
scanAztecCode: boolean;
scanCode128: boolean;
scanCode39: boolean;
scanDataMatrix: boolean;
scanEan13: boolean;
scanEan8: boolean;
scanInverse: boolean;
scanItf: boolean;
scanPdf417: boolean;
scanQrCode: boolean;
scanUncertain: boolean;
scanUpca: boolean;
scanUpce: boolean;
slowerThoroughScan: boolean;
}
export type BarcodeRecognizerCtor = RecognizerCtor<BarcodeRecognizer>;
export interface MrzResult {
documentType: string;
primaryId: string;
secondaryId: string;
issuer: string;
dateOfBirth: Date;
documentNumber: string;
nationality: string;
gender: string;
documentCode: string;
dateOfExpiry: Date;
opt1: string;
opt2: string;
alienNumber: string;
applicationReceiptNumber: string;
immigrantCaseNumber: string;
mrzText: string;
mrzParsed: boolean;
mrzVerified: boolean;
}
export interface SuccessFrameGrabberRecognizerResult extends RecognizerResult {
successFrame: string;
}
export type SuccessFrameGrabberRecognizerResultCtor = RecognizerResultCtor<SuccessFrameGrabberRecognizerResult>;
export interface SuccessFrameGrabberRecognizer extends Recognizer<SuccessFrameGrabberRecognizerResult> {
slaveRecognizer: Recognizer;
createResultFromNative(nativeResult: { slaveRecognizerResult: any }): SuccessFrameGrabberRecognizerResult;
}
export interface SuccessFrameGrabberRecognizerCtor {
new (recognizer: Recognizer): SuccessFrameGrabberRecognizer;
}
export interface AustraliaDlBackRecognizerResult extends RecognizerResult {
address: string;
dateOfExpiry: Date;
fullDocumentImage: string;
lastName: string;
licenseNumber: string;
}
export type AustraliaDlBackRecognizerResultCtor = RecognizerResultCtor<AustraliaDlBackRecognizerResult>;
export interface AustraliaDlBackRecognizer extends Recognizer<AustraliaDlBackRecognizerResult> {
extractAddress: boolean;
extractDateOfBirth: boolean;
extractLastName: boolean;
fullDocumentImageDpi: number;
returnFullDocumentImage: boolean;
}
export type AustraliaDlBackRecognizerCtor = RecognizerCtor<AustraliaDlBackRecognizer>;
export interface AustraliaDlFrontRecognizerResult extends RecognizerResult {
address: string;
dateOfBirth: Date;
dateOfExpiry: Date;
faceImage: string;
fullDocumentImage: string;
licenseNumber: string;
licenseType: string;
name: string;
signatureImage: string;
}
export type AustraliaDlFrontRecognizerResultCtor = RecognizerResultCtor<AustraliaDlFrontRecognizerResult>;
export interface AustraliaDlFrontRecognizer extends Recognizer<AustraliaDlFrontRecognizerResult> {
extractAddress: boolean;
extractDateOfBirth: boolean;
extractDateOfExpiry: boolean;
fullDocumentImageDpi: number;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
returnSignatureImage: boolean;
}
export type AustraliaDlFrontRecognizerCtor = RecognizerCtor<AustraliaDlFrontRecognizer>;
export interface AustriaCombinedRecognizerResult extends RecognizerResult {
dateOfBirth: Date;
dateOfExpiry: Date;
dateOfIssuance: Date;
digitalSignature: string;
digitalSignatureVersion: string;
documentDataMatch: boolean;
documentNumber: string;
eyeColor: string;
faceImage: string;
fullDocumentBackImage: string;
fullDocumentFrontImage: string;
givenName: string;
height: string;
issuingAuthority: string;
mrtdVerified: boolean;
nationality: string;
placeOfBirth: string;
principalResidence: string;
scanningFirstSideDone: boolean;
sex: string;
signatureImage: string;
surname: string;
}
export type AustriaCombinedRecognizerResultCtor = RecognizerResultCtor<AustriaCombinedRecognizerResult>;
export interface AustriaCombinedRecognizer extends Recognizer<AustriaCombinedRecognizerResult> {
detectGlare: boolean;
extractDateOfBirth: boolean;
extractDateOfExpiry: boolean;
extractDateOfIssuance: boolean;
extractDateOfIssue: boolean;
extractGivenName: boolean;
extractHeight: boolean;
extractIssuingAuthority: boolean;
extractNationality: boolean;
extractPassportNumber: boolean;
extractPlaceOfBirth: boolean;
extractPrincipalResidence: boolean;
extractSex: boolean;
extractSurname: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
signResult: boolean;
signatureImageDpi: number;
}
export type AustriaCombinedRecognizerCtor = RecognizerCtor<AustriaCombinedRecognizer>;
export interface AustriaDlFrontRecognizerResult extends RecognizerResult {
dateOfBirth: Date;
dateOfExpiry: Date;
dateOfIssue: Date;
faceImage: string;
firstName: string;
fullDocumentImage: string;
issuingAuthority: string;
licenseNumber: string;
name: string;
placeOfBirth: string;
signatureImage: string;
vehicleCategories: string;
}
export type AustriaDlFrontRecognizerResultCtor = RecognizerResultCtor<AustriaDlFrontRecognizerResult>;
export interface AustriaDlFrontRecognizer extends Recognizer<AustriaDlFrontRecognizerResult> {
detectGlare: boolean;
extractDateOfBirth: boolean;
extractDateOfExpiry: boolean;
extractDateOfIssue: boolean;
extractFirstName: boolean;
extractIssuingAuthority: boolean;
extractName: boolean;
extractPlaceOfBirth: boolean;
extractVehicleCategories: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
returnSignatureImage: boolean;
signatureImageDpi: number;
}
export type AustriaDlFrontRecognizerCtor = RecognizerCtor<AustriaDlFrontRecognizer>;
export interface AustriaIdBackRecognizerResult extends RecognizerResult {
dateOfIssuance: Date;
documentNumber: string;
eyeColor: string;
fullDocumentImage: string;
height: string;
issuingAuthority: string;
mrzResult: MrzResult;
placeOfBirth: string;
principalResidence: string;
}
export type AustriaIdBackRecognizerResultCtor = RecognizerResultCtor<AustriaIdBackRecognizerResult>;
export interface AustriaIdBackRecognizer extends Recognizer<AustriaIdBackRecognizerResult> {
detectGlare: boolean;
extractDateOfIssuance: boolean;
extractHeight: boolean;
extractIssuingAuthority: boolean;
extractPlaceOfBirth: boolean;
extractPrincipalResidence: boolean;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFullDocumentImage: boolean;
}
export type AustriaIdBackRecognizerCtor = RecognizerCtor<AustriaIdBackRecognizer>;
export interface AustriaIdFrontRecognizerResult extends RecognizerResult {
dateOfBirth: Date;
documentNumber: string;
faceImage: string;
fullDocumentImage: string;
givenName: string;
sex: string;
signatureImage: string;
surname: string;
}
export type AustriaIdFrontRecognizerResultCtor = RecognizerResultCtor<AustriaIdBackRecognizerResult>;
export interface AustriaIdFrontRecognizer extends Recognizer<AustriaIdFrontRecognizerResult> {
detectGlare: boolean;
extractDateOfBirth: boolean;
extractGivenName: boolean;
extractSex: boolean;
extractSurname: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnSignatureImage: boolean;
signatureImageDpi: number;
}
export type AustriaIdFrontRecognizerCtor = RecognizerCtor<AustriaIdFrontRecognizer>;
export interface AustriaPassportRecognizerResult extends RecognizerResult {
dateOfBirth: Date;
dateOfExpiry: Date;
dateOfIssuance: Date;
faceImage: string;
fullDocumentImage: string;
givenName: string;
height: string;
issuingAuthority: string;
mrzResult: MrzResult;
nationality: string;
passportNumber: string;
placeOfBirth: string;
sex: string;
signatureImage: string;
surname: string;
}
export type AustriaPassportRecognizerResultCtor = RecognizerResultCtor<AustriaPassportRecognizerResult>;
export interface AustriaPassportRecognizer extends Recognizer<AustriaPassportRecognizerResult> {
detectGlare: boolean;
extractDateOfBirth: boolean;
extractDateOfExpiry: boolean;
extractDateOfIssue: boolean;
extractGivenName: boolean;
extractHeight: boolean;
extractIssuingAuthority: boolean;
extractNationality: boolean;
extractPassportNumber: boolean;
extractPlaceOfBirth: boolean;
extractSex: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
returnSignatureImage: boolean;
signatureImageDpi: number;
}
export type AustriaPassportRecognizerCtor = RecognizerCtor<AustriaPassportRecognizer>;
export interface ColombiaDlFrontRecognizerResult extends RecognizerResult {
dateOfBirth: Date;
dateOfIssue: Date;
driverRestrictions: string;
faceImage: string;
fullDocumentImage: string;
issuingAgency: string;
licenseNumber: string;
name: string;
}
export type ColombiaDlFrontRecognizerResultCtor = RecognizerResultCtor<ColombiaDlFrontRecognizerResult>;
export interface ColombiaDlFrontRecognizer extends Recognizer<ColombiaDlFrontRecognizerResult> {
detectGlare: boolean;
extractDateOfBirth: boolean;
extractDriverRestrictions: boolean;
extractIssuingAgency: boolean;
extractName: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
}
export interface ColombiaIdBackRecognizerResult extends RecognizerResult {
birthDate: Date;
bloodGroup: string;
documentNumber: string;
fingerprint: string;
firstName: string;
fullDocumentImage: string;
lastName: string;
sex: string;
}
export type ColombiaIdBackRecognizerResultCtor = Recognizer<ColombiaIdBackRecognizerResult>;
export interface ColombiaIdBackRecognizer extends Recognizer<ColombiaIdBackRecognizerResult> {
detectGlare: boolean;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
nullQuietZoneAllowed: boolean;
returnFullDocumentImage: boolean;
scanUncertain: boolean;
}
export type ColombiaIdBackRecognizerCtor = RecognizerCtor<ColombiaIdBackRecognizer>;
export interface ColombiaIdFrontRecognizerResult extends RecognizerResult {
documentNumber: string;
faceImage: string;
firstName: string;
fullDocumentImage: string;
lastName: string;
signatureImage: string;
}
export type ColombiaIdFrontRecognizerResultCtor = Recognizer<ColombiaIdFrontRecognizerResult>;
export interface ColombiaIdFrontRecognizer extends Recognizer<ColombiaIdFrontRecognizerResult> {
detectGlare: boolean;
extractFirstName: boolean;
extractLastName: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
returnSignatureImage: boolean;
signatureImageDpi: number;
}
export type ColombiaIdFrontRecognizerCtor = RecognizerCtor<ColombiaIdFrontRecognizer>;
export interface CroatiaCombinedRecognizerResult extends RecognizerResult {
address: string;
citizenship: string;
dateOfBirth: Date;
dateOfExpiry: Date;
dateOfExpiryPermanent: Date;
dateOfIssue: Date;
digitalSignature: string;
digitalSignatureVersion: string;
documentBilingual: boolean;
documentDataMatch: string;
faceImage: string;
firstName: string;
fullDocumentBackImage: string;
fullDocumentFrontImage: string;
identityCardNumber: string;
issuingAuthority: string;
lastName: string;
mrzVerified: boolean;
nonResident: boolean;
personalIdentificationNumber: string;
scanningFirstSideDone: boolean;
sex: string;
signatureImage: string;
}
export type CroatiaCombinedRecognizerResultCtor = RecognizerResultCtor<CroatiaCombinedRecognizerResult>;
export interface CroatiaCombinedRecognizer extends Recognizer<CroatiaCombinedRecognizerResult> {
detectGlare: boolean;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
returnSignatureImage: boolean;
signResult: boolean;
}
export interface CroatiaIdBackRecognizerResult extends RecognizerResult {
dateOfExpiryPermanent: boolean;
dateOfIssue: Date;
documentForNonResident: boolean;
fullDocumentImage: string;
issuedBy: string;
mrzResult: MrzResult;
residence: string;
}
export type CroatiaIdBackRecognizerResultCtor = RecognizerResultCtor<CroatiaIdBackRecognizerResult>;
export interface CroatiaIdBackRecognizer extends Recognizer<CroatiaIdBackRecognizerResult> {
detectGlare: boolean;
extractDateOfIssue: boolean;
extractIssuedBy: boolean;
extractResidence: boolean;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFullDocumentImage: boolean;
}
export interface CroatiaIdFrontRecognizerResult extends RecognizerResult {
citizenship: string;
dateOfBirth: Date;
dateOfExpiry: Date;
dateOfExpiryPermanent: boolean;
documentBilingual: boolean;
documentNumber: string;
faceImage: string;
firstName: string;
fullDocumentImage: string;
lastName: string;
sex: string;
signatureImage: string;
}
export type CroatiaIdFrontRecognizerResultCtor = RecognizerResultCtor<CroatiaIdFrontRecognizerResult>;
export interface CroatiaIdFrontRecognizer extends Recognizer<CroatiaIdFrontRecognizerResult> {
detectGlare: boolean;
extractCitizenship: boolean;
extractDateOfBirth: boolean;
extractDateOfExpiry: boolean;
extractFirstName: boolean;
extractLastName: boolean;
extractSex: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
returnSignatureImage: boolean;
signatureImageDpi: number;
}
export interface CyprusIdBackRecognizerResult extends RecognizerResult {
dateOfBirth: Date;
expiresOn: Date;
fullDocumentImage: string;
sex: string;
}
export type CyprusIdBackRecognizerResultCtor = RecognizerResultCtor<CyprusIdBackRecognizerResult>;
export interface CyprusIdBackRecognizer extends Recognizer<CyprusIdBackRecognizerResult> {
detectGlare: boolean;
extractExpiresOn: boolean;
extractSex: boolean;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFullDocumentImage: boolean;
}
export type CyprusIdBackRecognizerCtor = RecognizerCtor<CyprusIdBackRecognizer>;
export interface CyprusIdFrontRecognizerResult extends RecognizerResult {
documentNumber: string;
faceImage: string;
fullDocumentImage: string;
idNumber: string;
name: string;
surname: string;
}
export type CyprusIdFrontRecognizerResultCtor = RecognizerResultCtor<CyprusIdFrontRecognizerResult>;
export interface CyprusIdFrontRecognizer extends Recognizer<CyprusIdFrontRecognizerResult> {
detectGlare: boolean;
extractDocumentNumber: boolean;
extractName: boolean;
extractSurname: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
}
export type CyprusIdFrontRecognizerCtor = RecognizerCtor<CyprusIdFrontRecognizer>;
export interface CzechiaCombinedRecognizerResult extends RecognizerResult {
address: string;
dateOfBirth: Date;
dateOfExpiry: Date;
dateOfIssue: Date;
digitalSignature: string;
digitalSignatureVersion: string;
documentDataMatch: boolean;
faceImage: string;
firstName: string;
fullDocumentBackImage: string;
fullDocumentFrontImage: string;
identityCardNumber: string;
issuingAuthority: string;
lastName: string;
mrzVerified: boolean;
nationality: string;
personalIdentificationNumber: string;
placeOfBirth: string;
scanningFirstSideDone: boolean;
sex: string;
signatureImage: string;
}
export type CzechiaCombinedRecognizerResultCtor = RecognizerResultCtor<CzechiaCombinedRecognizerResult>;
export interface CzechiaCombinedRecognizer extends Recognizer<CzechiaCombinedRecognizerResult> {
detectGlare: boolean;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
signResult: boolean;
}
export interface CzechiaIdBackRecognizerResult extends RecognizerResult {
authority: string;
dateOfBirth: Date;
dateOfExpiry: Date;
documentCode: string;
documentNumber: string;
fullDocumentImage: string;
issuer: string;
mrzParsed: boolean;
mrzText: string;
mrzVerified: boolean;
nationality: string;
opt1: string;
opt2: string;
permanentStay: string;
personalNumber: string;
primaryId: string;
secondaryId: string;
sex: string;
}
export type CzechiaIdBackRecognizerResultCtor = RecognizerResultCtor<CzechiaIdBackRecognizerResult>;
export interface CzechiaIdBackRecognizer extends Recognizer<CzechiaIdBackRecognizerResult> {
detectGlare: boolean;
extractAuthority: boolean;
extractPermanentStay: boolean;
extractPersonalNumber: boolean;
returnFullDocumentImage: boolean;
}
export interface CyprusIdFrontRecognizerResult extends RecognizerResult {
dateOfBirth: Date;
dateOfExpiry: Date;
dateOfIssue: Date;
faceImage: string;
firstName: string;
fullDocumentImage: string;
identityCardNumber: string;
lastName: string;
placeOfBirth: string;
sex: string;
signatureImage: string;
}
export type CyprusIdFrontRecognizerResultCtor = RecognizerResultCtor<CyprusIdFrontRecognizerResult>;
export interface CyprusIdFrontRecognizer extends Recognizer<CyprusIdFrontRecognizerResult> {
detectGlare: boolean;
extractDateOfBirth: boolean;
extractDateOfExpiry: boolean;
extractDateOfIssue: boolean;
extractGivenNames: boolean;
extractPlaceOfBirth: boolean;
extractSex: boolean;
extractSurname: boolean;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
returnSignatureImage: boolean;
}
export type CyprusIdFrontRecognizerCtor = RecognizerCtor<CyprusIdFrontRecognizer>;
export interface DocumentFaceRecognizerResult extends RecognizerResult {
documentLocation: string;
faceImage: string;
faceLocation: Quadrilateral;
fullDocumentImage: string;
}
export type DocumentFaceRecognizerResultCtor = RecognizerResultCtor<DocumentFaceRecognizerResult>;
export interface DocumentFaceRecognizer extends Recognizer<DocumentFaceRecognizerResult> {
detectorType: DocumentFaceDetectorType.TD1;
faceImageDpi: number;
fullDocumentImage: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
numStableDetectionsThreshold: number;
returnFaceImage: boolean;
}
export interface EgyptIdFrontRecognizerResult extends RecognizerResult {
documentNumber: string;
faceImage: string;
fullDocumentImage: string;
nationalNumber: string;
}
export type EgyptIdFrontRecognizerResultCtor = RecognizerResultCtor<EgyptIdFrontRecognizerResult>;
export interface EgyptIdFrontRecognizer extends Recognizer<EgyptIdFrontRecognizerResult> {
detectGlare: boolean;
extractNationalNumber: boolean;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
}
export type EgyptIdFrontRecognizerCtor = RecognizerCtor<EgyptIdFrontRecognizer>;
export interface BlinkCardEliteRecognizerResult extends RecognizerResult {
cardNumber: string;
cvv: string;
digitalSignature: string;
digitalSignatureVersion: string;
documentDataMatch: boolean;
fullDocumentBackImage: string;
fullDocumentFrontImage: string;
inventoryNumber: string;
owner: string;
scanningFirstSideDone: boolean;
validThru: Date;
}
export type BlinkCardEliteRecognizerResultCtor = RecognizerResultCtor<BlinkCardEliteRecognizerResult>;
export interface BlinkCardEliteRecognizer extends Recognizer<BlinkCardEliteRecognizerResult> {
anonymizeCardNumber: boolean;
anonymizeCvv: boolean;
anonymizeOwner: boolean;
detectGlare: boolean;
extractInventoryNumber: boolean;
extractOwner: boolean;
extractValidThru: boolean;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFullDocumentImage: boolean;
signResult: boolean;
}
export type BlinkCardEliteRecognizerCtor = RecognizerCtor<BlinkCardEliteRecognizer>;
export interface EudlRecognizerResult extends RecognizerResult {
address: string;
birthData: string;
country: string;
driverNumber: string;
expiryDate: Date;
faceImage: string;
firstName: string;
fullDocumentImage: string;
issueDate: Date;
issuingAuthority: string;
lastName: string;
personalNumber: string;
}
export type EudlRecognizerResultCtor = RecognizerResultCtor<EudlRecognizerResult>;
export interface EudlRecognizer extends Recognizer<EudlRecognizerResult> {
country: EudlCountry.Automatic;
extractAddress: boolean;
extractDateOfExpiry: boolean;
extractDateOfIssue: boolean;
extractIssuingAuthority: boolean;
extractPersonalNumber: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
}
export interface GermanyCombinedRecognizerResult extends RecognizerResult {
address: string;
canNumber: string;
dateOfBirth: Date;
dateOfExpiry: Date;
dateOfIssue: Date;
digitalSignature: string;
digitalSignatureVersion: string;
documentDataMatch: boolean;
eyeColor: string;
faceImage: string;
firstName: string;
fullDocumentBackImage: string;
fullDocumentFrontImage: string;
height: string;
identityCardNumber: string;
issuingAuthority: string;
lastName: string;
mrzVerified: boolean;
nationality: string;
placeOfBirth: string;
scanningFirstSideDone: boolean;
sex: boolean;
signatureImage: string;
}
export type GermanyCombinedRecognizerResultCtor = RecognizerResultCtor<GermanyCombinedRecognizerResult>;
export interface GermanyCombinedRecognizer extends Recognizer<GermanyCombinedRecognizerResult> {
detectGlare: boolean;
extractAddress: boolean;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
returnSignatureImage: boolean;
signResult: boolean;
}
export type GermanyCombinedRecognizerCtor = RecognizerCtor<GermanyCombinedRecognizer>;
export interface GermanyDlBackRecognizerResult extends RecognizerResult {
dateOfIssueB10: string;
dateOfIssueB10NotSpecified: boolean;
fullDocumentImage: string;
}
export type GermanyDlBackRecognizerResultCtor = RecognizerResultCtor<GermanyDlBackRecognizerResult>;
export interface GermanyDlBackRecognizer extends Recognizer<GermanyDlBackRecognizerResult> {
detectGlare: boolean;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFullDocumentImage: boolean;
}
export type GermanyDlBackRecognizerCtor = RecognizerCtor<GermanyDlBackRecognizer>;
export interface GermanyIdBackRecognizerResult extends RecognizerResult {
address: string;
addressCity: string;
addressHouseNumber: string;
addressStreet: string;
addressZipCode: string;
authority: string;
dateOfBirth: Date;
dateOfExpiry: Date;
dateOfIssue: Date;
documentCode: string;
documentNumber: string;
eyeColour: string;
fullDocumentImage: string;
height: string;
issuer: string;
mrzParsed: boolean;
mrzText: string;
mrzVerified: boolean;
nationality: string;
opt1: string;
opt2: string;
primaryId: string;
secondaryId: string;
sex: string;
}
export type GermanyIdBackRecognizerResultCtor = RecognizerResultCtor<GermanyIdBackRecognizerResult>;
export interface GermanyIdBackRecognizer extends Recognizer<GermanyIdBackRecognizerResult> {
detectGlare: boolean;
extractAddress: boolean;
extractDateOfIssue: boolean;
extractEyeColour: boolean;
extractHeight: boolean;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFullDocumentImage: boolean;
}
export type GermanyIdBackRecognizerCtor = RecognizerCtor<GermanyIdBackRecognizer>;
export interface GermanyIdFrontRecognizerResult extends RecognizerResult {
canNumber: string;
dateOfBirth: Date;
dateOfExpiry: Date;
documentNumber: string;
faceImage: string;
fullDocumentImage: string;
givenNames: string;
nationality: string;
placeOfBirth: string;
signatureImage: string;
surname: string;
}
export type GermanyIdFrontRecognizerResultCtor = RecognizerResultCtor<GermanyIdFrontRecognizerResult>;
export interface GermanyIdFrontRecognizer extends Recognizer<GermanyIdFrontRecognizerResult> {
detectGlare: boolean;
extractCanNumber: boolean;
extractDateOfExpiry: boolean;
extractDocumentNumber: boolean;
extractGivenNames: boolean;
extractNationality: boolean;
extractPlaceOfBirth: boolean;
extractSurname: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
returnSignatureImage: boolean;
signatureImageDpi: number;
}
export type GermanyIdFrontRecognizerCtor = RecognizerCtor<GermanyIdFrontRecognizer>;
export interface GermanyOldIdRecognizerResult extends RecognizerResult {
dateOfBirth: Date;
dateOfExpiry: Date;
documentCode: string;
documentNumber: string;
faceImage: string;
fullDocumentImage: string;
issuer: string;
mrzParsed: boolean;
mrzText: string;
mrzVerified: boolean;
nationality: string;
opt1: string;
opt2: string;
placeOfBirth: string;
primaryId: string;
secondaryId: string;
sex: string;
signatureImage: string;
}
export type GermanyOldIdRecognizerResultCtor = RecognizerResultCtor<GermanyOldIdRecognizerResult>;
export interface GermanyOldIdRecognizer extends Recognizer<GermanyOldIdRecognizerResult> {
detectGlare: boolean;
extractPlaceOfBirth: boolean;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
returnSignatureImage: boolean;
}
export type GermanyOldIdRecognizerCtor = RecognizerCtor<GermanyOldIdRecognizer>;
export interface GermanyPassportRecognizerResult extends RecognizerResult {
authority: string;
dateOfBirth: Date;
dateOfExpiry: Date;
dateOfIssue: Date;
documentCode: string;
documentNumber: string;
faceImage: string;
fullDocumentImage: string;
issuer: string;
mrzParsed: boolean;
mrzText: string;
mrzVerified: string;
name: string;
nationality: string;
opt1: string;
opt2: string;
placeOfBirth: string;
primaryId: string;
secondaryId: string;
sex: string;
signatureImage: string;
surname: string;
}
export type GermanyPassportRecognizerResultCtor = RecognizerResultCtor<GermanyPassportRecognizerResult>;
export interface GermanyPassportRecognizer extends Recognizer<GermanyPassportRecognizerResult> {
detectGlare: boolean;
extractAuthority: boolean;
extractDateOfIssue: boolean;
extractName: boolean;
extractNationality: boolean;
extractPlaceOfBirth: boolean;
extractSurname: boolean;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
returnSignatureImage: boolean;
}
export type GermanyPassportRecognizerCtor = RecognizerCtor<GermanyPassportRecognizer>;
export interface HongKongIdFrontRecognizerResult extends RecognizerResult {
commercialCode: string;
dateOfBirth: Date;
dateOfIssue: Date;
documentNumber: string;
faceImage: string;
fullDocumentImage: string;
fullName: string;
residentialStatus: string;
sex: string;
}
export type HongKongIdFrontRecognizerResultCtor = RecognizerResultCtor<HongKongIdFrontRecognizerResult>;
export interface HongKongIdFrontRecognizer extends Recognizer<HongKongIdFrontRecognizerResult> {
detectGlare: boolean;
extractDateOfBirth: boolean;
extractDateOfIssue: boolean;
extractFullName: boolean;
extractResidentialStatus: boolean;
extractSex: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
}
export type HongKongIdFrontRecognizerCtor = RecognizerCtor<HongKongIdFrontRecognizer>;
export interface IkadRecognizerResult extends RecognizerResult {
address: string;
dateOfBirth: Date;
employer: string;
expiryDate: Date;
faceImage: string;
facultyAddress: string;
fullDocumentImage: string;
name: string;
nationality: string;
passportNumber: string;
sectory: string;
sex: string;
}
export type IkadRecognizerResultCtor = RecognizerResultCtor<IkadRecognizerResult>;
export interface IkadRecognizer extends Recognizer<IkadRecognizerResult> {
detectGlare: boolean;
extractEmployer: boolean;
extractExpiryDate: boolean;
extractFacultyAddress: boolean;
extractNationality: boolean;
extractPassportNumber: boolean;
extractSector: boolean;
extractSex: boolean;
fullDocumentImageDpi: number;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
}
export type IkadRecognizerCtor = RecognizerCtor<IkadRecognizer>;
export interface IndonesiaIdFrontRecognizerResult extends RecognizerResult {
address: string;
bloodType: string;
citizenship: string;
city: string;
dateOfBirth: Date;
dateOfExpiry: Date;
dateOfExpiryPermanent: string;
district: string;
documentNumber: string;
faceImage: string;
fullDocumentImage: string;
kelDesa: string;
maritalStatus: string;
name: string;
occupation: string;
placeOfBirth: string;
province: string;
religion: string;
rt: string;
rw: string;
sex: string;
signatureImage: string;
}
export type IndonesiaIdFrontRecognizerResultCtor = RecognizerResultCtor<IndonesiaIdFrontRecognizerResult>;
export interface IndonesiaIdFrontRecognizer extends Recognizer<IndonesiaIdFrontRecognizerResult> {
detectGlare: boolean;
extractAddress: boolean;
extractBloodType: boolean;
extractCitizenship: boolean;
extractCity: boolean;
extractDateOfExpiry: boolean;
extractDistrict: boolean;
extractKelDesa: boolean;
extractMaritalStatus: boolean;
extractName: boolean;
extractOccupation: boolean;
extractPlaceOfBirth: boolean;
extractReligion: boolean;
extractRt: boolean;
extractRw: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
returnSignatureImage: boolean;
signatureImageDpi: number;
}
export type IndonesiaIdFrontRecognizerCtor = RecognizerCtor<IndonesiaIdFrontRecognizer>;
export interface IrelandDlFrontRecognizerResult extends RecognizerResult {
address: string;
dateOfBirth: Date;
dateOfExpiry: Date;
dateOfIssue: Date;
driverNumber: string;
faceImage: string;
firstName: string;
fullDocumentImage: string;
issuedBy: string;
// sic
licenceCategories: string;
// sic
licenceNumber: string;
placeOfBirth: string;
signatureImage: string;
surname: string;
}
export type IrelandDlFrontRecognizerResultCtor = RecognizerResultCtor<IrelandDlFrontRecognizerResult>;
export interface IrelandDlFrontRecognizer extends Recognizer<IrelandDlFrontRecognizerResult> {
detectGlare: boolean;
extractAddress: boolean;
extractDateOfBirth: boolean;
extractDateOfExpiry: boolean;
extractDateOfIssue: boolean;
extractFirstName: boolean;
extractIssuedBy: boolean;
extractLicenceCategories: boolean;
extractLicenceNumber: boolean;
extractPlaceOfBirth: boolean;
extractSurname: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
returnSignatureImage: boolean;
signatureImageDpi: number;
}
export type IrelandDlFrontRecognizerCtor = RecognizerCtor<IrelandDlFrontRecognizer>;
export interface ItalyDlFrontRecognizerResult extends RecognizerResult {
address: string;
dateOfBirth: Date;
dateOfExpiry: Date;
dateOfIssue: Date;
faceImage: string;
firstName: string;
fullDocumentImage: string;
givenName: string;
issuingAuthority: string;
// sic
licenceCategories: string;
// sic
licenceNumber: string;
placeOfBirth: string;
signatureImage: string;
surname: string;
}
export type ItalyDlFrontRecognizerResultCtor = RecognizerResultCtor<ItalyDlFrontRecognizerResult>;
export interface ItalyDlFrontRecognizer extends Recognizer<ItalyDlFrontRecognizerResult> {
detectGlare: boolean;
extractAddress: boolean;
extractDateOfBirth: boolean;
extractDateOfExpiry: boolean;
extractDateOfIssue: boolean;
extractGivenName: boolean;
extractIssuingAuthority: boolean;
extractLicenceCategories: boolean;
extractPlaceOfBirth: boolean;
extractSurname: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
returnSignatureImage: boolean;
signatureImageDpi: number;
}
export type ItalyDlFrontRecognizerCtor = RecognizerCtor<ItalyDlFrontRecognizer>;
export interface JordanCombinedRecognizerResult extends RecognizerResult {
dateOfBirth: Date;
dateOfExpiry: Date;
digitalSignature: string;
digitalSignatureVersion: string;
documentDataMatch: boolean;
documentNumber: string;
faceImage: string;
fullDocumentBackImage: string;
fullDocumentFrontImage: string;
issuer: string;
mrzVerified: boolean;
name: string;
nationalNumber: string;
nationality: string;
scanningFirstSideDone: boolean;
sex: string;
}
export type JordanCombinedRecognizerResultCtor = RecognizerResultCtor<JordanCombinedRecognizerResult>;
export interface JordanCombinedRecognizer extends Recognizer<JordanCombinedRecognizerResult> {
detectGlare: boolean;
returnFullDocumentImage: boolean;
}
export type JordanCombinedRecognizerCtor = RecognizerCtor<JordanCombinedRecognizer>;
export interface JordanIdBackRecognizerResult extends RecognizerResult {
dateOfBirth: Date;
dateOfExpiry: Date;
documentCode: string;
documentNumber: string;
fullDocumentImage: string;
issuer: string;
mrzParsed: boolean;
mrzText: string;
mrzVerified: boolean;
nationality: string;
opt1: string;
opt2: string;
primaryId: string;
secondaryId: string;
sex: string;
}
export type JordanIdBackRecognizerResultCtor = RecognizerResultCtor<JordanIdBackRecognizerResult>;
export interface JordanIdBackRecognizer extends Recognizer<JordanIdBackRecognizerResult> {
detectGlare: boolean;
extractDateOfBirth: boolean;
extractName: boolean;
extractSex: boolean;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
signResult: boolean;
}
export type JordanIdBackRecognizerCtor = RecognizerCtor<JordanIdBackRecognizer>;
export interface JordanIdFrontRecognizerResult extends RecognizerResult {
dateOfBirth: Date;
faceImage: string;
fullDocumentImage: string;
name: string;
nationalNumber: string;
sex: string;
}
export type JordanIdFrontRecognizerResultCtor = RecognizerResultCtor<JordanIdFrontRecognizerResult>;
export interface JordanIdFrontRecognizer extends Recognizer<JordanIdFrontRecognizerResult> {
detectGlare: boolean;
extractDateOfBirth: boolean;
extractName: boolean;
extractSex: boolean;
fullDocumentImageDpi: number;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
}
export type JordanIdFrontRecognizerCtor = RecognizerCtor<JordanIdFrontRecognizer>;
export interface KuwaitIdBackRecognizerResult extends RecognizerResult {
fullDocumentImage: string;
mrzResult: MrzResult;
serialNo: string;
}
export type KuwaitIdBackRecognizerResultCtor = RecognizerResultCtor<KuwaitIdBackRecognizerResult>;
export interface KuwaitIdBackRecognizer extends Recognizer<KuwaitIdBackRecognizerResult> {
detectGlare: boolean;
extractSerialNo: boolean;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFullDocumentImage: boolean;
}
export type KuwaitIdBackRecognizerCtor = RecognizerCtor<KuwaitIdBackRecognizer>;
export interface KuwaitIdFrontRecognizerResult extends RecognizerResult {
birthData: Date;
civilIdNumber: string;
expiryDate: Date;
faceImage: string;
fullDocumentImage: string;
name: string;
nationality: string;
sex: string;
}
export type KuwaitIdFrontRecognizerResultCtor = RecognizerResultCtor<KuwaitIdFrontRecognizerResult>;
export interface KuwaitIdFrontRecognizer extends Recognizer<KuwaitIdFrontRecognizerResult> {
detectGlare: boolean;
extractBirthDate: boolean;
extractName: boolean;
extractNationality: boolean;
extractSex: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
}
export type KuwaitIdFrontRecognizerCtor = RecognizerCtor<KuwaitIdFrontRecognizer>;
export interface MalaysiaDlFrontRecognizerResult extends RecognizerResult {
city: string;
dlClass: string;
faceImage: string;
fullAddress: string;
fullDocumentImage: string;
identityNumber: string;
name: string;
nationality: string;
ownerState: string;
street: string;
validFrom: Date;
validUntil: Date;
zipcode: string;
}
export type MalaysiaDlFrontRecognizerResultCtor = RecognizerResultCtor<MalaysiaDlFrontRecognizerResult>;
export interface MalaysiaDlFrontRecognizer extends Recognizer<MalaysiaDlFrontRecognizerResult> {
detectGlare: boolean;
extractAddress: boolean;
extractClass: boolean;
extractName: boolean;
extractNationality: boolean;
extractValidFrom: boolean;
extractValidUntil: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
}
export type MalaysiaDlFrontRecognizerCtor = RecognizerCtor<MalaysiaDlFrontRecognizer>;
export interface MalaysiaMyTenteraRecognizerResult extends RecognizerResult {
armyNumber: string;
birthData: Date;
city: string;
faceImage: string;
fullAddress: string;
fullDocumentImage: string;
fullName: string;
nric: string;
ownerState: string;
religion: string;
sex: string;
street: string;
zipcode: string;
}
export type MalaysiaMyTenteraRecognizerResultCtor = RecognizerResultCtor<MalaysiaMyTenteraRecognizerResult>;
export interface MalaysiaMyTenteraRecognizer extends Recognizer<MalaysiaMyTenteraRecognizerResult> {
detectGlare: boolean;
extractFullNameAndAddress: boolean;
extractReligion: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
}
export type MalaysiaMyTenteraRecognizerCtor = RecognizerCtor<MalaysiaMyTenteraRecognizer>;
export interface MexicoVoterIdFrontRecognizerResult extends RecognizerResult {
address: string;
curp: string;
dateOfBirth: Date;
electorKey: string;
faceImage: string;
fullDocumentImage: string;
fullName: string;
sex: string;
signatureImage: string;
}
export type MexicoVoterIdFrontRecognizerResultCtor = RecognizerResultCtor<MexicoVoterIdFrontRecognizerResult>;
export interface MexicoVoterIdFrontRecognizer extends Recognizer<MexicoVoterIdFrontRecognizerResult> {
detectGlare: boolean;
extractAddress: boolean;
extractCurp: boolean;
extractFullName: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
returnSignatureImage: boolean;
signatureImageDpi: number;
}
export type MexicoVoterIdFrontRecognizerCtor = RecognizerCtor<MexicoVoterIdFrontRecognizer>;
export interface MoroccoIdBackRecognizerResult extends RecognizerResult {
address: string;
civilStatusNumber: string;
dateOfExpiry: Date;
documentNumber: string;
fathersName: string;
fullDocumentImage: string;
mothersName: string;
sex: string;
}
export type MoroccoIdBackRecognizerResultCtor = RecognizerResultCtor<MoroccoIdBackRecognizerResult>;
export interface MoroccoIdBackRecognizer extends Recognizer<MoroccoIdBackRecognizerResult> {
detectGlare: boolean;
extractAddress: boolean;
extractCivilStatusNumber: boolean;
extractDateOfExpiry: boolean;
extractFathersName: boolean;
extractMothersName: boolean;
extractSex: boolean;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFullDocumentImage: boolean;
}
export type MoroccoIdBackRecognizerCtor = RecognizerCtor<MoroccoIdBackRecognizer>;
export interface MoroccoIdFrontRecognizerResult extends RecognizerResult {
dateOfBirth: Date;
dateOfExpiry: Date;
documentNumber: string;
faceImage: string;
fullDocumentImage: string;
name: string;
placeOfBirth: string;
sex: string;
signatureImage: string;
surname: string;
}
export type MoroccoIdFrontRecognizerResultCtor = RecognizerResultCtor<MoroccoIdFrontRecognizerResult>;
export interface MoroccoIdFrontRecognizer extends Recognizer<MoroccoIdFrontRecognizerResult> {
detectGlare: boolean;
extractDateOfExpiry: boolean;
extractDateOfBirth: boolean;
extractName: boolean;
extractPlaceOfBirth: boolean;
extractSex: boolean;
extractSurname: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
returnSignatureImage: boolean;
signatureImageDpi: number;
}
export type MoroccoIdFrontRecognizerCtor = RecognizerCtor<MoroccoIdFrontRecognizer>;
export interface MrtdCombinedRecognizerResult extends RecognizerResult {
alienNumber: string;
applicationReceiptNumber: string;
dateOfBirth: Date;
dateOfExpiry: Date;
digitalSignature: string;
digitalSignatureVersion: string;
documentCode: string;
documentDataMatch: boolean;
documentNumber: string;
documentType: string;
faceImage: string;
fullDocumentBackImage: string;
fullDocumentFrontImage: string;
immigrantCaseNumber: string;
issuer: string;
mrzImage: string;
mrzParsed: boolean;
mrzText: string;
mrzVerified: boolean;
nationality: string;
opt1: string;
opt2: string;
primaryId: string;
scanningFirstSideDone: boolean;
secondaryId: string;
sex: string;
}
export type MrtdCombinedRecognizerResultCtor = RecognizerResultCtor<MrtdCombinedRecognizerResult>;
export interface MrtdCombinedRecognizer extends Recognizer<MrtdCombinedRecognizerResult> {
allowUnparsedResults: boolean;
allowUnverifiedResults: boolean;
numStableDetectionsThreshold: number;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
returnMrzImage: boolean;
signResult: boolean;
}
export type MrtdCombinedRecognizerCtor = RecognizerCtor<MrtdCombinedRecognizer>;
export interface MrtdRecognizerResult extends RecognizerResult {
fullDocumentImage: string;
mrzImage: string;
mrzResult: MrzResult;
}
export type MrtdRecognizerResultCtor = RecognizerResultCtor<MrtdRecognizerResult>;
export interface MrtdRecognizer extends Recognizer<MrtdRecognizerResult> {
allowUnparsedResults: boolean;
allowUnverifiedResults: boolean;
detectGlare: boolean;
returnFullDocumentImage: boolean;
returnMrzImage: boolean;
saveImageDPI: number;
}
export type MrtdRecognizerCtor = RecognizerCtor<MrtdRecognizer>;
export interface MyKadBackRecognizerResult extends RecognizerResult {
dateOfBirth: Date;
extendedNric: string;
fullDocumentImage: string;
nric: string;
oldNric: string;
sex: string;
signatureImage: string;
}
export type MyKadBackRecognizerResultCtor = RecognizerResultCtor<MyKadBackRecognizerResult>;
export interface MyKadBackRecognizer extends Recognizer<MyKadBackRecognizerResult> {
detectGlare: boolean;
extractOldNric: boolean;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFullDocumentImage: boolean;
returnSignatureImage: boolean;
signatureImageDpi: number;
}
export type MyKadBackRecognizerCtor = RecognizerCtor<MyKadBackRecognizer>;
export interface MyKadFrontRecognizerResult extends RecognizerResult {
armyNumber: string;
faceImage: string;
fullDocumentImage: string;
nricNumber: string;
ownerAddress: string;
ownerAddressCity: string;
ownerAddressState: string;
ownerAddressStreet: string;
ownerAddressZipCode: string;
ownerBirthDate: Date;
ownerFullName: string;
ownerReligion: string;
ownerSex: string;
}
export type MyKadFrontRecognizerResultCtor = RecognizerResultCtor<MyKadFrontRecognizerResult>;
export interface MyKadFrontRecognizer extends Recognizer<MyKadFrontRecognizerResult> {
extractArmyNumber: boolean;
fullDocumentImageDpi: number;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
}
export type MyKadFrontRecognizerCtor = RecognizerCtor<MyKadFrontRecognizer>;
export interface NewZealandDlFrontRecognizerResult extends RecognizerResult {
address: string;
cardVersion: string;
dateOfBirth: Date;
dateOfExpiry: Date;
dateOfIssue: Date;
donorIndicator: string;
faceImage: string;
firstNames: string;
fullDocumentImage: string;
licenceNumber: string;
signatureImage: string;
surname: string;
}
export type NewZealandDlFrontRecognizerResultCtor = RecognizerResultCtor<NewZealandDlFrontRecognizerResult>;
export interface NewZealandDlFrontRecognizer extends Recognizer<NewZealandDlFrontRecognizerResult> {
detectGlare: boolean;
extractAddress: boolean;
extractDateOfBirth: boolean;
extractDateOfExpiry: boolean;
extractDateOfIssue: boolean;
extractDonorIndicator: boolean;
extractFirstName: boolean;
extractSurname: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
returnSignatureImage: boolean;
signatureImageDpi: number;
}
export type NewZealandDlFrontRecognizerCtor = RecognizerCtor<NewZealandDlFrontRecognizer>;
export interface BlinkCardRecognizerResult extends RecognizerResult {
cardNumber: string;
cvv: string;
digitalSignature: string;
digitalSignatureVersion: string;
documentDataMatch: string;
fullDocumentBackImage: string;
fullDocumentFrontImage: string;
inventoryNumber: string;
issuer: string;
owner: string;
scanningFirstSideDone: boolean;
validThru: Date;
}
export type BlinkCardRecognizerResultCtor = RecognizerResultCtor<BlinkCardRecognizerResult>;
export interface BlinkCardRecognizer extends Recognizer<BlinkCardRecognizerResult> {
anonymizeCardNumber: boolean;
anonymizeCvv: boolean;
anonymizeOwner: boolean;
detectGlare: boolean;
extractCvv: boolean;
extractInventoryNumber: boolean;
extractOwner: boolean;
extractValidThru: boolean;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFullDocumentImage: boolean;
signResult: boolean;
}
export type BlinkCardRecognizerCtor = RecognizerCtor<BlinkCardRecognizer>;
export interface Pdf417RecognizerResult extends RecognizerResult {
barcodeType: string;
rawData: string;
stringData: string;
uncertain: boolean;
}
export type Pdf417RecognizerResultCtor = RecognizerResultCtor<Pdf417RecognizerResult>;
export interface Pdf417Recognizer extends Recognizer<Pdf417RecognizerResult> {
nullQuietZoneAllowed: boolean;
scanInverse: boolean;
scanUncertain: boolean;
}
export type Pdf417RecognizerCtor = RecognizerCtor<Pdf417Recognizer>;
export interface PolandCombinedRecognizerResult extends RecognizerResult {
dateOfBirth: Date;
dateOfExpiry: Date;
digitalSignature: string;
digitalSignatureVersion: string;
documentDataMatch: string;
documentNumber: string;
faceImage: string;
familyName: string;
fullDocumentBackImage: string;
fullDocumentFrontImage: string;
givenNames: string;
issuer: string;
mrzVerified: boolean;
nationality: string;
parentsGivenNames: string;
personalNumber: string;
scanningFirstSideDone: boolean;
sex: string;
surname: string;
}
export type PolandCombinedRecognizerResultCtor = RecognizerResultCtor<PolandCombinedRecognizerResult>;
export interface PolandCombinedRecognizer extends Recognizer<PolandCombinedRecognizerResult> {
detectGlare: boolean;
extractDateOfBirth: boolean;
extractFamilyName: boolean;
extractGivenName: boolean;
extractParentsGivenNames: boolean;
extractSex: boolean;
extractSurname: boolean;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
signResult: boolean;
}
export type PolandCombinedRecognizerCtor = RecognizerCtor<PolandCombinedRecognizer>;
export interface PolandIdBackRecognizerResult extends RecognizerResult {
dateOfBirth: Date;
dateOfExpiry: Date;
documentCode: string;
documentNumber: string;
fullDocumentImage: string;
issuer: string;
mrzParsed: boolean;
mrzText: string;
mrzVerified: boolean;
nationality: string;
opt1: string;
opt2: string;
primaryId: string;
secondaryId: string;
sex: string;
}
export type PolandIdBackRecognizerResultCtor = RecognizerResultCtor<PolandIdBackRecognizerResult>;
export interface PolandIdBackRecognizer extends Recognizer<PolandIdBackRecognizerResult> {
detectGlare: boolean;
returnFullDocumentImage: boolean;
}
export type PolandIdBackRecognizerCtor = RecognizerCtor<PolandIdBackRecognizer>;
export interface PolandIdFrontRecognizerResult extends RecognizerResult {
dateOfBirth: Date;
faceImage: string;
familyName: string;
fullDocumentImage: string;
givenNames: string;
parentsGivenNames: string;
sex: string;
surname: string;
}
export type PolandIdFrontRecognizerResultCtor = RecognizerResultCtor<PolandIdFrontRecognizerResult>;
export interface PolandIdFrontRecognizer extends Recognizer<PolandIdFrontRecognizerResult> {
detectGlare: boolean;
extractDateOfBirth: boolean;
extractFamilyName: boolean;
extractGivenNames: boolean;
extractParentsGivenNames: boolean;
extractSex: boolean;
extractSurname: boolean;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
}
export type PolandIdFrontRecognizerCtor = RecognizerCtor<PolandIdFrontRecognizer>;
export interface RomaniaIdFrontRecognizerResult extends RecognizerResult {
address: string;
cardNumber: string;
cnp: string;
dateOfBirth: Date;
dateOfExpiry: Date;
documentCode: string;
documentNumber: string;
faceImage: string;
firstName: string;
fullDocumentImage: string;
idSeries: string;
issuedBy: string;
issuer: string;
lastName: string;
mrzParsed: boolean;
mrzText: string;
mrzVerified: boolean;
nationality: string;
nonMRZNationality: string;
nonMRZSex: string;
opt1: string;
opt2: string;
parentNames: string;
placeOfBirth: string;
primaryId: string;
secondaryId: string;
sex: string;
validFrom: Date;
validUntil: Date;
}
export type RomaniaIdFrontRecognizerResultCtor = RecognizerResultCtor<RomaniaIdFrontRecognizerResult>;
export interface RomaniaIdFrontRecognizer extends Recognizer<RomaniaIdFrontRecognizerResult> {
detectGlare: boolean;
extractAddress: boolean;
extractFirstName: boolean;
extractIssuedBy: boolean;
extractLastName: boolean;
extractNonMRZSex: boolean;
extractPlaceOfBirth: boolean;
extractValidFrom: boolean;
extractValidUntil: boolean;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
}
export type RomaniaIdFrontRecognizerCtor = RecognizerCtor<RomaniaIdFrontRecognizer>;
export interface SerbiaCombinedRecognizerResult extends RecognizerResult {
dateOfBirth: Date;
dateOfExpiry: Date;
dateOfIssue: Date;
digitalSignature: string;
digitalSignatureVersion: string;
documentDataMatch: boolean;
faceImage: string;
firstName: string;
fullDocumentBackImage: string;
fullDocumentFrontImage: string;
identityCardNumber: string;
issuer: string;
jmbg: string;
lastName: string;
mrzVerified: boolean;
nationality: string;
scanningFirstSideDone: boolean;
sex: string;
signatureImage: string;
}
export type SerbiaCombinedRecognizerResultCtor = RecognizerResultCtor<SerbiaCombinedRecognizerResult>;
export interface SerbiaCombinedRecognizer extends Recognizer<SerbiaCombinedRecognizerResult> {
detectGlare: boolean;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
returnSignatureImage: boolean;
signResult: boolean;
}
export type SerbiaCombinedRecognizerCtor = RecognizerCtor<SerbiaCombinedRecognizer>;
export interface SerbiaIdBackRecognizerResult extends RecognizerResult {
dateOfBirth: Date;
dateOfExpiry: Date;
documentCode: string;
documentNumber: string;
fullDocumentImage: string;
issuer: string;
mrzParsed: boolean;
mrzText: string;
mrzVerified: boolean;
nationality: string;
opt1: string;
opt2: string;
primaryId: string;
secondaryId: string;
sex: string;
}
export type SerbiaIdBackRecognizerResultCtor = RecognizerResultCtor<SerbiaIdBackRecognizerResult>;
export interface SerbiaIdBackRecognizer extends Recognizer<SerbiaIdBackRecognizerResult> {
detectGlare: boolean;
returnFullDocumentImage: boolean;
}
export type SerbiaIdBackRecognizerCtor = RecognizerCtor<SerbiaIdBackRecognizer>;
export interface SerbiaIdFrontRecognizerResult extends RecognizerResult {
documentNumber: string;
faceImage: string;
fullDocumentImage: string;
issuingDate: Date;
signatureImage: string;
validThru: Date;
validUntil: Date;
}
export type SerbiaIdFrontRecognizerResultCtor = RecognizerResultCtor<SerbiaIdFrontRecognizerResult>;
export interface SerbiaIdFrontRecognizer extends Recognizer<SerbiaIdFrontRecognizerResult> {
detectGlare: boolean;
extractIssuingDate: boolean;
extractValidUntil: boolean;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
returnSignatureImage: boolean;
}
export type SerbiaIdFrontRecognizerCtor = RecognizerCtor<SerbiaIdFrontRecognizer>;
export interface SimNumberRecognizerResult extends RecognizerResult {
simNumber: string;
}
export type SimNumberRecognizerResultCtor = RecognizerResultCtor<SimNumberRecognizerResult>;
export type SimNumberRecognizer = Recognizer<SimNumberRecognizerResult>;
export type SimNumberRecognizerCtor = RecognizerCtor<SimNumberRecognizer>;
export interface SingaporeChangiEmployeeIdRecognizerResult extends RecognizerResult {
companyName: string;
dateOfExpiry: Date;
documentNumber: string;
faceImage: string;
fullDocumentImage: string;
name: string;
}
export type SingaporeChangiEmployeeIdRecognizerResultCtor =
RecognizerResultCtor<SingaporeChangiEmployeeIdRecognizerResult>;
export interface SingaporeChangiEmployeeIdRecognizer extends Recognizer<SingaporeChangiEmployeeIdRecognizerResult> {
detectGlare: boolean;
extractCompanyName: boolean;
extractDateOfExpiry: boolean;
extractName: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
}
export type SingaporeChangiEmployeeIdRecognizerCtor = RecognizerCtor<SingaporeChangiEmployeeIdRecognizer>;
export interface SingaporeCombinedRecognizerResult extends RecognizerResult {
address: string;
addressChangeDate: Date;
bloodGroup: string;
countryOfBirth: string;
dateOfBirth: Date;
dateOfIssue: Date;
digitalSignature: string;
digitalSignatureVersion: string;
documentDataMatch: boolean;
faceImage: string;
fullDocumentBackImage: string;
fullDocumentFrontImage: string;
identityCardNumber: string;
name: string;
race: string;
scanningFirstSideDone: string;
sex: string;
}
export type SingaporeCombinedRecognizerResultCtor = RecognizerResultCtor<SingaporeCombinedRecognizerResult>;
export interface SingaporeCombinedRecognizer extends Recognizer<SingaporeCombinedRecognizerResult> {
detectGlare: boolean;
extractAddress: boolean;
extractAddressChangeDate: boolean;
extractBloodGroup: boolean;
extractCountryOfBirth: boolean;
extractDateOfBirth: boolean;
extractDateOfIssue: boolean;
extractName: boolean;
extractRace: boolean;
extractSex: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
signResult: boolean;
}
export type SingaporeCombinedRecognizerCtor = RecognizerCtor<SingaporeCombinedRecognizer>;
export interface SingaporeDlFrontRecognizerResult extends RecognizerResult {
birthData: Date;
faceImage: string;
fullDocumentImage: string;
issueDate: Date;
licenceNumber: string;
name: string;
validTill: Date;
}
export type SingaporeDlFrontRecognizerResultCtor = RecognizerResultCtor<SingaporeDlFrontRecognizerResult>;
export interface SingaporeDlFrontRecognizer extends Recognizer<SingaporeDlFrontRecognizerResult> {
detectGlare: boolean;
extractBirthDate: boolean;
extractIssueDate: boolean;
extractName: boolean;
extractValidTill: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
}
export type SingaporeDlFrontRecognizerCtor = RecognizerCtor<SingaporeDlFrontRecognizer>;
export interface SingaporeIdBackRecognizerResult extends RecognizerResult {
address: string;
addressChangeDate: string;
bloodGroup: string;
cardNumber: string;
dateOfIssue: Date;
fullDocumentImage: string;
}
export type SingaporeIdBackRecognizerResultCtor = RecognizerResultCtor<SingaporeIdBackRecognizerResult>;
export interface SingaporeIdBackRecognizer extends Recognizer<SingaporeIdBackRecognizerResult> {
detectGlare: boolean;
extractAddress: boolean;
extractAddressChangeDate: boolean;
extractBloodGroup: boolean;
extractDateOfIssue: boolean;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFullDocumentImage: boolean;
}
export type SingaporeIdBackRecognizerCtor = RecognizerCtor<SingaporeIdBackRecognizer>;
export interface SingaporeIdFrontRecognizerResult extends RecognizerResult {
countryOfBirth: string;
dateOfBirth: Date;
faceImage: string;
fullDocumentImage: string;
identityCardNumber: string;
name: string;
race: string;
sex: string;
}
export type SingaporeIdFrontRecognizerResultCtor = RecognizerResultCtor<SingaporeIdFrontRecognizerResult>;
export interface SingaporeIdFrontRecognizer extends Recognizer<SingaporeIdFrontRecognizerResult> {
detectGlare: boolean;
extractCountryOfBirth: boolean;
extractDateOfBirth: boolean;
extractName: boolean;
extractRace: boolean;
extractSex: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
}
export type SingaporeIdFrontRecognizerCtor = RecognizerCtor<SingaporeIdFrontRecognizer>;
export interface SlovakiaCombinedRecognizerResult extends RecognizerResult {
address: string;
dateOfBirth: Date;
dateOfExpiry: Date;
dateOfIssue: Date;
digitalSignature: number;
digitalSignatureVersion: number;
documentDataMatch: boolean;
documentNumber: string;
faceImage: string;
firstName: string;
fullDocumentBackImage: string;
fullDocumentFrontImage: string;
issuingAuthority: string;
lastName: string;
mrzVerified: boolean;
nationality: string;
personalIdentificationNumber: string;
placeOfBirth: string;
scanningFirstSideDone: string;
sex: string;
signatureImage: string;
specialRemarks: string;
surnameAtBirth: string;
}
export type SlovakiaCombinedRecognizerResultCtor = RecognizerResultCtor<SlovakiaCombinedRecognizerResult>;
export interface SlovakiaCombinedRecognizer extends Recognizer<SlovakiaCombinedRecognizerResult> {
detectGlare: boolean;
extractDateOfBirth: boolean;
extractDateOfExpiry: boolean;
extractDateOfIssue: boolean;
extractDocumentNumber: boolean;
extractIssuedBy: boolean;
extractNationality: boolean;
extractPlaceOfBirth: boolean;
extractSex: boolean;
extractSpecialRemarks: boolean;
extractSurnameAtBirth: boolean;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
signResult: boolean;
}
export type SlovakiaCombinedRecognizerCtor = RecognizerCtor<SlovakiaCombinedRecognizer>;
export interface SlovakiaIdBackRecognizerResult extends RecognizerResult {
address: string;
dateOfBirth: Date;
dateOfExpiry: Date;
documentCode: string;
fullDocumentImage: string;
issuer: string;
mrzParsed: boolean;
mrzText: string;
mrzVerified: boolean;
nationality: string;
opt1: string;
opt2: string;
placeOfBirth: string;
primaryId: string;
secondaryId: string;
sex: string;
specialRemarks: string;
surnameAtBirth: string;
}
export type SlovakiaIdBackRecognizerResultCtor = RecognizerResultCtor<SlovakiaIdBackRecognizerResult>;
export interface SlovakiaIdBackRecognizer extends Recognizer<SlovakiaIdBackRecognizerResult> {
detectGlare: boolean;
extractPlaceOfBirth: boolean;
extractSpecialRemarks: boolean;
extractSurnameAtBirth: boolean;
returnFullDocumentImage: boolean;
}
export type SlovakiaIdBackRecognizerCtor = RecognizerCtor<SlovakiaIdBackRecognizer>;
export interface SlovakiaIdFrontRecognizerResult extends RecognizerResult {
dateOfBirth: Date;
dateOfExpiry: Date;
dateOfIssue: Date;
documentNumber: string;
faceImage: string;
firstName: string;
fullDocumentImage: string;
issuedBy: string;
lastName: string;
nationality: string;
personalNumber: string;
sex: string;
signatureImage: string;
}
export type SlovakiaIdFrontRecognizerResultCtor = RecognizerResultCtor<SlovakiaIdFrontRecognizerResult>;
export interface SlovakiaIdFrontRecognizer extends Recognizer<SlovakiaIdFrontRecognizerResult> {
detectGlare: boolean;
extractPlaceOfBirth: boolean;
extractDateOfExpiry: boolean;
extractDateOfIssue: boolean;
extractDocumentNumber: boolean;
extractIssuedBy: boolean;
extractNationality: boolean;
extractSex: boolean;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
returnSignatureImage: boolean;
}
export type SlovakiaIdFrontRecognizerCtor = RecognizerCtor<SlovakiaIdFrontRecognizer>;
export interface SloveniaCombinedRecognizerResult extends RecognizerResult {
address: string;
citizenship: string;
dateOfBirth: Date;
dateOfExpiry: Date;
dateOfIssue: Date;
digitalSignature: string;
digitalSignatureVersion: string;
documentDataMatch: boolean;
faceImage: string;
firstName: string;
fullDocumentBackImage: string;
fullDocumentFrontImage: string;
identityCardNumber: string;
issuingAuthority: string;
lastName: string;
mrzVerified: boolean;
personalIdentificationNumber: string;
scanningFirstSideDone: boolean;
sex: string;
signatureImage: string;
}
export type SloveniaCombinedRecognizerResultCtor = RecognizerResultCtor<SloveniaCombinedRecognizerResult>;
export interface SloveniaCombinedRecognizer extends Recognizer<SloveniaCombinedRecognizerResult> {
detectGlare: boolean;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
returnSignatureImage: boolean;
signResult: boolean;
}
export type SloveniaCombinedRecognizerCtor = RecognizerCtor<SloveniaCombinedRecognizer>;
export interface SloveniaIdBackRecognizerResult extends RecognizerResult {
address: string;
authority: string;
dateOfExpiry: Date;
dateOfIssue: Date;
documentCode: string;
documentNumber: string;
fullDocumentImage: string;
issuer: string;
mrzParsed: boolean;
mrzText: string;
mrzVerified: boolean;
nationality: string;
opt1: string;
opt2: string;
primaryId: string;
secondaryId: string;
sex: string;
}
export type SloveniaIdBackRecognizerResultCtor = RecognizerResultCtor<SloveniaIdBackRecognizerResult>;
export interface SloveniaIdBackRecognizer extends Recognizer<SloveniaIdBackRecognizerResult> {
detectGlare: boolean;
extractAuthority: boolean;
extractDateOfIssue: boolean;
returnFullDocumentImage: boolean;
}
export type SloveniaIdBackRecognizerCtor = RecognizerCtor<SloveniaIdBackRecognizer>;
export interface SloveniaIdFrontRecognizerResult extends RecognizerResult {
dateOfBirth: Date;
dateOfExpiry: Date;
faceImage: string;
firstName: string;
fullDocumentImage: string;
lastName: string;
nationality: string;
sex: string;
signatureImage: string;
}
export type SloveniaIdFrontRecognizerResultCtor = RecognizerResultCtor<SloveniaIdFrontRecognizerResult>;
export interface SloveniaIdFrontRecognizer extends Recognizer<SloveniaIdFrontRecognizerResult> {
detectGlare: boolean;
extractDateOfBirth: boolean;
extractDateOfExpiry: boolean;
extractNationality: boolean;
extractSex: boolean;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
returnSignatureImage: boolean;
}
export type SloveniaIdFrontRecognizerCtor = RecognizerCtor<SloveniaIdFrontRecognizer>;
export interface SpainDlFrontRecognizerResult extends RecognizerResult {
dateOfBirth: Date;
faceImage: string;
firstName: string;
fullDocumentImage: string;
issuingAuthority: string;
licenceCategories: string;
number: string;
placeOfBirth: string;
signatureImage: string;
surname: string;
validFrom: Date;
validUntil: Date;
}
export type SpainDlFrontRecognizerResultCtor = RecognizerResultCtor<SpainDlFrontRecognizerResult>;
export interface SpainDlFrontRecognizer extends Recognizer<SpainDlFrontRecognizerResult> {
detectGlare: boolean;
extractDateOfBirth: boolean;
extractFirstName: boolean;
extractIssuingAuthority: boolean;
extractLicenceCategories: boolean;
extractPlaceOfBirth: boolean;
extractSurname: boolean;
extractValidFrom: boolean;
extractValidUntil: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
returnSignatureImage: boolean;
signatureImageDpi: number;
}
export type SpainDlFrontRecognizerCtor = RecognizerCtor<SpainDlFrontRecognizer>;
export interface SwedenDlFrontRecognizerResult extends RecognizerResult {
dateOfBirth: Date;
dateOfExpiry: Date;
dateOfIssue: Date;
faceImage: string;
fullDocumentImage: string;
issuingAgency: string;
licenceCategories: string;
licenceNumber: string;
name: string;
referenceNumber: string;
signatureImage: string;
surname: string;
}
export type SwedenDlFrontRecognizerResultCtor = RecognizerResultCtor<SwedenDlFrontRecognizerResult>;
export interface SwedenDlFrontRecognizer extends Recognizer<SwedenDlFrontRecognizerResult> {
detectGlare: boolean;
extractDateOfBirth: boolean;
extractDateOfExpiry: boolean;
extractDateOfIssue: boolean;
extractIssuingAuthority: boolean;
extractLicenceCategories: boolean;
extractName: boolean;
extractReferenceNumber: boolean;
extractSurname: boolean;
extractValidFrom: boolean;
fullDocumentImageDpi: number;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
returnSignatureImage: boolean;
}
export type SwedenDlFrontRecognizerCtor = RecognizerCtor<SwedenDlFrontRecognizer>;
export interface SwitzerlandDlFrontRecognizerResult extends RecognizerResult {
dateOfBirth: Date;
dateOfExpiry: Date;
dateOfIssue: Date;
expiryDatePermanent: boolean;
faceImage: string;
firstName: string;
fullDocumentImage: string;
issuingAuthority: string;
lastName: string;
licenseNumber: string;
placeOfBirth: string;
signatureImage: string;
vehicleCategories: string;
}
export type SwitzerlandDlFrontRecognizerResultCtor = RecognizerResultCtor<SwitzerlandDlFrontRecognizerResult>;
export interface SwitzerlandDlFrontRecognizer extends Recognizer<SwitzerlandDlFrontRecognizerResult> {
detectGlare: boolean;
extractDateOfBirth: boolean;
extractDateOfExpiry: boolean;
extractDateOfIssue: boolean;
extractFirstName: boolean;
extractIssuingAuthority: boolean;
extractLastName: boolean;
extractPlaceOfBirth: boolean;
extractVehicleCategories: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
returnSignatureImage: boolean;
signatureImageDpi: number;
}
export type SwitzerlandDlFrontRecognizerCtor = RecognizerCtor<SwitzerlandDlFrontRecognizer>;
export interface SwitzerlandDlBackRecognizerResult extends RecognizerResult {
authority: string;
dateOfBirth: Date;
dateOfExpiry: Date;
dateOfIssue: Date;
documentCode: string;
documentNumber: string;
fullDocumentImage: string;
height: string;
issuer: string;
mrzParsed: boolean;
mrzText: string;
mrzVerified: boolean;
nationality: string;
nonMrzDateOfExpiry: Date;
nonMrzSex: string;
opt1: string;
opt2: string;
placeOfOrigin: string;
primaryId: string;
secondaryId: string;
sex: string;
}
export type SwitzerlandDlBackRecognizerResultCtor = RecognizerResultCtor<SwitzerlandDlBackRecognizerResult>;
export interface SwitzerlandDlBackRecognizer extends Recognizer<SwitzerlandDlBackRecognizerResult> {
detectGlare: boolean;
extractAuthority: boolean;
extractDateOfExpiry: boolean;
extractDateOfIssue: boolean;
extractHeight: boolean;
extractPlaceOfOrigin: boolean;
extractSex: boolean;
returnFullDocumentImage: boolean;
}
export type SwitzerlandDlBackRecognizerCtor = RecognizerCtor<SwitzerlandDlBackRecognizer>;
export interface SwitzerlandIdFrontRecognizerResult extends RecognizerResult {
dateOfBirth: Date;
faceImage: string;
fullDocumentImage: string;
givenName: string;
signatureImage: string;
surname: string;
}
export type SwitzerlandIdFrontRecognizerResultCtor = RecognizerResultCtor<SwitzerlandIdFrontRecognizerResult>;
export interface SwitzerlandIdFrontRecognizer extends Recognizer<SwitzerlandIdFrontRecognizerResult> {
detectGlare: boolean;
extractGivenName: boolean;
extractSurname: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
returnSignatureImage: boolean;
signatureImageDpi: number;
}
export type SwitzerlandIdFrontRecognizerCtor = RecognizerCtor<SwitzerlandIdFrontRecognizer>;
export interface SwitzerlandPassportRecognizerResult extends RecognizerResult {
authority: string;
dateOfBirth: Date;
dateOfExpiry: Date;
dateOfIssue: Date;
documentCode: string;
documentNumber: string;
faceImage: string;
fullDocumentImage: string;
givenName: string;
height: string;
issuer: string;
mrzParsed: boolean;
mrzText: string;
mrzVerified: boolean;
nationality: string;
nonMrzDateOfBirth: Date;
nonMrzDateOfExpiry: Date;
nonMrzSex: string;
opt1: string;
opt2: string;
passportNumber: string;
placeOfBirth: string;
primaryId: string;
secondaryId: string;
sex: string;
surname: string;
}
export type SwitzerlandPassportRecognizerResultCtor = RecognizerResultCtor<SwitzerlandPassportRecognizerResult>;
export interface SwitzerlandPassportRecognizer extends Recognizer<SwitzerlandPassportRecognizerResult> {
detectGlare: boolean;
extractAuthority: boolean;
extractDateOfBirth: boolean;
extractDateOfExpiry: boolean;
extractDateOfIssue: boolean;
extractGivenName: boolean;
extractHeight: boolean;
extractPassportNumber: boolean;
extractPlaceOfBirth: boolean;
extractSex: boolean;
extractSurname: boolean;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
}
export type SwitzerlandPassportRecognizerCtor = RecognizerCtor<SwitzerlandPassportRecognizer>;
export interface UnitedArabEmiratesDlFrontRecognizerResult extends RecognizerResult {
dateOfBirth: Date;
expiryDate: Date;
faceImage: string;
fullDocumentImage: string;
issueDate: Date;
licenseNumber: string;
licensingAuthority: string;
name: string;
nationality: string;
placeOfIssue: string;
}
export type UnitedArabEmiratesDlFrontRecognizerResultCtor =
RecognizerResultCtor<UnitedArabEmiratesDlFrontRecognizerResult>;
export interface UnitedArabEmiratesDlFrontRecognizer extends Recognizer<UnitedArabEmiratesDlFrontRecognizerResult> {
detectGlare: boolean;
extractDateOfBirth: boolean;
extractDateOfIssue: boolean;
extractLicenseNumber: boolean;
extractLicensingAuthority: boolean;
extractName: boolean;
extractNationality: boolean;
extractPlaceOfIssue: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
}
export type UnitedArabEmiratesDlFrontRecognizerCtor = RecognizerCtor<UnitedArabEmiratesDlFrontRecognizer>;
export interface UnitedArabEmiratesIdBackRecognizerResult extends RecognizerResult {
fullDocumentImage: string;
mrzResult: MrzResult;
}
export type UnitedArabEmiratesIdBackRecognizerResultCtor =
RecognizerResultCtor<UnitedArabEmiratesIdBackRecognizerResult>;
export interface UnitedArabEmiratesIdBackRecognizer extends Recognizer<UnitedArabEmiratesIdBackRecognizerResult> {
detectGlare: boolean;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFullDocumentImage: boolean;
}
export type UnitedArabEmiratesIdBackRecognizerCtor = RecognizerCtor<UnitedArabEmiratesIdBackRecognizer>;
export interface UnitedArabEmiratesIdFrontRecognizerResult extends RecognizerResult {
faceImage: string;
fullDocumentImage: string;
idNumber: string;
name: string;
nationality: string;
}
export type UnitedArabEmiratesIdFrontRecognizerResultCtor =
RecognizerResultCtor<UnitedArabEmiratesIdFrontRecognizerResult>;
export interface UnitedArabEmiratesIdFrontRecognizer extends Recognizer<UnitedArabEmiratesIdFrontRecognizerResult> {
detectGlare: boolean;
extractName: boolean;
extractNationality: boolean;
faceImageDpi: number;
fullDocumentImageDpi: number;
fullDocumentImageExtensionFactors: ImageExtensionFactors;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
}
export type UnitedArabEmiratesIdFrontRecognizerCtor = RecognizerCtor<UnitedArabEmiratesIdFrontRecognizer>;
export interface VinRecognizerResult extends RecognizerResult {
vin: string;
}
export type VinRecognizerResultCtor = RecognizerResultCtor<VinRecognizerResult>;
export type VinRecognizer = Recognizer<VinRecognizerResult>;
export type VinRecognizerCtor = RecognizerCtor<VinRecognizer>;
export interface UsdlRecognizerResult extends RecognizerResult {
optionalElements: any[];
rawData: string;
rawStringData: string;
uncertain: string;
fields: any[];
}
export type UsdlRecognizerResultCtor = RecognizerResultCtor<UsdlRecognizerResult>;
export interface UsdlRecognizer extends Recognizer<UsdlRecognizerResult> {
nullQuietZoneAllowed: boolean;
uncertainDecoding: boolean;
}
export type UsdlRecognizerCtor = RecognizerCtor<UsdlRecognizer>;
export interface UsdlCombinedRecognizerResult extends RecognizerResult {
digitalSignature: string;
digitalSignatureVersion: string;
documentDataMatch: boolean;
faceImage: string;
fullDocumentImage: string;
scanningFirstSideDone: boolean;
optionalElements: any[];
rawData: string;
rawStringData: string;
uncertain: boolean;
fields: any[];
}
export type UsdlCombinedRecognizerResultCtor = RecognizerResultCtor<UsdlCombinedRecognizerResult>;
export interface UsdlCombinedRecognizer extends Recognizer<UsdlCombinedRecognizerResult> {
faceImageDpi: number;
fullDocumentImageDpi: number;
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
signResult: boolean;
}
export type UsdlCombinedRecognizerCtor = RecognizerCtor<UsdlCombinedRecognizer>;
export type BlinkIdRecognizerCtor = RecognizerCtor<BlinkIdRecognizer>;
export interface BlinkIdRecognizer extends Recognizer<BlinkIdRecognizerResult> {
returnFaceImage: boolean;
returnFullDocumentImage: boolean;
anonymizationMode: number;
}
export interface BlinkIdRecognizerResult extends RecognizerResult {
firstName: string;
lastName: string;
fullName: string;
localizedName: string;
additionalNameInformation: string;
placeOfBirth: string;
documentNumber: string;
dateOfBirth: Date;
sex: string;
nationality: string;
fullDocumentImage: string;
mrzResult: MrzResult;
}
export interface BlinkIdOverlaySettingsCtor {
new (): BlinkIdOverlaySettings;
}
export type BlinkIdOverlaySettings = OverlaySettings;
export type BlinkIdRecognizerResultCtor = RecognizerResultCtor<BlinkIdRecognizerResult>;
/**
* @name BlinkId
* @description
* Microblink SDK wrapper for barcode and document scanning. See the
* blinkid-phonegap repository for available recognizers and other settings
* @usage
* ```typescript
* import { BlinkId, RecognizerResultState } from '@awesome-cordova-plugins/blinkid/ngx';
*
* constructor(private blinkId: BlinkId) { }
*
* ...
*
* const overlaySettings = new this.blinkId.DocumentOverlaySettings();
*
* const usdlRecognizer = new this.blinkId.UsdlRecognizer();
* const usdlSuccessFrameGrabber = new this.blinkId.SuccessFrameGrabberRecognizer(usdlRecognizer);
*
* const barcodeRecognizer = new this.blinkId.BarcodeRecognizer();
* barcodeRecognizer.scanPdf417 = true;
*
* const recognizerCollection = new this.blinkId.RecognizerCollection([
* usdlSuccessFrameGrabber,
* barcodeRecognizer,
* ]);
*
* const canceled = await this.blinkId.scanWithCamera(
* overlaySettings,
* recognizerCollection,
* { ios: IOS_LICENSE_KEY, android: ANDROID_LICENSE_KEY },
* );
*
* if (!canceled) {
* if (usdlRecognizer.result.resultState === RecognizerResultState.valid) {
* const successFrame = usdlSuccessFrameGrabber.result.successFrame;
* if (successFrame) {
* this.base64Img = `data:image/jpg;base64, ${successFrame}`;
* this.fields = usdlRecognizer.result.fields;
* }
* } else {
* this.barcodeStringData = barcodeRecognizer.result.stringData;
* }
* }
*
* ...
*
* const overlaySettings = new this.blinkId.BlinkCardOverlaySettings();
* const recognizer = new this.blinkId.BlinkCardRecognizer();
* recognizer.returnFullDocumentImage = false;
* recognizer.detectGlare = true;
* recognizer.extractCvv = true;
* recognizer.extractValidThru = true;
* recognizer.extractOwner = true;
*
* const recognizerCollection = new this.blinkId.RecognizerCollection([recognizer]);
* const canceled = await this.blinkId.scanWithCamera(
* overlaySettings,
* recognizerCollection,
* {
* ios: '', //iOS License Key
* android: '' //Android License Key
* },
* );
*
* if (!canceled) {
* if (recognizer.result.resultState === RecognizerResultState.valid) {
* const results = recognizer.result;
*
* if (results.resultState === RecognizerResultState.valid) {
* const ccInfo = {
* cardNumber: Number(results.cardNumber),
* expirationMonth: Number(results.validThru.month),
* expirationYear: Number(results.validThru.year),
* cvv: Number(results.cvv)
* };
* }
* }
* ```
*/
@Plugin({
pluginName: 'BlinkId',
plugin: 'blinkid-cordova',
pluginRef: 'cordova.plugins.BlinkID',
repo: 'https://github.com/BlinkID/blinkid-phonegap',
install:
'ionic cordova plugin add blinkid-cordova --variable CAMERA_USAGE_DESCRIPTION="Enable your camera so that you can scan your ID to validate your account"',
platforms: ['iOS', 'Android'],
})
@Injectable()
export class BlinkId extends AwesomeCordovaNativePlugin {
/**
* Opens the camera dialog and attempts to scan a barcode/document
*
* @param overlaySettings {OverlaySettings} for camera overlay customization
* @param recognizerCollection {RecognizerCollection} collection of recognizers to scan with
* @param licenses
* @returns {Promise<boolean>}
*/
@Cordova({
callbackOrder: 'reverse',
})
scanWithCamera(
overlaySettings: OverlaySettings,
recognizerCollection: RecognizerCollection,
licenses: Licenses
): Promise<boolean> {
return;
}
@CordovaProperty() Date: DateCtor;
@CordovaProperty() Point: PointCtor;
@CordovaProperty() Quadrilateral: QuadrilateralCtor;
@CordovaProperty() BarcodeOverlaySettings: BarcodeOverlaySettingsCtor;
@CordovaProperty() DocumentOverlaySettings: DocumentOverlaySettingsCtor;
@CordovaProperty() DocumentVerificationOverlaySettings: DocumentVerificationOverlaySettingsCtor;
@CordovaProperty() BlinkCardOverlaySettings: BlinkCardOverlaySettingsCtor;
@CordovaProperty() RecognizerCollection: RecognizerCollectionCtor;
@CordovaProperty() BarcodeRecognizerResult: BarcodeRecognizerResultCtor;
@CordovaProperty() BarcodeRecognizer: BarcodeRecognizerCtor;
@CordovaProperty() SuccessFrameGrabberRecognizerResult: SuccessFrameGrabberRecognizerResultCtor;
@CordovaProperty() SuccessFrameGrabberRecognizer: SuccessFrameGrabberRecognizerCtor;
@CordovaProperty() AustraliaDlBackRecognizerResult: AustraliaDlBackRecognizerResultCtor;
@CordovaProperty() AustraliaDlBackRecognizer: AustraliaDlBackRecognizerCtor;
@CordovaProperty() AustraliaDlFrontRecognizerResult: AustraliaDlFrontRecognizerResultCtor;
@CordovaProperty() AustraliaDlFrontRecognizer: AustraliaDlFrontRecognizerCtor;
@CordovaProperty() AustriaCombinedRecognizerResult: AustriaCombinedRecognizerResultCtor;
@CordovaProperty() AustriaCombinedRecognizer: AustriaCombinedRecognizerCtor;
@CordovaProperty() AustriaDlFrontRecognizerResult: AustriaDlFrontRecognizerResultCtor;
@CordovaProperty() AustriaDlFrontRecognizer: AustriaDlFrontRecognizerCtor;
@CordovaProperty() AustriaIdBackRecognizerResult: AustriaIdBackRecognizerResultCtor;
@CordovaProperty() AustriaIdBackRecognizer: AustriaIdBackRecognizerCtor;
@CordovaProperty() AustriaIdFrontRecognizerResult: AustriaIdFrontRecognizerResultCtor;
@CordovaProperty() AustriaIdFrontRecognizer: AustriaIdFrontRecognizerCtor;
@CordovaProperty() AustriaPassportRecognizerResult: AustriaPassportRecognizerResultCtor;
@CordovaProperty() AustriaPassportRecognizer: AustriaPassportRecognizerCtor;
@CordovaProperty() BlinkCardEliteRecognizer: BlinkCardEliteRecognizerCtor;
@CordovaProperty() BlinkCardEliteRecognizerResult: BlinkCardEliteRecognizerResultCtor;
@CordovaProperty() BlinkCardRecognizerResult: BlinkCardRecognizerResultCtor;
@CordovaProperty() BlinkCardRecognizer: BlinkCardRecognizerCtor;
@CordovaProperty() ColombiaDlFrontRecognizerResult: ColombiaDlFrontRecognizerResultCtor;
@CordovaProperty() ColombiaIdBackRecognizerResult: ColombiaIdBackRecognizerResultCtor;
@CordovaProperty() ColombiaIdBackRecognizer: ColombiaIdBackRecognizerCtor;
@CordovaProperty() ColombiaIdFrontRecognizerResult: ColombiaIdFrontRecognizerResultCtor;
@CordovaProperty() ColombiaIdFrontRecognizer: ColombiaIdFrontRecognizerCtor;
@CordovaProperty() CroatiaCombinedRecognizerResult: CroatiaCombinedRecognizerResultCtor;
@CordovaProperty() CroatiaIdBackRecognizerResult: CroatiaIdBackRecognizerResultCtor;
@CordovaProperty() CroatiaIdFrontRecognizerResult: CroatiaIdFrontRecognizerResultCtor;
@CordovaProperty() CyprusIdBackRecognizerResult: CyprusIdBackRecognizerResultCtor;
@CordovaProperty() CyprusIdBackRecognizer: CyprusIdBackRecognizerCtor;
@CordovaProperty() CyprusIdFrontRecognizerResult: CyprusIdFrontRecognizerResultCtor;
@CordovaProperty() CyprusIdFrontRecognizer: CyprusIdFrontRecognizerCtor;
@CordovaProperty() CzechiaCombinedRecognizerResult: CzechiaCombinedRecognizerResultCtor;
@CordovaProperty() CzechiaIdBackRecognizerResult: CzechiaIdBackRecognizerResultCtor;
@CordovaProperty() DocumentFaceRecognizerResult: DocumentFaceRecognizerResultCtor;
@CordovaProperty() EgyptIdFrontRecognizerResult: EgyptIdFrontRecognizerResultCtor;
@CordovaProperty() EgyptIdFrontRecognizer: EgyptIdFrontRecognizerCtor;
@CordovaProperty() EudlRecognizerResult: EudlRecognizerResultCtor;
@CordovaProperty() GermanyCombinedRecognizerResult: GermanyCombinedRecognizerResultCtor;
@CordovaProperty() GermanyCombinedRecognizer: GermanyCombinedRecognizerCtor;
@CordovaProperty() GermanyDlBackRecognizerResult: GermanyDlBackRecognizerResultCtor;
@CordovaProperty() GermanyDlBackRecognizer: GermanyDlBackRecognizerCtor;
@CordovaProperty() GermanyIdBackRecognizerResult: GermanyIdBackRecognizerResultCtor;
@CordovaProperty() GermanyIdBackRecognizer: GermanyIdBackRecognizerCtor;
@CordovaProperty() GermanyIdFrontRecognizerResult: GermanyIdFrontRecognizerResultCtor;
@CordovaProperty() GermanyIdFrontRecognizer: GermanyIdFrontRecognizerCtor;
@CordovaProperty() GermanyOldIdRecognizerResult: GermanyOldIdRecognizerResultCtor;
@CordovaProperty() GermanyOldIdRecognizer: GermanyOldIdRecognizerCtor;
@CordovaProperty() GermanyPassportRecognizerResult: GermanyPassportRecognizerResultCtor;
@CordovaProperty() GermanyPassportRecognizer: GermanyPassportRecognizerCtor;
@CordovaProperty() HongKongIdFrontRecognizerResult: HongKongIdFrontRecognizerResultCtor;
@CordovaProperty() HongKongIdFrontRecognizer: HongKongIdFrontRecognizerCtor;
@CordovaProperty() IkadRecognizerResult: IkadRecognizerResultCtor;
@CordovaProperty() IkadRecognizer: IkadRecognizerCtor;
@CordovaProperty() IndonesiaIdFrontRecognizerResult: IndonesiaIdFrontRecognizerResultCtor;
@CordovaProperty() IndonesiaIdFrontRecognizer: IndonesiaIdFrontRecognizerCtor;
@CordovaProperty() IrelandDlFrontRecognizerResult: IrelandDlFrontRecognizerResultCtor;
@CordovaProperty() IrelandDlFrontRecognizer: IrelandDlFrontRecognizerCtor;
@CordovaProperty() ItalyDlFrontRecognizerResult: ItalyDlFrontRecognizerResultCtor;
@CordovaProperty() ItalyDlFrontRecognizer: ItalyDlFrontRecognizerCtor;
@CordovaProperty() JordanCombinedRecognizerResult: JordanCombinedRecognizerResultCtor;
@CordovaProperty() JordanCombinedRecognizer: JordanCombinedRecognizerCtor;
@CordovaProperty() JordanIdBackRecognizerResult: JordanIdBackRecognizerResultCtor;
@CordovaProperty() JordanIdBackRecognizer: JordanIdBackRecognizerCtor;
@CordovaProperty() JordanIdFrontRecognizerResult: JordanIdFrontRecognizerResultCtor;
@CordovaProperty() JordanIdFrontRecognizer: JordanIdFrontRecognizerCtor;
@CordovaProperty() KuwaitIdBackRecognizerResult: KuwaitIdBackRecognizerResultCtor;
@CordovaProperty() KuwaitIdBackRecognizer: KuwaitIdBackRecognizerCtor;
@CordovaProperty() KuwaitIdFrontRecognizerResult: KuwaitIdFrontRecognizerResultCtor;
@CordovaProperty() KuwaitIdFrontRecognizer: KuwaitIdFrontRecognizerCtor;
@CordovaProperty() MalaysiaDlFrontRecognizerResult: MalaysiaDlFrontRecognizerResultCtor;
@CordovaProperty() MalaysiaDlFrontRecognizer: MalaysiaDlFrontRecognizerCtor;
@CordovaProperty() MalaysiaMyTenteraRecognizerResult: MalaysiaMyTenteraRecognizerResultCtor;
@CordovaProperty() MalaysiaMyTenteraRecognizer: MalaysiaMyTenteraRecognizerCtor;
@CordovaProperty() MexicoVoterIdFrontRecognizerResult: MexicoVoterIdFrontRecognizerResultCtor;
@CordovaProperty() MexicoVoterIdFrontRecognizer: MexicoVoterIdFrontRecognizerCtor;
@CordovaProperty() MoroccoIdBackRecognizerResult: MoroccoIdBackRecognizerResultCtor;
@CordovaProperty() MoroccoIdBackRecognizer: MoroccoIdBackRecognizerCtor;
@CordovaProperty() MoroccoIdFrontRecognizerResult: MoroccoIdFrontRecognizerResultCtor;
@CordovaProperty() MoroccoIdFrontRecognizer: MoroccoIdFrontRecognizerCtor;
@CordovaProperty() MrtdCombinedRecognizerResult: MrtdCombinedRecognizerResultCtor;
@CordovaProperty() MrtdCombinedRecognizer: MrtdCombinedRecognizerCtor;
@CordovaProperty() MrtdRecognizerResult: MrtdRecognizerResultCtor;
@CordovaProperty() MrtdRecognizer: MrtdRecognizerCtor;
@CordovaProperty() MyKadBackRecognizerResult: MyKadBackRecognizerResultCtor;
@CordovaProperty() MyKadBackRecognizer: MyKadBackRecognizerCtor;
@CordovaProperty() MyKadFrontRecognizerResult: MyKadFrontRecognizerResultCtor;
@CordovaProperty() MyKadFrontRecognizer: MyKadFrontRecognizerCtor;
@CordovaProperty() NewZealandDlFrontRecognizerResult: NewZealandDlFrontRecognizerResultCtor;
@CordovaProperty() NewZealandDlFrontRecognizer: NewZealandDlFrontRecognizerCtor;
@CordovaProperty() Pdf417RecognizerResult: Pdf417RecognizerResultCtor;
@CordovaProperty() Pdf417Recognizer: Pdf417RecognizerCtor;
@CordovaProperty() PolandCombinedRecognizerResult: PolandCombinedRecognizerResultCtor;
@CordovaProperty() PolandCombinedRecognizer: PolandCombinedRecognizerCtor;
@CordovaProperty() PolandIdBackRecognizerResult: PolandIdBackRecognizerResultCtor;
@CordovaProperty() PolandIdBackRecognizer: PolandIdBackRecognizerCtor;
@CordovaProperty() PolandIdFrontRecognizerResult: PolandIdFrontRecognizerResultCtor;
@CordovaProperty() PolandIdFrontRecognizer: PolandIdFrontRecognizerCtor;
@CordovaProperty() RomaniaIdFrontRecognizerResult: RomaniaIdFrontRecognizerResultCtor;
@CordovaProperty() RomaniaIdFrontRecognizer: RomaniaIdFrontRecognizerCtor;
@CordovaProperty() SerbiaCombinedRecognizerResult: SerbiaCombinedRecognizerResultCtor;
@CordovaProperty() SerbiaCombinedRecognizer: SerbiaCombinedRecognizerCtor;
@CordovaProperty() SerbiaIdBackRecognizerResult: SerbiaIdBackRecognizerResultCtor;
@CordovaProperty() SerbiaIdBackRecognizer: SerbiaIdBackRecognizerCtor;
@CordovaProperty() SerbiaIdFrontRecognizerResult: SerbiaIdFrontRecognizerResultCtor;
@CordovaProperty() SerbiaIdFrontRecognizer: SerbiaIdFrontRecognizerCtor;
@CordovaProperty() SimNumberRecognizerResult: SimNumberRecognizerResultCtor;
@CordovaProperty() SimNumberRecognizer: SimNumberRecognizerCtor;
@CordovaProperty() SingaporeChangiEmployeeIdRecognizerResult: SingaporeChangiEmployeeIdRecognizerResultCtor;
@CordovaProperty() SingaporeChangiEmployeeIdRecognizer: SingaporeChangiEmployeeIdRecognizerCtor;
@CordovaProperty() SingaporeCombinedRecognizerResult: SingaporeCombinedRecognizerResultCtor;
@CordovaProperty() SingaporeCombinedRecognizer: SingaporeCombinedRecognizerCtor;
@CordovaProperty() SingaporeDlFrontRecognizerResult: SingaporeDlFrontRecognizerResultCtor;
@CordovaProperty() SingaporeDlFrontRecognizer: SingaporeDlFrontRecognizerCtor;
@CordovaProperty() SingaporeIdBackRecognizerResult: SingaporeIdBackRecognizerResultCtor;
@CordovaProperty() SingaporeIdBackRecognizer: SingaporeIdBackRecognizerCtor;
@CordovaProperty() SingaporeIdFrontRecognizerResult: SingaporeIdFrontRecognizerResultCtor;
@CordovaProperty() SingaporeIdFrontRecognizer: SingaporeIdFrontRecognizerCtor;
@CordovaProperty() SlovakiaCombinedRecognizerResult: SlovakiaCombinedRecognizerResultCtor;
@CordovaProperty() SlovakiaCombinedRecognizer: SlovakiaCombinedRecognizerCtor;
@CordovaProperty() SlovakiaIdBackRecognizerResult: SlovakiaIdBackRecognizerResultCtor;
@CordovaProperty() SlovakiaIdBackRecognizer: SlovakiaIdBackRecognizerCtor;
@CordovaProperty() SlovakiaIdFrontRecognizerResult: SlovakiaIdFrontRecognizerResultCtor;
@CordovaProperty() SlovakiaIdFrontRecognizer: SlovakiaIdFrontRecognizerCtor;
@CordovaProperty() SloveniaCombinedRecognizerResult: SloveniaCombinedRecognizerResultCtor;
@CordovaProperty() SloveniaCombinedRecognizer: SloveniaCombinedRecognizerCtor;
@CordovaProperty() SloveniaIdBackRecognizerResult: SloveniaIdBackRecognizerResultCtor;
@CordovaProperty() SloveniaIdBackRecognizer: SloveniaIdBackRecognizerCtor;
@CordovaProperty() SloveniaIdFrontRecognizerResult: SloveniaIdFrontRecognizerResultCtor;
@CordovaProperty() SloveniaIdFrontRecognizer: SloveniaIdFrontRecognizerCtor;
@CordovaProperty() SpainDlFrontRecognizerResult: SpainDlFrontRecognizerResultCtor;
@CordovaProperty() SpainDlFrontRecognizer: SpainDlFrontRecognizerCtor;
@CordovaProperty() SwedenDlFrontRecognizerResult: SwedenDlFrontRecognizerResultCtor;
@CordovaProperty() SwedenDlFrontRecognizer: SwedenDlFrontRecognizerCtor;
@CordovaProperty() SwitzerlandDlFrontRecognizerResult: SwitzerlandDlFrontRecognizerResultCtor;
@CordovaProperty() SwitzerlandDlFrontRecognizer: SwitzerlandDlFrontRecognizerCtor;
@CordovaProperty() SwitzerlandDlBackRecognizerResult: SwitzerlandDlBackRecognizerResultCtor;
@CordovaProperty() SwitzerlandDlBackRecognizer: SwitzerlandDlBackRecognizerCtor;
@CordovaProperty() SwitzerlandIdFrontRecognizerResult: SwitzerlandIdFrontRecognizerResultCtor;
@CordovaProperty() SwitzerlandIdFrontRecognizer: SwitzerlandIdFrontRecognizerCtor;
@CordovaProperty() SwitzerlandPassportRecognizerResult: SwitzerlandPassportRecognizerResultCtor;
@CordovaProperty() SwitzerlandPassportRecognizer: SwitzerlandPassportRecognizerCtor;
@CordovaProperty() UnitedArabEmiratesDlFrontRecognizerResult: UnitedArabEmiratesDlFrontRecognizerResultCtor;
@CordovaProperty() UnitedArabEmiratesDlFrontRecognizer: UnitedArabEmiratesDlFrontRecognizerCtor;
@CordovaProperty() UnitedArabEmiratesIdBackRecognizerResult: UnitedArabEmiratesIdBackRecognizerResultCtor;
@CordovaProperty() UnitedArabEmiratesIdBackRecognizer: UnitedArabEmiratesIdBackRecognizerCtor;
@CordovaProperty() UnitedArabEmiratesIdFrontRecognizerResult: UnitedArabEmiratesIdFrontRecognizerResultCtor;
@CordovaProperty() UnitedArabEmiratesIdFrontRecognizer: UnitedArabEmiratesIdFrontRecognizerCtor;
@CordovaProperty() VinRecognizerResult: VinRecognizerResultCtor;
@CordovaProperty() VinRecognizer: VinRecognizerCtor;
@CordovaProperty() UsdlRecognizerResult: UsdlRecognizerResultCtor;
@CordovaProperty() UsdlRecognizer: UsdlRecognizerCtor;
@CordovaProperty() UsdlCombinedRecognizerResult: UsdlCombinedRecognizerResultCtor;
@CordovaProperty() UsdlCombinedRecognizer: UsdlCombinedRecognizerCtor;
@CordovaProperty() BlinkIdRecognizer: BlinkIdRecognizerCtor;
@CordovaProperty() BlinkIdOverlaySettings: BlinkIdOverlaySettingsCtor;
@CordovaProperty() BlinkIdRecognizerResult: BlinkIdRecognizerResultCtor;
} | the_stack |
import {earcut} from '@math.gl/polygon';
import type {
BinaryAttribute,
BinaryFeatures,
FlatFeature,
FlatPoint,
FlatLineString,
FlatPolygon,
GeojsonGeometryInfo,
TypedArray
} from '@loaders.gl/schema';
import {PropArrayConstructor, Lines, Points, Polygons} from './flat-geojson-to-binary-types';
/**
* Convert binary features to flat binary arrays. Similar to
* `geojsonToBinary` helper function, except that it expects
* a binary representation of the feature data, which enables
* 2X-3X speed increase in parse speed, compared to using
* geoJSON. See `binary-vector-tile/VectorTileFeature` for
* data format detais
*
* @param features
* @param geometryInfo
* @param options
* @returns filled arrays
*/
export function flatGeojsonToBinary(
features: FlatFeature[],
geometryInfo: GeojsonGeometryInfo,
options?: FlatGeojsonToBinaryOptions
) {
const propArrayTypes = extractNumericPropTypes(features);
const numericPropKeys = Object.keys(propArrayTypes).filter((k) => propArrayTypes[k] !== Array);
return fillArrays(
features,
{
propArrayTypes,
...geometryInfo
},
{
numericPropKeys: (options && options.numericPropKeys) || numericPropKeys,
PositionDataType: options ? options.PositionDataType : Float32Array
}
);
}
/**
* Options for `flatGeojsonToBinary`
*/
export type FlatGeojsonToBinaryOptions = {
numericPropKeys?: string[];
PositionDataType?: Float32ArrayConstructor | Float64ArrayConstructor;
};
export const TEST_EXPORTS = {
extractNumericPropTypes
};
/**
* Extracts properties that are always numeric
*
* @param features
* @returns object with numeric types
*/
function extractNumericPropTypes(features: FlatFeature[]): {
[key: string]: PropArrayConstructor;
} {
const propArrayTypes = {};
for (const feature of features) {
if (feature.properties) {
for (const key in feature.properties) {
// If property has not been seen before, or if property has been numeric
// in all previous features, check if numeric in this feature
// If not numeric, Array is stored to prevent rechecking in the future
// Additionally, detects if 64 bit precision is required
const val = feature.properties[key];
propArrayTypes[key] = deduceArrayType(val, propArrayTypes[key]);
}
}
}
return propArrayTypes;
}
/**
* Fills coordinates into pre-allocated typed arrays
*
* @param features
* @param geometryInfo
* @param options
* @returns an accessor object with value and size keys
*/
// eslint-disable-next-line complexity
function fillArrays(
features: FlatFeature[],
geometryInfo: GeojsonGeometryInfo & {
propArrayTypes: {[key: string]: PropArrayConstructor};
},
options: FlatGeojsonToBinaryOptions
) {
const {
pointPositionsCount,
pointFeaturesCount,
linePositionsCount,
linePathsCount,
lineFeaturesCount,
polygonPositionsCount,
polygonObjectsCount,
polygonRingsCount,
polygonFeaturesCount,
propArrayTypes,
coordLength
} = geometryInfo;
const {numericPropKeys = [], PositionDataType = Float32Array} = options;
const hasGlobalId = features[0] && 'id' in features[0];
const GlobalFeatureIdsDataType = features.length > 65535 ? Uint32Array : Uint16Array;
const points: Points = {
type: 'Point',
positions: new PositionDataType(pointPositionsCount * coordLength),
globalFeatureIds: new GlobalFeatureIdsDataType(pointPositionsCount),
featureIds:
pointFeaturesCount > 65535
? new Uint32Array(pointPositionsCount)
: new Uint16Array(pointPositionsCount),
numericProps: {},
properties: [],
fields: []
};
const lines: Lines = {
type: 'LineString',
pathIndices:
linePositionsCount > 65535
? new Uint32Array(linePathsCount + 1)
: new Uint16Array(linePathsCount + 1),
positions: new PositionDataType(linePositionsCount * coordLength),
globalFeatureIds: new GlobalFeatureIdsDataType(linePositionsCount),
featureIds:
lineFeaturesCount > 65535
? new Uint32Array(linePositionsCount)
: new Uint16Array(linePositionsCount),
numericProps: {},
properties: [],
fields: []
};
const polygons: Polygons = {
type: 'Polygon',
polygonIndices:
polygonPositionsCount > 65535
? new Uint32Array(polygonObjectsCount + 1)
: new Uint16Array(polygonObjectsCount + 1),
primitivePolygonIndices:
polygonPositionsCount > 65535
? new Uint32Array(polygonRingsCount + 1)
: new Uint16Array(polygonRingsCount + 1),
positions: new PositionDataType(polygonPositionsCount * coordLength),
triangles: [],
globalFeatureIds: new GlobalFeatureIdsDataType(polygonPositionsCount),
featureIds:
polygonFeaturesCount > 65535
? new Uint32Array(polygonPositionsCount)
: new Uint16Array(polygonPositionsCount),
numericProps: {},
properties: [],
fields: []
};
// Instantiate numeric properties arrays; one value per vertex
for (const object of [points, lines, polygons]) {
for (const propName of numericPropKeys) {
// If property has been numeric in all previous features in which the property existed, check
// if numeric in this feature
const T = propArrayTypes[propName];
object.numericProps[propName] = new T(object.positions.length / coordLength) as TypedArray;
}
}
// Set last element of path/polygon indices as positions length
lines.pathIndices[linePathsCount] = linePositionsCount;
polygons.polygonIndices[polygonObjectsCount] = polygonPositionsCount;
polygons.primitivePolygonIndices[polygonRingsCount] = polygonPositionsCount;
const indexMap = {
pointPosition: 0,
pointFeature: 0,
linePosition: 0,
linePath: 0,
lineFeature: 0,
polygonPosition: 0,
polygonObject: 0,
polygonRing: 0,
polygonFeature: 0,
feature: 0
};
for (const feature of features) {
const geometry = feature.geometry;
const properties = feature.properties || {};
switch (geometry.type) {
case 'Point':
handlePoint(geometry, points, indexMap, coordLength, properties);
points.properties.push(keepStringProperties(properties, numericPropKeys));
if (hasGlobalId) {
points.fields.push({id: feature.id});
}
indexMap.pointFeature++;
break;
case 'LineString':
handleLineString(geometry, lines, indexMap, coordLength, properties);
lines.properties.push(keepStringProperties(properties, numericPropKeys));
if (hasGlobalId) {
lines.fields.push({id: feature.id});
}
indexMap.lineFeature++;
break;
case 'Polygon':
handlePolygon(geometry, polygons, indexMap, coordLength, properties);
polygons.properties.push(keepStringProperties(properties, numericPropKeys));
if (hasGlobalId) {
polygons.fields.push({id: feature.id});
}
indexMap.polygonFeature++;
break;
default:
throw new Error('Invalid geometry type');
}
indexMap.feature++;
}
// Wrap each array in an accessor object with value and size keys
return makeAccessorObjects(points, lines, polygons, coordLength);
}
/**
* Fills (Multi)Point coordinates into points object of arrays
*
* @param geometry
* @param points
* @param indexMap
* @param coordLength
* @param properties
*/
function handlePoint(
geometry: FlatPoint,
points: Points,
indexMap: {
pointPosition: number;
pointFeature: number;
linePosition?: number;
linePath?: number;
lineFeature?: number;
polygonPosition?: number;
polygonObject?: number;
polygonRing?: number;
polygonFeature?: number;
feature: number;
},
coordLength: number,
properties: {[x: string]: string | number | boolean | null}
): void {
points.positions.set(geometry.data, indexMap.pointPosition * coordLength);
const nPositions = geometry.data.length / coordLength;
fillNumericProperties(points, properties, indexMap.pointPosition, nPositions);
points.globalFeatureIds.fill(
indexMap.feature,
indexMap.pointPosition,
indexMap.pointPosition + nPositions
);
points.featureIds.fill(
indexMap.pointFeature,
indexMap.pointPosition,
indexMap.pointPosition + nPositions
);
indexMap.pointPosition += nPositions;
}
/**
* Fills (Multi)LineString coordinates into lines object of arrays
*
* @param geometry
* @param lines
* @param indexMap
* @param coordLength
* @param properties
*/
function handleLineString(
geometry: FlatLineString,
lines: Lines,
indexMap: {
pointPosition?: number;
pointFeature?: number;
linePosition: number;
linePath: number;
lineFeature: number;
polygonPosition?: number;
polygonObject?: number;
polygonRing?: number;
polygonFeature?: number;
feature: number;
},
coordLength: number,
properties: {[x: string]: string | number | boolean | null}
): void {
lines.positions.set(geometry.data, indexMap.linePosition * coordLength);
const nPositions = geometry.data.length / coordLength;
fillNumericProperties(lines, properties, indexMap.linePosition, nPositions);
lines.globalFeatureIds.fill(
indexMap.feature,
indexMap.linePosition,
indexMap.linePosition + nPositions
);
lines.featureIds.fill(
indexMap.lineFeature,
indexMap.linePosition,
indexMap.linePosition + nPositions
);
for (let i = 0, il = geometry.indices.length; i < il; ++i) {
// Extract range of data we are working with, defined by start
// and end indices (these index into the geometry.data array)
const start = geometry.indices[i];
const end =
i === il - 1
? geometry.data.length // last line, so read to end of data
: geometry.indices[i + 1]; // start index for next line
lines.pathIndices[indexMap.linePath++] = indexMap.linePosition;
indexMap.linePosition += (end - start) / coordLength;
}
}
/**
* Fills (Multi)Polygon coordinates into polygons object of arrays
*
* @param geometry
* @param polygons
* @param indexMap
* @param coordLength
* @param properties
*/
function handlePolygon(
geometry: FlatPolygon,
polygons: Polygons,
indexMap: {
pointPosition?: number;
pointFeature?: number;
linePosition?: number;
linePath?: number;
lineFeature?: number;
polygonPosition: number;
polygonObject: number;
polygonRing: number;
polygonFeature: number;
feature: number;
},
coordLength: number,
properties: {[x: string]: string | number | boolean | null}
): void {
polygons.positions.set(geometry.data, indexMap.polygonPosition * coordLength);
const nPositions = geometry.data.length / coordLength;
fillNumericProperties(polygons, properties, indexMap.polygonPosition, nPositions);
polygons.globalFeatureIds.fill(
indexMap.feature,
indexMap.polygonPosition,
indexMap.polygonPosition + nPositions
);
polygons.featureIds.fill(
indexMap.polygonFeature,
indexMap.polygonPosition,
indexMap.polygonPosition + nPositions
);
// Unlike Point & LineString geometry.indices is a 2D array
for (let l = 0, ll = geometry.indices.length; l < ll; ++l) {
const startPosition = indexMap.polygonPosition;
polygons.polygonIndices[indexMap.polygonObject++] = startPosition;
const areas = geometry.areas[l];
const indices = geometry.indices[l];
const nextIndices = geometry.indices[l + 1];
for (let i = 0, il = indices.length; i < il; ++i) {
const start = indices[i];
const end =
i === il - 1
? // last line, so either read to:
nextIndices === undefined
? geometry.data.length // end of data (no next indices)
: nextIndices[0] // start of first line in nextIndices
: indices[i + 1]; // start index for next line
polygons.primitivePolygonIndices[indexMap.polygonRing++] = indexMap.polygonPosition;
indexMap.polygonPosition += (end - start) / coordLength;
}
const endPosition = indexMap.polygonPosition;
triangulatePolygon(polygons, areas, indices, {startPosition, endPosition, coordLength});
}
}
/**
* Triangulate polygon using earcut
*
* @param polygons
* @param areas
* @param indices
* @param param3
*/
function triangulatePolygon(
polygons: Polygons,
areas: number[],
indices: number[],
{
startPosition,
endPosition,
coordLength
}: {startPosition: number; endPosition: number; coordLength: number}
): void {
const start = startPosition * coordLength;
const end = endPosition * coordLength;
// Extract positions and holes for just this polygon
const polygonPositions = polygons.positions.subarray(start, end);
// Holes are referenced relative to outer polygon
const offset = indices[0];
const holes = indices.slice(1).map((n: number) => (n - offset) / coordLength);
// Compute triangulation
const triangles = earcut(polygonPositions, holes, coordLength, areas);
// Indices returned by triangulation are relative to start
// of polygon, so we need to offset
for (let t = 0, tl = triangles.length; t < tl; ++t) {
polygons.triangles.push(startPosition + triangles[t]);
}
}
/**
* Wraps an object containing array into accessors
*
* @param obj
* @param size
*/
function wrapProps(
obj: {[key: string]: TypedArray},
size: number
): {[key: string]: BinaryAttribute} {
const returnObj = {};
for (const key in obj) {
returnObj[key] = {value: obj[key], size};
}
return returnObj;
}
/**
* Wrap each array in an accessor object with value and size keys
*
* @param points
* @param lines
* @param polygons
* @param coordLength
* @returns object
*/
function makeAccessorObjects(
points: Points,
lines: Lines,
polygons: Polygons,
coordLength: number
): BinaryFeatures {
return {
points: {
...points,
positions: {value: points.positions, size: coordLength},
globalFeatureIds: {value: points.globalFeatureIds, size: 1},
featureIds: {value: points.featureIds, size: 1},
numericProps: wrapProps(points.numericProps, 1)
},
lines: {
...lines,
positions: {value: lines.positions, size: coordLength},
pathIndices: {value: lines.pathIndices, size: 1},
globalFeatureIds: {value: lines.globalFeatureIds, size: 1},
featureIds: {value: lines.featureIds, size: 1},
numericProps: wrapProps(lines.numericProps, 1)
},
polygons: {
...polygons,
positions: {value: polygons.positions, size: coordLength},
polygonIndices: {value: polygons.polygonIndices, size: 1},
primitivePolygonIndices: {value: polygons.primitivePolygonIndices, size: 1},
triangles: {value: new Uint32Array(polygons.triangles), size: 1},
globalFeatureIds: {value: polygons.globalFeatureIds, size: 1},
featureIds: {value: polygons.featureIds, size: 1},
numericProps: wrapProps(polygons.numericProps, 1)
}
};
}
/**
* Add numeric properties to object
*
* @param object
* @param properties
* @param index
* @param length
*/
function fillNumericProperties(
object: Points | Lines | Polygons,
properties: {[x: string]: string | number | boolean | null},
index: number,
length: number
): void {
for (const numericPropName in object.numericProps) {
if (numericPropName in properties) {
const value = properties[numericPropName] as number;
object.numericProps[numericPropName].fill(value, index, index + length);
}
}
}
/**
* Keep string properties in object
*
* @param properties
* @param numericKeys
* @returns object
*/
function keepStringProperties(
properties: {[x: string]: string | number | boolean | null},
numericKeys: string[]
) {
const props = {};
for (const key in properties) {
if (!numericKeys.includes(key)) {
props[key] = properties[key];
}
}
return props;
}
/**
*
* Deduce correct array constructor to use for a given value
*
* @param x value to test
* @param constructor previous constructor deduced
* @returns PropArrayConstructor
*/
function deduceArrayType(x: any, constructor: PropArrayConstructor): PropArrayConstructor {
if (constructor === Array || !Number.isFinite(x)) {
return Array;
}
// If this or previous value required 64bits use Float64Array
return constructor === Float64Array || Math.fround(x) !== x ? Float64Array : Float32Array;
} | the_stack |
import NeovimStore from './store';
import { compositionStart, compositionEnd, inputToNeovim, notifyFocusChanged } from './actions';
import log from '../log';
const OnDarwin = global.process.platform === 'darwin';
const IsAlpha = /^[a-zA-Z]$/;
export default class NeovimInput {
element: HTMLInputElement;
// fake span element to measure text width of preedit input
fake_element: HTMLSpanElement;
ime_running: boolean; // XXX: Local state!
static shouldIgnoreOnKeydown(event: KeyboardEvent) {
const { ctrlKey, shiftKey, altKey, keyCode, metaKey } = event;
return (
(!ctrlKey && !altKey && !metaKey) ||
(shiftKey && keyCode === 16) ||
(ctrlKey && keyCode === 17) ||
(altKey && keyCode === 18) ||
(metaKey && keyCode === 91)
);
}
// Note:
// Workaround when KeyboardEvent.key is not available.
static getVimSpecialCharFromKeyCode(key_code: number, shift: boolean) {
switch (key_code) {
case 0:
return 'Nul';
case 8:
return 'BS';
case 9:
return 'Tab';
case 10:
return 'NL';
case 13:
return 'CR';
case 33:
return 'PageUp';
case 34:
return 'PageDown';
case 27:
return 'Esc';
case 32:
return 'Space';
case 35:
return 'End';
case 36:
return 'Home';
case 37:
return 'Left';
case 38:
return 'Up';
case 39:
return 'Right';
case 40:
return 'Down';
case 45:
return 'Insert';
case 46:
return 'Del';
case 47:
return 'Help';
case 92:
return 'Bslash';
case 112:
return 'F1';
case 113:
return 'F2';
case 114:
return 'F3';
case 115:
return 'F4';
case 116:
return 'F5';
case 117:
return 'F6';
case 118:
return 'F7';
case 119:
return 'F8';
case 120:
return 'F9';
case 121:
return 'F10';
case 122:
return 'F11';
case 123:
return 'F12';
case 124:
return 'Bar'; // XXX
case 127:
return 'Del'; // XXX
case 188:
return shift ? 'LT' : null;
default:
return null;
}
}
// Note:
// Special key handling using KeyboardEvent.key. Thank you @romgrk for the idea.
// https://www.w3.org/TR/DOM-Level-3-Events-key/
static getVimSpecialCharFromKey(event: KeyboardEvent) {
const key = event.key;
if (key.length === 1) {
switch (key) {
case '<':
return event.ctrlKey || event.altKey ? 'LT' : null;
case ' ':
return 'Space';
case '\0':
return 'Nul';
default:
return null;
}
}
if (key[0] === 'F') {
// F1, F2, F3, ...
return /^F\d+/.test(key) ? key : null;
}
const ctrl = event.ctrlKey;
const key_code = event.keyCode;
switch (key) {
case 'Escape': {
if (ctrl && key_code !== 27) {
// Note:
// When <C-[> is input
// XXX:
// Keycode of '[' is not available because it is 219 in OS X
// and it is not for '['.
return '[';
} else {
return 'Esc';
}
}
case 'Backspace': {
if (ctrl && key_code === 72) {
// Note:
// When <C-h> is input (72 is key code of 'h')
return 'h';
} else {
return 'BS';
}
}
case 'Tab': {
if (ctrl && key_code === 73) {
// Note:
// When <C-i> is input (73 is key code of 'i')
return 'i';
} else {
return 'Tab';
}
}
case 'Enter': {
// Note: Should consider <NL>?
if (ctrl && key_code === 77) {
// Note:
// When <C-m> is input (77 is key code of 'm')
return 'm';
} else if (ctrl && key_code === 67) {
// XXX:
// This is workaround for a bug of Chromium. Ctrl+c emits wrong KeyboardEvent.key.
// (It should be "\uxxxx" but actually "Enter")
// https://github.com/rhysd/NyaoVim/issues/37
return 'c';
} else {
return 'CR';
}
}
case 'PageUp':
return 'PageUp';
case 'PageDown':
return 'PageDown';
case 'End':
return 'End';
case 'Home':
return 'Home';
case 'ArrowLeft':
return 'Left';
case 'ArrowUp':
return 'Up';
case 'ArrowRight':
return 'Right';
case 'ArrowDown':
return 'Down';
case 'Insert':
return 'Insert';
case 'Delete':
return 'Del';
case 'Help':
return 'Help';
case 'Unidentified':
return null;
default:
return null;
}
}
static getVimSpecialCharInput(event: KeyboardEvent) {
const should_fallback = event.key === undefined || (event.key === '\0' && event.keyCode !== 0);
const special_char = should_fallback
? NeovimInput.getVimSpecialCharFromKeyCode(event.keyCode, event.shiftKey)
: NeovimInput.getVimSpecialCharFromKey(event);
if (!special_char) {
return null;
}
let vim_input = '<';
if (event.ctrlKey) {
vim_input += 'C-';
}
if (event.metaKey) {
vim_input += 'D-';
}
if (event.altKey) {
vim_input += 'A-';
}
// Note: <LT> is a special case where shift should not be handled.
if (event.shiftKey && special_char !== 'LT') {
vim_input += 'S-';
}
vim_input += special_char + '>';
return vim_input;
}
static replaceKeyToAvoidCtrlShiftSpecial(ctrl: boolean, shift: boolean, key: string) {
if (!ctrl || shift) {
return key;
}
// Note:
// These characters are especially replaced in Vim frontend.
// https://github.com/vim/vim/blob/d58b0f982ad758c59abe47627216a15497e9c3c1/src/gui_w32.c#L1956-L1989
// Issue:
// https://github.com/rhysd/NyaoVim/issues/87
switch (key) {
case '6':
return '^';
case '-':
return '_';
case '2':
return '@';
default:
return key;
}
}
static getVimInputFromKeyCode(event: KeyboardEvent) {
let modifiers = '';
if (event.ctrlKey) {
modifiers += 'C-';
}
if (event.metaKey) {
modifiers += 'D-';
}
if (event.altKey) {
modifiers += 'A-';
}
// Note: <LT> is a special case where shift should not be handled.
if (event.shiftKey) {
modifiers += 'S-';
}
let vim_input = NeovimInput.replaceKeyToAvoidCtrlShiftSpecial(
event.ctrlKey,
event.shiftKey,
String.fromCharCode(event.keyCode).toLowerCase(),
);
if (modifiers !== '') {
vim_input = `<${modifiers}${vim_input}>`;
}
return vim_input;
}
constructor(private readonly store: NeovimStore) {
this.ime_running = false;
this.element = this.store.dom.input as HTMLInputElement;
this.element.addEventListener('compositionstart', this.startComposition.bind(this));
this.element.addEventListener('compositionend', this.endComposition.bind(this));
this.element.addEventListener('keydown', this.onInputNonText.bind(this));
this.element.addEventListener('input', this.onInputText.bind(this));
this.element.addEventListener('blur', this.onBlur.bind(this));
this.element.addEventListener('focus', this.onFocus.bind(this));
this.store.on('cursor', this.updateElementPos.bind(this));
this.store.on('font-size-changed', this.updateFontSize.bind(this));
this.fake_element = this.store.dom.preedit as HTMLSpanElement;
const { face } = this.store.font_attr;
this.element.style.fontFamily = face;
this.fake_element.style.fontFamily = face;
this.updateFontSize();
this.focus();
}
startComposition(_: Event) {
log.debug('start composition');
// make <input> visible to show preedit
this.element.style.color = this.store.fg_color;
this.element.style.backgroundColor = this.store.bg_color;
this.element.style.width = 'auto';
// hide cursor
this.store.dispatcher.dispatch(compositionStart());
this.ime_running = true;
}
endComposition(event: CompositionEvent) {
log.debug('end composition');
this.inputToNeovim(event.data, event);
// hide HTMLInputElement
this.element.style.color = 'transparent';
this.element.style.backgroundColor = 'transparent';
this.element.style.width = '1px';
// show cursor
this.store.dispatcher.dispatch(compositionEnd());
this.ime_running = false;
}
focus() {
this.element.focus();
}
onFocus() {
this.store.dispatcher.dispatch(notifyFocusChanged(true));
// Note:
// Neovim frontend has responsibility to emit 'FocusGained'.
// :execute 'normal!' "\<FocusGained>" is available.
// (it seems undocumented.)
this.store.dispatcher.dispatch(inputToNeovim('<FocusGained>'));
}
onBlur(e: Event) {
e.preventDefault();
this.store.dispatcher.dispatch(notifyFocusChanged(false));
// Note:
// Neovim frontend has responsibility to emit 'FocusLost'.
// :execute 'normal!' "\<FocusLost>" is available.
// (it seems undocumented.)
this.store.dispatcher.dispatch(inputToNeovim('<FocusLost>'));
}
// Note:
// Assumes keydown event is always fired before input event
onInputNonText(event: KeyboardEvent) {
log.debug('Keydown event:', event);
if (this.ime_running) {
log.debug('IME is running. Input canceled.');
return;
}
const special_sequence = NeovimInput.getVimSpecialCharInput(event);
if (special_sequence) {
this.inputToNeovim(special_sequence, event);
return;
}
if (NeovimInput.shouldIgnoreOnKeydown(event)) {
return;
}
const should_osx_workaround = OnDarwin && event.altKey && !event.ctrlKey && this.store.mode === 'normal';
if (this.store.alt_key_disabled && event.altKey) {
// Note: Overwrite 'altKey' to false to disable alt key input.
Object.defineProperty(event, 'altKey', { value: false });
}
if (this.store.meta_key_disabled && event.metaKey) {
// Note:
// Simply ignore input with metakey if metakey is disabled. This aims to delegate the key input
// to menu items on OS X.
return;
}
if (should_osx_workaround) {
// Note:
//
// In OS X, option + {key} sequences input special characters which can't be
// input with keyboard normally. (e.g. option+a -> å)
// MacVim accepts the special characters only in insert mode, otherwise <A-{char}>
// is emitted.
//
this.inputToNeovim(NeovimInput.getVimInputFromKeyCode(event), event);
return;
}
if (event.key) {
if (event.key.length === 1) {
let input = '<';
if (event.ctrlKey) {
input += 'C-';
}
if (event.metaKey) {
input += 'D-';
}
if (event.altKey) {
input += 'A-';
}
if (event.shiftKey && IsAlpha.test(event.key)) {
// Note:
// If input is not an alphabetical character, it already considers
// Shift modifier.
// e.g. Ctrl+Shift+2 -> event.key == '@'
// But for alphabets, Vim ignores the case. For example <C-s> is
// equivalent to <C-S>. So we need to specify <C-S-s> or <C-S-S>.
input += 'S-';
}
if (input === '<') {
// Note: No modifier was pressed
this.inputToNeovim(event.key, event);
} else {
const key = NeovimInput.replaceKeyToAvoidCtrlShiftSpecial(event.ctrlKey, event.shiftKey, event.key);
this.inputToNeovim(input + key + '>', event);
}
} else {
log.warn("Invalid key input on 'keydown': ", event.key);
}
} else {
this.inputToNeovim(NeovimInput.getVimInputFromKeyCode(event), event);
}
}
inputToNeovim(input: string, event: Event) {
this.store.dispatcher.dispatch(inputToNeovim(input));
log.debug('Input to neovim:', JSON.stringify(input));
event.preventDefault();
event.stopPropagation();
const t = event.target as HTMLInputElement;
if (t.value) {
t.value = '';
}
}
onInputText(event: KeyboardEvent) {
log.debug('Input event:', event);
if (this.ime_running) {
log.debug('IME is running. Input canceled.');
// update width of the input element
this.fake_element.innerText = this.element.value;
// to get the width of peedit area, show it just a moment
this.fake_element.style.display = 'inline';
const width = this.fake_element.getBoundingClientRect().width;
this.fake_element.style.display = 'none';
this.element.style.width = width + 'px';
return;
}
const t = event.target as HTMLInputElement;
if (t.value === '') {
log.warn('onInputText: Empty');
return;
}
const input = t.value !== '<' ? t.value : '<LT>';
this.inputToNeovim(input, event);
}
updateElementPos() {
const { line, col } = this.store.cursor;
const { width, height } = this.store.font_attr;
const x = col * width;
const y = line * height;
this.element.style.left = x + 'px';
this.element.style.top = y + 'px';
}
updateFontSize() {
// don't need to consider device pixel ratio for DOM elements
const { specified_px: font_size } = this.store.font_attr;
this.element.style.fontSize = font_size + 'px';
this.fake_element.style.fontSize = font_size + 'px';
}
} | the_stack |
import {FieldsSelection,Observable} from '@genql/runtime'
export type Scalars = {
Boolean: boolean,
Float: number,
ID: string,
Int: number,
String: string,
}
/** mutation root */
export interface mutation_root {
/** delete data from the table: "user" */
delete_user?: user_mutation_response
/** delete single row from the table: "user" */
delete_user_by_pk?: user
/** insert data into the table: "user" */
insert_user?: user_mutation_response
/** insert a single row into the table: "user" */
insert_user_one?: user
/** update data of the table: "user" */
update_user?: user_mutation_response
/** update single row of the table: "user" */
update_user_by_pk?: user
__typename: 'mutation_root'
}
/** column ordering options */
export type order_by = 'asc' | 'asc_nulls_first' | 'asc_nulls_last' | 'desc' | 'desc_nulls_first' | 'desc_nulls_last'
/** query root */
export interface query_root {
/** fetch data from the table: "user" */
user: user[]
/** fetch aggregated fields from the table: "user" */
user_aggregate: user_aggregate
/** fetch data from the table: "user" using primary key columns */
user_by_pk?: user
__typename: 'query_root'
}
/** subscription root */
export interface subscription_root {
/** fetch data from the table: "user" */
user: user[]
/** fetch aggregated fields from the table: "user" */
user_aggregate: user_aggregate
/** fetch data from the table: "user" using primary key columns */
user_by_pk?: user
__typename: 'subscription_root'
}
/** columns and relationships of "user" */
export interface user {
age: Scalars['Int']
id: Scalars['String']
name: Scalars['String']
__typename: 'user'
}
/** aggregated selection of "user" */
export interface user_aggregate {
aggregate?: user_aggregate_fields
nodes: user[]
__typename: 'user_aggregate'
}
/** aggregate fields of "user" */
export interface user_aggregate_fields {
avg?: user_avg_fields
count?: Scalars['Int']
max?: user_max_fields
min?: user_min_fields
stddev?: user_stddev_fields
stddev_pop?: user_stddev_pop_fields
stddev_samp?: user_stddev_samp_fields
sum?: user_sum_fields
var_pop?: user_var_pop_fields
var_samp?: user_var_samp_fields
variance?: user_variance_fields
__typename: 'user_aggregate_fields'
}
/** aggregate avg on columns */
export interface user_avg_fields {
age?: Scalars['Float']
__typename: 'user_avg_fields'
}
/** unique or primary key constraints on table "user" */
export type user_constraint = 'user_pkey'
/** aggregate max on columns */
export interface user_max_fields {
age?: Scalars['Int']
id?: Scalars['String']
name?: Scalars['String']
__typename: 'user_max_fields'
}
/** aggregate min on columns */
export interface user_min_fields {
age?: Scalars['Int']
id?: Scalars['String']
name?: Scalars['String']
__typename: 'user_min_fields'
}
/** response of any mutation on the table "user" */
export interface user_mutation_response {
/** number of affected rows by the mutation */
affected_rows: Scalars['Int']
/** data of the affected rows by the mutation */
returning: user[]
__typename: 'user_mutation_response'
}
/** select columns of table "user" */
export type user_select_column = 'age' | 'id' | 'name'
/** aggregate stddev on columns */
export interface user_stddev_fields {
age?: Scalars['Float']
__typename: 'user_stddev_fields'
}
/** aggregate stddev_pop on columns */
export interface user_stddev_pop_fields {
age?: Scalars['Float']
__typename: 'user_stddev_pop_fields'
}
/** aggregate stddev_samp on columns */
export interface user_stddev_samp_fields {
age?: Scalars['Float']
__typename: 'user_stddev_samp_fields'
}
/** aggregate sum on columns */
export interface user_sum_fields {
age?: Scalars['Int']
__typename: 'user_sum_fields'
}
/** update columns of table "user" */
export type user_update_column = 'age' | 'id' | 'name'
/** aggregate var_pop on columns */
export interface user_var_pop_fields {
age?: Scalars['Float']
__typename: 'user_var_pop_fields'
}
/** aggregate var_samp on columns */
export interface user_var_samp_fields {
age?: Scalars['Float']
__typename: 'user_var_samp_fields'
}
/** aggregate variance on columns */
export interface user_variance_fields {
age?: Scalars['Float']
__typename: 'user_variance_fields'
}
export type Query = query_root
export type Mutation = mutation_root
export type Subscription = subscription_root
/** expression to compare columns of type Int. All fields are combined with logical 'AND'. */
export interface Int_comparison_exp {_eq?: (Scalars['Int'] | null),_gt?: (Scalars['Int'] | null),_gte?: (Scalars['Int'] | null),_in?: (Scalars['Int'][] | null),_is_null?: (Scalars['Boolean'] | null),_lt?: (Scalars['Int'] | null),_lte?: (Scalars['Int'] | null),_neq?: (Scalars['Int'] | null),_nin?: (Scalars['Int'][] | null)}
/** expression to compare columns of type String. All fields are combined with logical 'AND'. */
export interface String_comparison_exp {_eq?: (Scalars['String'] | null),_gt?: (Scalars['String'] | null),_gte?: (Scalars['String'] | null),_ilike?: (Scalars['String'] | null),_in?: (Scalars['String'][] | null),_is_null?: (Scalars['Boolean'] | null),_like?: (Scalars['String'] | null),_lt?: (Scalars['String'] | null),_lte?: (Scalars['String'] | null),_neq?: (Scalars['String'] | null),_nilike?: (Scalars['String'] | null),_nin?: (Scalars['String'][] | null),_nlike?: (Scalars['String'] | null),_nsimilar?: (Scalars['String'] | null),_similar?: (Scalars['String'] | null)}
/** mutation root */
export interface mutation_rootRequest{
/** delete data from the table: "user" */
delete_user?: [{
/** filter the rows which have to be deleted */
where: user_bool_exp},user_mutation_responseRequest]
/** delete single row from the table: "user" */
delete_user_by_pk?: [{id: Scalars['String']},userRequest]
/** insert data into the table: "user" */
insert_user?: [{
/** the rows to be inserted */
objects: user_insert_input[],
/** on conflict condition */
on_conflict?: (user_on_conflict | null)},user_mutation_responseRequest]
/** insert a single row into the table: "user" */
insert_user_one?: [{
/** the row to be inserted */
object: user_insert_input,
/** on conflict condition */
on_conflict?: (user_on_conflict | null)},userRequest]
/** update data of the table: "user" */
update_user?: [{
/** increments the integer columns with given value of the filtered values */
_inc?: (user_inc_input | null),
/** sets the columns of the filtered rows to the given values */
_set?: (user_set_input | null),
/** filter the rows which have to be updated */
where: user_bool_exp},user_mutation_responseRequest]
/** update single row of the table: "user" */
update_user_by_pk?: [{
/** increments the integer columns with given value of the filtered values */
_inc?: (user_inc_input | null),
/** sets the columns of the filtered rows to the given values */
_set?: (user_set_input | null),pk_columns: user_pk_columns_input},userRequest]
__typename?: boolean | number
__scalar?: boolean | number
}
/** query root */
export interface query_rootRequest{
/** fetch data from the table: "user" */
user?: [{
/** distinct select on columns */
distinct_on?: (user_select_column[] | null),
/** limit the number of rows returned */
limit?: (Scalars['Int'] | null),
/** skip the first n rows. Use only with order_by */
offset?: (Scalars['Int'] | null),
/** sort the rows by one or more columns */
order_by?: (user_order_by[] | null),
/** filter the rows returned */
where?: (user_bool_exp | null)},userRequest] | userRequest
/** fetch aggregated fields from the table: "user" */
user_aggregate?: [{
/** distinct select on columns */
distinct_on?: (user_select_column[] | null),
/** limit the number of rows returned */
limit?: (Scalars['Int'] | null),
/** skip the first n rows. Use only with order_by */
offset?: (Scalars['Int'] | null),
/** sort the rows by one or more columns */
order_by?: (user_order_by[] | null),
/** filter the rows returned */
where?: (user_bool_exp | null)},user_aggregateRequest] | user_aggregateRequest
/** fetch data from the table: "user" using primary key columns */
user_by_pk?: [{id: Scalars['String']},userRequest]
__typename?: boolean | number
__scalar?: boolean | number
}
/** subscription root */
export interface subscription_rootRequest{
/** fetch data from the table: "user" */
user?: [{
/** distinct select on columns */
distinct_on?: (user_select_column[] | null),
/** limit the number of rows returned */
limit?: (Scalars['Int'] | null),
/** skip the first n rows. Use only with order_by */
offset?: (Scalars['Int'] | null),
/** sort the rows by one or more columns */
order_by?: (user_order_by[] | null),
/** filter the rows returned */
where?: (user_bool_exp | null)},userRequest] | userRequest
/** fetch aggregated fields from the table: "user" */
user_aggregate?: [{
/** distinct select on columns */
distinct_on?: (user_select_column[] | null),
/** limit the number of rows returned */
limit?: (Scalars['Int'] | null),
/** skip the first n rows. Use only with order_by */
offset?: (Scalars['Int'] | null),
/** sort the rows by one or more columns */
order_by?: (user_order_by[] | null),
/** filter the rows returned */
where?: (user_bool_exp | null)},user_aggregateRequest] | user_aggregateRequest
/** fetch data from the table: "user" using primary key columns */
user_by_pk?: [{id: Scalars['String']},userRequest]
__typename?: boolean | number
__scalar?: boolean | number
}
/** columns and relationships of "user" */
export interface userRequest{
age?: boolean | number
id?: boolean | number
name?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** aggregated selection of "user" */
export interface user_aggregateRequest{
aggregate?: user_aggregate_fieldsRequest
nodes?: userRequest
__typename?: boolean | number
__scalar?: boolean | number
}
/** aggregate fields of "user" */
export interface user_aggregate_fieldsRequest{
avg?: user_avg_fieldsRequest
count?: [{columns?: (user_select_column[] | null),distinct?: (Scalars['Boolean'] | null)}] | boolean | number
max?: user_max_fieldsRequest
min?: user_min_fieldsRequest
stddev?: user_stddev_fieldsRequest
stddev_pop?: user_stddev_pop_fieldsRequest
stddev_samp?: user_stddev_samp_fieldsRequest
sum?: user_sum_fieldsRequest
var_pop?: user_var_pop_fieldsRequest
var_samp?: user_var_samp_fieldsRequest
variance?: user_variance_fieldsRequest
__typename?: boolean | number
__scalar?: boolean | number
}
/** order by aggregate values of table "user" */
export interface user_aggregate_order_by {avg?: (user_avg_order_by | null),count?: (order_by | null),max?: (user_max_order_by | null),min?: (user_min_order_by | null),stddev?: (user_stddev_order_by | null),stddev_pop?: (user_stddev_pop_order_by | null),stddev_samp?: (user_stddev_samp_order_by | null),sum?: (user_sum_order_by | null),var_pop?: (user_var_pop_order_by | null),var_samp?: (user_var_samp_order_by | null),variance?: (user_variance_order_by | null)}
/** input type for inserting array relation for remote table "user" */
export interface user_arr_rel_insert_input {data: user_insert_input[],on_conflict?: (user_on_conflict | null)}
/** aggregate avg on columns */
export interface user_avg_fieldsRequest{
age?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** order by avg() on columns of table "user" */
export interface user_avg_order_by {age?: (order_by | null)}
/** Boolean expression to filter rows from the table "user". All fields are combined with a logical 'AND'. */
export interface user_bool_exp {_and?: ((user_bool_exp | null)[] | null),_not?: (user_bool_exp | null),_or?: ((user_bool_exp | null)[] | null),age?: (Int_comparison_exp | null),id?: (String_comparison_exp | null),name?: (String_comparison_exp | null)}
/** input type for incrementing integer column in table "user" */
export interface user_inc_input {age?: (Scalars['Int'] | null)}
/** input type for inserting data into table "user" */
export interface user_insert_input {age?: (Scalars['Int'] | null),id?: (Scalars['String'] | null),name?: (Scalars['String'] | null)}
/** aggregate max on columns */
export interface user_max_fieldsRequest{
age?: boolean | number
id?: boolean | number
name?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** order by max() on columns of table "user" */
export interface user_max_order_by {age?: (order_by | null),id?: (order_by | null),name?: (order_by | null)}
/** aggregate min on columns */
export interface user_min_fieldsRequest{
age?: boolean | number
id?: boolean | number
name?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** order by min() on columns of table "user" */
export interface user_min_order_by {age?: (order_by | null),id?: (order_by | null),name?: (order_by | null)}
/** response of any mutation on the table "user" */
export interface user_mutation_responseRequest{
/** number of affected rows by the mutation */
affected_rows?: boolean | number
/** data of the affected rows by the mutation */
returning?: userRequest
__typename?: boolean | number
__scalar?: boolean | number
}
/** input type for inserting object relation for remote table "user" */
export interface user_obj_rel_insert_input {data: user_insert_input,on_conflict?: (user_on_conflict | null)}
/** on conflict condition type for table "user" */
export interface user_on_conflict {constraint: user_constraint,update_columns: user_update_column[],where?: (user_bool_exp | null)}
/** ordering options when selecting data from "user" */
export interface user_order_by {age?: (order_by | null),id?: (order_by | null),name?: (order_by | null)}
/** primary key columns input for table: "user" */
export interface user_pk_columns_input {id: Scalars['String']}
/** input type for updating data in table "user" */
export interface user_set_input {age?: (Scalars['Int'] | null),id?: (Scalars['String'] | null),name?: (Scalars['String'] | null)}
/** aggregate stddev on columns */
export interface user_stddev_fieldsRequest{
age?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** order by stddev() on columns of table "user" */
export interface user_stddev_order_by {age?: (order_by | null)}
/** aggregate stddev_pop on columns */
export interface user_stddev_pop_fieldsRequest{
age?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** order by stddev_pop() on columns of table "user" */
export interface user_stddev_pop_order_by {age?: (order_by | null)}
/** aggregate stddev_samp on columns */
export interface user_stddev_samp_fieldsRequest{
age?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** order by stddev_samp() on columns of table "user" */
export interface user_stddev_samp_order_by {age?: (order_by | null)}
/** aggregate sum on columns */
export interface user_sum_fieldsRequest{
age?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** order by sum() on columns of table "user" */
export interface user_sum_order_by {age?: (order_by | null)}
/** aggregate var_pop on columns */
export interface user_var_pop_fieldsRequest{
age?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** order by var_pop() on columns of table "user" */
export interface user_var_pop_order_by {age?: (order_by | null)}
/** aggregate var_samp on columns */
export interface user_var_samp_fieldsRequest{
age?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** order by var_samp() on columns of table "user" */
export interface user_var_samp_order_by {age?: (order_by | null)}
/** aggregate variance on columns */
export interface user_variance_fieldsRequest{
age?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** order by variance() on columns of table "user" */
export interface user_variance_order_by {age?: (order_by | null)}
export type QueryRequest = query_rootRequest
export type MutationRequest = mutation_rootRequest
export type SubscriptionRequest = subscription_rootRequest
const mutation_root_possibleTypes = ['mutation_root']
export const ismutation_root = (obj?: { __typename?: any } | null): obj is mutation_root => {
if (!obj?.__typename) throw new Error('__typename is missing in "ismutation_root"')
return mutation_root_possibleTypes.includes(obj.__typename)
}
const query_root_possibleTypes = ['query_root']
export const isquery_root = (obj?: { __typename?: any } | null): obj is query_root => {
if (!obj?.__typename) throw new Error('__typename is missing in "isquery_root"')
return query_root_possibleTypes.includes(obj.__typename)
}
const subscription_root_possibleTypes = ['subscription_root']
export const issubscription_root = (obj?: { __typename?: any } | null): obj is subscription_root => {
if (!obj?.__typename) throw new Error('__typename is missing in "issubscription_root"')
return subscription_root_possibleTypes.includes(obj.__typename)
}
const user_possibleTypes = ['user']
export const isuser = (obj?: { __typename?: any } | null): obj is user => {
if (!obj?.__typename) throw new Error('__typename is missing in "isuser"')
return user_possibleTypes.includes(obj.__typename)
}
const user_aggregate_possibleTypes = ['user_aggregate']
export const isuser_aggregate = (obj?: { __typename?: any } | null): obj is user_aggregate => {
if (!obj?.__typename) throw new Error('__typename is missing in "isuser_aggregate"')
return user_aggregate_possibleTypes.includes(obj.__typename)
}
const user_aggregate_fields_possibleTypes = ['user_aggregate_fields']
export const isuser_aggregate_fields = (obj?: { __typename?: any } | null): obj is user_aggregate_fields => {
if (!obj?.__typename) throw new Error('__typename is missing in "isuser_aggregate_fields"')
return user_aggregate_fields_possibleTypes.includes(obj.__typename)
}
const user_avg_fields_possibleTypes = ['user_avg_fields']
export const isuser_avg_fields = (obj?: { __typename?: any } | null): obj is user_avg_fields => {
if (!obj?.__typename) throw new Error('__typename is missing in "isuser_avg_fields"')
return user_avg_fields_possibleTypes.includes(obj.__typename)
}
const user_max_fields_possibleTypes = ['user_max_fields']
export const isuser_max_fields = (obj?: { __typename?: any } | null): obj is user_max_fields => {
if (!obj?.__typename) throw new Error('__typename is missing in "isuser_max_fields"')
return user_max_fields_possibleTypes.includes(obj.__typename)
}
const user_min_fields_possibleTypes = ['user_min_fields']
export const isuser_min_fields = (obj?: { __typename?: any } | null): obj is user_min_fields => {
if (!obj?.__typename) throw new Error('__typename is missing in "isuser_min_fields"')
return user_min_fields_possibleTypes.includes(obj.__typename)
}
const user_mutation_response_possibleTypes = ['user_mutation_response']
export const isuser_mutation_response = (obj?: { __typename?: any } | null): obj is user_mutation_response => {
if (!obj?.__typename) throw new Error('__typename is missing in "isuser_mutation_response"')
return user_mutation_response_possibleTypes.includes(obj.__typename)
}
const user_stddev_fields_possibleTypes = ['user_stddev_fields']
export const isuser_stddev_fields = (obj?: { __typename?: any } | null): obj is user_stddev_fields => {
if (!obj?.__typename) throw new Error('__typename is missing in "isuser_stddev_fields"')
return user_stddev_fields_possibleTypes.includes(obj.__typename)
}
const user_stddev_pop_fields_possibleTypes = ['user_stddev_pop_fields']
export const isuser_stddev_pop_fields = (obj?: { __typename?: any } | null): obj is user_stddev_pop_fields => {
if (!obj?.__typename) throw new Error('__typename is missing in "isuser_stddev_pop_fields"')
return user_stddev_pop_fields_possibleTypes.includes(obj.__typename)
}
const user_stddev_samp_fields_possibleTypes = ['user_stddev_samp_fields']
export const isuser_stddev_samp_fields = (obj?: { __typename?: any } | null): obj is user_stddev_samp_fields => {
if (!obj?.__typename) throw new Error('__typename is missing in "isuser_stddev_samp_fields"')
return user_stddev_samp_fields_possibleTypes.includes(obj.__typename)
}
const user_sum_fields_possibleTypes = ['user_sum_fields']
export const isuser_sum_fields = (obj?: { __typename?: any } | null): obj is user_sum_fields => {
if (!obj?.__typename) throw new Error('__typename is missing in "isuser_sum_fields"')
return user_sum_fields_possibleTypes.includes(obj.__typename)
}
const user_var_pop_fields_possibleTypes = ['user_var_pop_fields']
export const isuser_var_pop_fields = (obj?: { __typename?: any } | null): obj is user_var_pop_fields => {
if (!obj?.__typename) throw new Error('__typename is missing in "isuser_var_pop_fields"')
return user_var_pop_fields_possibleTypes.includes(obj.__typename)
}
const user_var_samp_fields_possibleTypes = ['user_var_samp_fields']
export const isuser_var_samp_fields = (obj?: { __typename?: any } | null): obj is user_var_samp_fields => {
if (!obj?.__typename) throw new Error('__typename is missing in "isuser_var_samp_fields"')
return user_var_samp_fields_possibleTypes.includes(obj.__typename)
}
const user_variance_fields_possibleTypes = ['user_variance_fields']
export const isuser_variance_fields = (obj?: { __typename?: any } | null): obj is user_variance_fields => {
if (!obj?.__typename) throw new Error('__typename is missing in "isuser_variance_fields"')
return user_variance_fields_possibleTypes.includes(obj.__typename)
}
/** mutation root */
export interface mutation_rootPromiseChain{
/** delete data from the table: "user" */
delete_user: ((args: {
/** filter the rows which have to be deleted */
where: user_bool_exp}) => user_mutation_responsePromiseChain & {get: <R extends user_mutation_responseRequest>(request: R, defaultValue?: (FieldsSelection<user_mutation_response, R> | undefined)) => Promise<(FieldsSelection<user_mutation_response, R> | undefined)>}),
/** delete single row from the table: "user" */
delete_user_by_pk: ((args: {id: Scalars['String']}) => userPromiseChain & {get: <R extends userRequest>(request: R, defaultValue?: (FieldsSelection<user, R> | undefined)) => Promise<(FieldsSelection<user, R> | undefined)>}),
/** insert data into the table: "user" */
insert_user: ((args: {
/** the rows to be inserted */
objects: user_insert_input[],
/** on conflict condition */
on_conflict?: (user_on_conflict | null)}) => user_mutation_responsePromiseChain & {get: <R extends user_mutation_responseRequest>(request: R, defaultValue?: (FieldsSelection<user_mutation_response, R> | undefined)) => Promise<(FieldsSelection<user_mutation_response, R> | undefined)>}),
/** insert a single row into the table: "user" */
insert_user_one: ((args: {
/** the row to be inserted */
object: user_insert_input,
/** on conflict condition */
on_conflict?: (user_on_conflict | null)}) => userPromiseChain & {get: <R extends userRequest>(request: R, defaultValue?: (FieldsSelection<user, R> | undefined)) => Promise<(FieldsSelection<user, R> | undefined)>}),
/** update data of the table: "user" */
update_user: ((args: {
/** increments the integer columns with given value of the filtered values */
_inc?: (user_inc_input | null),
/** sets the columns of the filtered rows to the given values */
_set?: (user_set_input | null),
/** filter the rows which have to be updated */
where: user_bool_exp}) => user_mutation_responsePromiseChain & {get: <R extends user_mutation_responseRequest>(request: R, defaultValue?: (FieldsSelection<user_mutation_response, R> | undefined)) => Promise<(FieldsSelection<user_mutation_response, R> | undefined)>}),
/** update single row of the table: "user" */
update_user_by_pk: ((args: {
/** increments the integer columns with given value of the filtered values */
_inc?: (user_inc_input | null),
/** sets the columns of the filtered rows to the given values */
_set?: (user_set_input | null),pk_columns: user_pk_columns_input}) => userPromiseChain & {get: <R extends userRequest>(request: R, defaultValue?: (FieldsSelection<user, R> | undefined)) => Promise<(FieldsSelection<user, R> | undefined)>})
}
/** mutation root */
export interface mutation_rootObservableChain{
/** delete data from the table: "user" */
delete_user: ((args: {
/** filter the rows which have to be deleted */
where: user_bool_exp}) => user_mutation_responseObservableChain & {get: <R extends user_mutation_responseRequest>(request: R, defaultValue?: (FieldsSelection<user_mutation_response, R> | undefined)) => Observable<(FieldsSelection<user_mutation_response, R> | undefined)>}),
/** delete single row from the table: "user" */
delete_user_by_pk: ((args: {id: Scalars['String']}) => userObservableChain & {get: <R extends userRequest>(request: R, defaultValue?: (FieldsSelection<user, R> | undefined)) => Observable<(FieldsSelection<user, R> | undefined)>}),
/** insert data into the table: "user" */
insert_user: ((args: {
/** the rows to be inserted */
objects: user_insert_input[],
/** on conflict condition */
on_conflict?: (user_on_conflict | null)}) => user_mutation_responseObservableChain & {get: <R extends user_mutation_responseRequest>(request: R, defaultValue?: (FieldsSelection<user_mutation_response, R> | undefined)) => Observable<(FieldsSelection<user_mutation_response, R> | undefined)>}),
/** insert a single row into the table: "user" */
insert_user_one: ((args: {
/** the row to be inserted */
object: user_insert_input,
/** on conflict condition */
on_conflict?: (user_on_conflict | null)}) => userObservableChain & {get: <R extends userRequest>(request: R, defaultValue?: (FieldsSelection<user, R> | undefined)) => Observable<(FieldsSelection<user, R> | undefined)>}),
/** update data of the table: "user" */
update_user: ((args: {
/** increments the integer columns with given value of the filtered values */
_inc?: (user_inc_input | null),
/** sets the columns of the filtered rows to the given values */
_set?: (user_set_input | null),
/** filter the rows which have to be updated */
where: user_bool_exp}) => user_mutation_responseObservableChain & {get: <R extends user_mutation_responseRequest>(request: R, defaultValue?: (FieldsSelection<user_mutation_response, R> | undefined)) => Observable<(FieldsSelection<user_mutation_response, R> | undefined)>}),
/** update single row of the table: "user" */
update_user_by_pk: ((args: {
/** increments the integer columns with given value of the filtered values */
_inc?: (user_inc_input | null),
/** sets the columns of the filtered rows to the given values */
_set?: (user_set_input | null),pk_columns: user_pk_columns_input}) => userObservableChain & {get: <R extends userRequest>(request: R, defaultValue?: (FieldsSelection<user, R> | undefined)) => Observable<(FieldsSelection<user, R> | undefined)>})
}
/** query root */
export interface query_rootPromiseChain{
/** fetch data from the table: "user" */
user: ((args?: {
/** distinct select on columns */
distinct_on?: (user_select_column[] | null),
/** limit the number of rows returned */
limit?: (Scalars['Int'] | null),
/** skip the first n rows. Use only with order_by */
offset?: (Scalars['Int'] | null),
/** sort the rows by one or more columns */
order_by?: (user_order_by[] | null),
/** filter the rows returned */
where?: (user_bool_exp | null)}) => {get: <R extends userRequest>(request: R, defaultValue?: FieldsSelection<user, R>[]) => Promise<FieldsSelection<user, R>[]>})&({get: <R extends userRequest>(request: R, defaultValue?: FieldsSelection<user, R>[]) => Promise<FieldsSelection<user, R>[]>}),
/** fetch aggregated fields from the table: "user" */
user_aggregate: ((args?: {
/** distinct select on columns */
distinct_on?: (user_select_column[] | null),
/** limit the number of rows returned */
limit?: (Scalars['Int'] | null),
/** skip the first n rows. Use only with order_by */
offset?: (Scalars['Int'] | null),
/** sort the rows by one or more columns */
order_by?: (user_order_by[] | null),
/** filter the rows returned */
where?: (user_bool_exp | null)}) => user_aggregatePromiseChain & {get: <R extends user_aggregateRequest>(request: R, defaultValue?: FieldsSelection<user_aggregate, R>) => Promise<FieldsSelection<user_aggregate, R>>})&(user_aggregatePromiseChain & {get: <R extends user_aggregateRequest>(request: R, defaultValue?: FieldsSelection<user_aggregate, R>) => Promise<FieldsSelection<user_aggregate, R>>}),
/** fetch data from the table: "user" using primary key columns */
user_by_pk: ((args: {id: Scalars['String']}) => userPromiseChain & {get: <R extends userRequest>(request: R, defaultValue?: (FieldsSelection<user, R> | undefined)) => Promise<(FieldsSelection<user, R> | undefined)>})
}
/** query root */
export interface query_rootObservableChain{
/** fetch data from the table: "user" */
user: ((args?: {
/** distinct select on columns */
distinct_on?: (user_select_column[] | null),
/** limit the number of rows returned */
limit?: (Scalars['Int'] | null),
/** skip the first n rows. Use only with order_by */
offset?: (Scalars['Int'] | null),
/** sort the rows by one or more columns */
order_by?: (user_order_by[] | null),
/** filter the rows returned */
where?: (user_bool_exp | null)}) => {get: <R extends userRequest>(request: R, defaultValue?: FieldsSelection<user, R>[]) => Observable<FieldsSelection<user, R>[]>})&({get: <R extends userRequest>(request: R, defaultValue?: FieldsSelection<user, R>[]) => Observable<FieldsSelection<user, R>[]>}),
/** fetch aggregated fields from the table: "user" */
user_aggregate: ((args?: {
/** distinct select on columns */
distinct_on?: (user_select_column[] | null),
/** limit the number of rows returned */
limit?: (Scalars['Int'] | null),
/** skip the first n rows. Use only with order_by */
offset?: (Scalars['Int'] | null),
/** sort the rows by one or more columns */
order_by?: (user_order_by[] | null),
/** filter the rows returned */
where?: (user_bool_exp | null)}) => user_aggregateObservableChain & {get: <R extends user_aggregateRequest>(request: R, defaultValue?: FieldsSelection<user_aggregate, R>) => Observable<FieldsSelection<user_aggregate, R>>})&(user_aggregateObservableChain & {get: <R extends user_aggregateRequest>(request: R, defaultValue?: FieldsSelection<user_aggregate, R>) => Observable<FieldsSelection<user_aggregate, R>>}),
/** fetch data from the table: "user" using primary key columns */
user_by_pk: ((args: {id: Scalars['String']}) => userObservableChain & {get: <R extends userRequest>(request: R, defaultValue?: (FieldsSelection<user, R> | undefined)) => Observable<(FieldsSelection<user, R> | undefined)>})
}
/** subscription root */
export interface subscription_rootPromiseChain{
/** fetch data from the table: "user" */
user: ((args?: {
/** distinct select on columns */
distinct_on?: (user_select_column[] | null),
/** limit the number of rows returned */
limit?: (Scalars['Int'] | null),
/** skip the first n rows. Use only with order_by */
offset?: (Scalars['Int'] | null),
/** sort the rows by one or more columns */
order_by?: (user_order_by[] | null),
/** filter the rows returned */
where?: (user_bool_exp | null)}) => {get: <R extends userRequest>(request: R, defaultValue?: FieldsSelection<user, R>[]) => Promise<FieldsSelection<user, R>[]>})&({get: <R extends userRequest>(request: R, defaultValue?: FieldsSelection<user, R>[]) => Promise<FieldsSelection<user, R>[]>}),
/** fetch aggregated fields from the table: "user" */
user_aggregate: ((args?: {
/** distinct select on columns */
distinct_on?: (user_select_column[] | null),
/** limit the number of rows returned */
limit?: (Scalars['Int'] | null),
/** skip the first n rows. Use only with order_by */
offset?: (Scalars['Int'] | null),
/** sort the rows by one or more columns */
order_by?: (user_order_by[] | null),
/** filter the rows returned */
where?: (user_bool_exp | null)}) => user_aggregatePromiseChain & {get: <R extends user_aggregateRequest>(request: R, defaultValue?: FieldsSelection<user_aggregate, R>) => Promise<FieldsSelection<user_aggregate, R>>})&(user_aggregatePromiseChain & {get: <R extends user_aggregateRequest>(request: R, defaultValue?: FieldsSelection<user_aggregate, R>) => Promise<FieldsSelection<user_aggregate, R>>}),
/** fetch data from the table: "user" using primary key columns */
user_by_pk: ((args: {id: Scalars['String']}) => userPromiseChain & {get: <R extends userRequest>(request: R, defaultValue?: (FieldsSelection<user, R> | undefined)) => Promise<(FieldsSelection<user, R> | undefined)>})
}
/** subscription root */
export interface subscription_rootObservableChain{
/** fetch data from the table: "user" */
user: ((args?: {
/** distinct select on columns */
distinct_on?: (user_select_column[] | null),
/** limit the number of rows returned */
limit?: (Scalars['Int'] | null),
/** skip the first n rows. Use only with order_by */
offset?: (Scalars['Int'] | null),
/** sort the rows by one or more columns */
order_by?: (user_order_by[] | null),
/** filter the rows returned */
where?: (user_bool_exp | null)}) => {get: <R extends userRequest>(request: R, defaultValue?: FieldsSelection<user, R>[]) => Observable<FieldsSelection<user, R>[]>})&({get: <R extends userRequest>(request: R, defaultValue?: FieldsSelection<user, R>[]) => Observable<FieldsSelection<user, R>[]>}),
/** fetch aggregated fields from the table: "user" */
user_aggregate: ((args?: {
/** distinct select on columns */
distinct_on?: (user_select_column[] | null),
/** limit the number of rows returned */
limit?: (Scalars['Int'] | null),
/** skip the first n rows. Use only with order_by */
offset?: (Scalars['Int'] | null),
/** sort the rows by one or more columns */
order_by?: (user_order_by[] | null),
/** filter the rows returned */
where?: (user_bool_exp | null)}) => user_aggregateObservableChain & {get: <R extends user_aggregateRequest>(request: R, defaultValue?: FieldsSelection<user_aggregate, R>) => Observable<FieldsSelection<user_aggregate, R>>})&(user_aggregateObservableChain & {get: <R extends user_aggregateRequest>(request: R, defaultValue?: FieldsSelection<user_aggregate, R>) => Observable<FieldsSelection<user_aggregate, R>>}),
/** fetch data from the table: "user" using primary key columns */
user_by_pk: ((args: {id: Scalars['String']}) => userObservableChain & {get: <R extends userRequest>(request: R, defaultValue?: (FieldsSelection<user, R> | undefined)) => Observable<(FieldsSelection<user, R> | undefined)>})
}
/** columns and relationships of "user" */
export interface userPromiseChain{
age: ({get: (request?: boolean|number, defaultValue?: Scalars['Int']) => Promise<Scalars['Int']>}),
id: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Promise<Scalars['String']>}),
name: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Promise<Scalars['String']>})
}
/** columns and relationships of "user" */
export interface userObservableChain{
age: ({get: (request?: boolean|number, defaultValue?: Scalars['Int']) => Observable<Scalars['Int']>}),
id: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Observable<Scalars['String']>}),
name: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Observable<Scalars['String']>})
}
/** aggregated selection of "user" */
export interface user_aggregatePromiseChain{
aggregate: (user_aggregate_fieldsPromiseChain & {get: <R extends user_aggregate_fieldsRequest>(request: R, defaultValue?: (FieldsSelection<user_aggregate_fields, R> | undefined)) => Promise<(FieldsSelection<user_aggregate_fields, R> | undefined)>}),
nodes: ({get: <R extends userRequest>(request: R, defaultValue?: FieldsSelection<user, R>[]) => Promise<FieldsSelection<user, R>[]>})
}
/** aggregated selection of "user" */
export interface user_aggregateObservableChain{
aggregate: (user_aggregate_fieldsObservableChain & {get: <R extends user_aggregate_fieldsRequest>(request: R, defaultValue?: (FieldsSelection<user_aggregate_fields, R> | undefined)) => Observable<(FieldsSelection<user_aggregate_fields, R> | undefined)>}),
nodes: ({get: <R extends userRequest>(request: R, defaultValue?: FieldsSelection<user, R>[]) => Observable<FieldsSelection<user, R>[]>})
}
/** aggregate fields of "user" */
export interface user_aggregate_fieldsPromiseChain{
avg: (user_avg_fieldsPromiseChain & {get: <R extends user_avg_fieldsRequest>(request: R, defaultValue?: (FieldsSelection<user_avg_fields, R> | undefined)) => Promise<(FieldsSelection<user_avg_fields, R> | undefined)>}),
count: ((args?: {columns?: (user_select_column[] | null),distinct?: (Scalars['Boolean'] | null)}) => {get: (request?: boolean|number, defaultValue?: (Scalars['Int'] | undefined)) => Promise<(Scalars['Int'] | undefined)>})&({get: (request?: boolean|number, defaultValue?: (Scalars['Int'] | undefined)) => Promise<(Scalars['Int'] | undefined)>}),
max: (user_max_fieldsPromiseChain & {get: <R extends user_max_fieldsRequest>(request: R, defaultValue?: (FieldsSelection<user_max_fields, R> | undefined)) => Promise<(FieldsSelection<user_max_fields, R> | undefined)>}),
min: (user_min_fieldsPromiseChain & {get: <R extends user_min_fieldsRequest>(request: R, defaultValue?: (FieldsSelection<user_min_fields, R> | undefined)) => Promise<(FieldsSelection<user_min_fields, R> | undefined)>}),
stddev: (user_stddev_fieldsPromiseChain & {get: <R extends user_stddev_fieldsRequest>(request: R, defaultValue?: (FieldsSelection<user_stddev_fields, R> | undefined)) => Promise<(FieldsSelection<user_stddev_fields, R> | undefined)>}),
stddev_pop: (user_stddev_pop_fieldsPromiseChain & {get: <R extends user_stddev_pop_fieldsRequest>(request: R, defaultValue?: (FieldsSelection<user_stddev_pop_fields, R> | undefined)) => Promise<(FieldsSelection<user_stddev_pop_fields, R> | undefined)>}),
stddev_samp: (user_stddev_samp_fieldsPromiseChain & {get: <R extends user_stddev_samp_fieldsRequest>(request: R, defaultValue?: (FieldsSelection<user_stddev_samp_fields, R> | undefined)) => Promise<(FieldsSelection<user_stddev_samp_fields, R> | undefined)>}),
sum: (user_sum_fieldsPromiseChain & {get: <R extends user_sum_fieldsRequest>(request: R, defaultValue?: (FieldsSelection<user_sum_fields, R> | undefined)) => Promise<(FieldsSelection<user_sum_fields, R> | undefined)>}),
var_pop: (user_var_pop_fieldsPromiseChain & {get: <R extends user_var_pop_fieldsRequest>(request: R, defaultValue?: (FieldsSelection<user_var_pop_fields, R> | undefined)) => Promise<(FieldsSelection<user_var_pop_fields, R> | undefined)>}),
var_samp: (user_var_samp_fieldsPromiseChain & {get: <R extends user_var_samp_fieldsRequest>(request: R, defaultValue?: (FieldsSelection<user_var_samp_fields, R> | undefined)) => Promise<(FieldsSelection<user_var_samp_fields, R> | undefined)>}),
variance: (user_variance_fieldsPromiseChain & {get: <R extends user_variance_fieldsRequest>(request: R, defaultValue?: (FieldsSelection<user_variance_fields, R> | undefined)) => Promise<(FieldsSelection<user_variance_fields, R> | undefined)>})
}
/** aggregate fields of "user" */
export interface user_aggregate_fieldsObservableChain{
avg: (user_avg_fieldsObservableChain & {get: <R extends user_avg_fieldsRequest>(request: R, defaultValue?: (FieldsSelection<user_avg_fields, R> | undefined)) => Observable<(FieldsSelection<user_avg_fields, R> | undefined)>}),
count: ((args?: {columns?: (user_select_column[] | null),distinct?: (Scalars['Boolean'] | null)}) => {get: (request?: boolean|number, defaultValue?: (Scalars['Int'] | undefined)) => Observable<(Scalars['Int'] | undefined)>})&({get: (request?: boolean|number, defaultValue?: (Scalars['Int'] | undefined)) => Observable<(Scalars['Int'] | undefined)>}),
max: (user_max_fieldsObservableChain & {get: <R extends user_max_fieldsRequest>(request: R, defaultValue?: (FieldsSelection<user_max_fields, R> | undefined)) => Observable<(FieldsSelection<user_max_fields, R> | undefined)>}),
min: (user_min_fieldsObservableChain & {get: <R extends user_min_fieldsRequest>(request: R, defaultValue?: (FieldsSelection<user_min_fields, R> | undefined)) => Observable<(FieldsSelection<user_min_fields, R> | undefined)>}),
stddev: (user_stddev_fieldsObservableChain & {get: <R extends user_stddev_fieldsRequest>(request: R, defaultValue?: (FieldsSelection<user_stddev_fields, R> | undefined)) => Observable<(FieldsSelection<user_stddev_fields, R> | undefined)>}),
stddev_pop: (user_stddev_pop_fieldsObservableChain & {get: <R extends user_stddev_pop_fieldsRequest>(request: R, defaultValue?: (FieldsSelection<user_stddev_pop_fields, R> | undefined)) => Observable<(FieldsSelection<user_stddev_pop_fields, R> | undefined)>}),
stddev_samp: (user_stddev_samp_fieldsObservableChain & {get: <R extends user_stddev_samp_fieldsRequest>(request: R, defaultValue?: (FieldsSelection<user_stddev_samp_fields, R> | undefined)) => Observable<(FieldsSelection<user_stddev_samp_fields, R> | undefined)>}),
sum: (user_sum_fieldsObservableChain & {get: <R extends user_sum_fieldsRequest>(request: R, defaultValue?: (FieldsSelection<user_sum_fields, R> | undefined)) => Observable<(FieldsSelection<user_sum_fields, R> | undefined)>}),
var_pop: (user_var_pop_fieldsObservableChain & {get: <R extends user_var_pop_fieldsRequest>(request: R, defaultValue?: (FieldsSelection<user_var_pop_fields, R> | undefined)) => Observable<(FieldsSelection<user_var_pop_fields, R> | undefined)>}),
var_samp: (user_var_samp_fieldsObservableChain & {get: <R extends user_var_samp_fieldsRequest>(request: R, defaultValue?: (FieldsSelection<user_var_samp_fields, R> | undefined)) => Observable<(FieldsSelection<user_var_samp_fields, R> | undefined)>}),
variance: (user_variance_fieldsObservableChain & {get: <R extends user_variance_fieldsRequest>(request: R, defaultValue?: (FieldsSelection<user_variance_fields, R> | undefined)) => Observable<(FieldsSelection<user_variance_fields, R> | undefined)>})
}
/** aggregate avg on columns */
export interface user_avg_fieldsPromiseChain{
age: ({get: (request?: boolean|number, defaultValue?: (Scalars['Float'] | undefined)) => Promise<(Scalars['Float'] | undefined)>})
}
/** aggregate avg on columns */
export interface user_avg_fieldsObservableChain{
age: ({get: (request?: boolean|number, defaultValue?: (Scalars['Float'] | undefined)) => Observable<(Scalars['Float'] | undefined)>})
}
/** aggregate max on columns */
export interface user_max_fieldsPromiseChain{
age: ({get: (request?: boolean|number, defaultValue?: (Scalars['Int'] | undefined)) => Promise<(Scalars['Int'] | undefined)>}),
id: ({get: (request?: boolean|number, defaultValue?: (Scalars['String'] | undefined)) => Promise<(Scalars['String'] | undefined)>}),
name: ({get: (request?: boolean|number, defaultValue?: (Scalars['String'] | undefined)) => Promise<(Scalars['String'] | undefined)>})
}
/** aggregate max on columns */
export interface user_max_fieldsObservableChain{
age: ({get: (request?: boolean|number, defaultValue?: (Scalars['Int'] | undefined)) => Observable<(Scalars['Int'] | undefined)>}),
id: ({get: (request?: boolean|number, defaultValue?: (Scalars['String'] | undefined)) => Observable<(Scalars['String'] | undefined)>}),
name: ({get: (request?: boolean|number, defaultValue?: (Scalars['String'] | undefined)) => Observable<(Scalars['String'] | undefined)>})
}
/** aggregate min on columns */
export interface user_min_fieldsPromiseChain{
age: ({get: (request?: boolean|number, defaultValue?: (Scalars['Int'] | undefined)) => Promise<(Scalars['Int'] | undefined)>}),
id: ({get: (request?: boolean|number, defaultValue?: (Scalars['String'] | undefined)) => Promise<(Scalars['String'] | undefined)>}),
name: ({get: (request?: boolean|number, defaultValue?: (Scalars['String'] | undefined)) => Promise<(Scalars['String'] | undefined)>})
}
/** aggregate min on columns */
export interface user_min_fieldsObservableChain{
age: ({get: (request?: boolean|number, defaultValue?: (Scalars['Int'] | undefined)) => Observable<(Scalars['Int'] | undefined)>}),
id: ({get: (request?: boolean|number, defaultValue?: (Scalars['String'] | undefined)) => Observable<(Scalars['String'] | undefined)>}),
name: ({get: (request?: boolean|number, defaultValue?: (Scalars['String'] | undefined)) => Observable<(Scalars['String'] | undefined)>})
}
/** response of any mutation on the table "user" */
export interface user_mutation_responsePromiseChain{
/** number of affected rows by the mutation */
affected_rows: ({get: (request?: boolean|number, defaultValue?: Scalars['Int']) => Promise<Scalars['Int']>}),
/** data of the affected rows by the mutation */
returning: ({get: <R extends userRequest>(request: R, defaultValue?: FieldsSelection<user, R>[]) => Promise<FieldsSelection<user, R>[]>})
}
/** response of any mutation on the table "user" */
export interface user_mutation_responseObservableChain{
/** number of affected rows by the mutation */
affected_rows: ({get: (request?: boolean|number, defaultValue?: Scalars['Int']) => Observable<Scalars['Int']>}),
/** data of the affected rows by the mutation */
returning: ({get: <R extends userRequest>(request: R, defaultValue?: FieldsSelection<user, R>[]) => Observable<FieldsSelection<user, R>[]>})
}
/** aggregate stddev on columns */
export interface user_stddev_fieldsPromiseChain{
age: ({get: (request?: boolean|number, defaultValue?: (Scalars['Float'] | undefined)) => Promise<(Scalars['Float'] | undefined)>})
}
/** aggregate stddev on columns */
export interface user_stddev_fieldsObservableChain{
age: ({get: (request?: boolean|number, defaultValue?: (Scalars['Float'] | undefined)) => Observable<(Scalars['Float'] | undefined)>})
}
/** aggregate stddev_pop on columns */
export interface user_stddev_pop_fieldsPromiseChain{
age: ({get: (request?: boolean|number, defaultValue?: (Scalars['Float'] | undefined)) => Promise<(Scalars['Float'] | undefined)>})
}
/** aggregate stddev_pop on columns */
export interface user_stddev_pop_fieldsObservableChain{
age: ({get: (request?: boolean|number, defaultValue?: (Scalars['Float'] | undefined)) => Observable<(Scalars['Float'] | undefined)>})
}
/** aggregate stddev_samp on columns */
export interface user_stddev_samp_fieldsPromiseChain{
age: ({get: (request?: boolean|number, defaultValue?: (Scalars['Float'] | undefined)) => Promise<(Scalars['Float'] | undefined)>})
}
/** aggregate stddev_samp on columns */
export interface user_stddev_samp_fieldsObservableChain{
age: ({get: (request?: boolean|number, defaultValue?: (Scalars['Float'] | undefined)) => Observable<(Scalars['Float'] | undefined)>})
}
/** aggregate sum on columns */
export interface user_sum_fieldsPromiseChain{
age: ({get: (request?: boolean|number, defaultValue?: (Scalars['Int'] | undefined)) => Promise<(Scalars['Int'] | undefined)>})
}
/** aggregate sum on columns */
export interface user_sum_fieldsObservableChain{
age: ({get: (request?: boolean|number, defaultValue?: (Scalars['Int'] | undefined)) => Observable<(Scalars['Int'] | undefined)>})
}
/** aggregate var_pop on columns */
export interface user_var_pop_fieldsPromiseChain{
age: ({get: (request?: boolean|number, defaultValue?: (Scalars['Float'] | undefined)) => Promise<(Scalars['Float'] | undefined)>})
}
/** aggregate var_pop on columns */
export interface user_var_pop_fieldsObservableChain{
age: ({get: (request?: boolean|number, defaultValue?: (Scalars['Float'] | undefined)) => Observable<(Scalars['Float'] | undefined)>})
}
/** aggregate var_samp on columns */
export interface user_var_samp_fieldsPromiseChain{
age: ({get: (request?: boolean|number, defaultValue?: (Scalars['Float'] | undefined)) => Promise<(Scalars['Float'] | undefined)>})
}
/** aggregate var_samp on columns */
export interface user_var_samp_fieldsObservableChain{
age: ({get: (request?: boolean|number, defaultValue?: (Scalars['Float'] | undefined)) => Observable<(Scalars['Float'] | undefined)>})
}
/** aggregate variance on columns */
export interface user_variance_fieldsPromiseChain{
age: ({get: (request?: boolean|number, defaultValue?: (Scalars['Float'] | undefined)) => Promise<(Scalars['Float'] | undefined)>})
}
/** aggregate variance on columns */
export interface user_variance_fieldsObservableChain{
age: ({get: (request?: boolean|number, defaultValue?: (Scalars['Float'] | undefined)) => Observable<(Scalars['Float'] | undefined)>})
} | the_stack |
import fetch from "cross-fetch";
import * as fs from "fs";
import { toQueryString } from "../../utils";
import { SdkClient } from "../common/sdk-client";
import { DataLakeModels } from "./data-lake.models";
const HttpsProxyAgent = require("https-proxy-agent");
export class DataLakeClient extends SdkClient {
private _baseUrl: string = "/api/datalake/v3";
/**
* * Object Metadata Catalog Operations
*
* Get Metadata for the object. If tenant is operating for a subtenant object,
* he should specify subtenant in request query parameter.
* If path contains special characters which require URL encoding, it should be done as appropriate.
*
* @param {string} path path of an object denoting folders and object name. e.g. basefolder/subfolder/objectname.objectext
* @param {{ subtenantid?: string }} [optional] Only to be used by tenants, to address a subtenants object metadata. If not provided by a tenant, its own object metadata is addressed. Subtenants are not allowed to use this parameter and can only address their own object metadata. e.g. subtenantId 204a896c-a23a-11e9-a2a3-2a2ae2dbcce4
* @returns {Promise<DataLakeModels.ObjectMetaDataResponse>}
*
* @memberOf DataLakeClient
*/
public async GetObjectMetaData(
path: string,
optional?: { subtenantid?: string }
): Promise<DataLakeModels.ObjectMetaDataResponse> {
return (await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/objectMetadata/${path}?${toQueryString(optional)}`,
})) as DataLakeModels.ObjectMetaDataResponse;
}
/**
* * Object Metadata Catalog Operations
*
* Get a list of metadata information with a filter
*
* @param {string} path
* @param {{ filter: string; subtenantid?: string; size?: number; page?: number }} params
* @returns {Promise<DataLakeModels.SearchResponse>}
*
* @memberOf DataLakeClient
*/
public async GetObjectMetaDatas(
path: string,
params: { filter: string; subtenantid?: string; size?: number; page?: number }
): Promise<DataLakeModels.SearchResponse> {
return (await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/objectMetadata/${path}?${toQueryString(params)}`,
})) as DataLakeModels.SearchResponse;
}
/**
*
* * Object Metadata Catalog Operations
*
* Create/Update metadata. If tenant is operating for a subtenant object,
* he should specify subtenant in request query parameter.
* If path contains special characters which require URL encoding, it should be done as appropriate.
* Maximum 8 tags are allowed, where each tag can be maximum 128 characters.
*
* @param {string} path path of an object denoting folders and object name. e.g. basefolder/subfolder/objectname.objectext
* @param {DataLakeModels.Metadata} Metadata
* @param {{ subtenantid?: string }} [optional] Only to be used by tenants, to address a subtenants object metadata. If not provided by a tenant, its own object metadata is addressed. Subtenants are not allowed to use this parameter and can only address their own object metadata. e.g. subtenantId 204a896c-a23a-11e9-a2a3-2a2ae2dbcce4
* @returns
*
* @memberOf DataLakeClient
*/
public async PutObjectMetaData(
path: string,
metadata: DataLakeModels.Metadata,
optional?: { subtenantid?: string }
) {
return await this.HttpAction({
verb: "PUT",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
body: metadata,
baseUrl: `${this._baseUrl}/objectMetadata/${path}?${toQueryString(optional)}`,
});
}
/**
*
* * Object Access Operations
*
* * Generate signed URLs to upload an object.
*
* @param {DataLakeModels.GenerateUrlPayload} generateUrlPayload
* upload payload with path details array and optional subtenant id
* @returns
*
* @memberOf DataLakeClient
*/
public async GenerateUploadObjectUrls(
generateUrlPayload: DataLakeModels.GenerateUrlPayload
): Promise<DataLakeModels.SignedUrlResponse> {
return (await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/generateUploadObjectUrls`,
body: generateUrlPayload,
})) as DataLakeModels.SignedUrlResponse;
}
/**
*
* * Object Access Operations
*
* * Generate signed URLs to download an object
*
* @param {DataLakeModels.GenerateUrlPayload} generateUrlPayload
* @returns {Promise<DataLakeModels.SignedUrlResponse>}
*
* @memberOf DataLakeClient
*/
public async GenerateDownloadObjectUrls(
generateUrlPayload: DataLakeModels.GenerateUrlPayload
): Promise<DataLakeModels.SignedUrlResponse> {
return (await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/generateDownloadObjectUrls`,
body: generateUrlPayload,
})) as DataLakeModels.SignedUrlResponse;
}
/**
* * Object Access Operations
* * Upload file to data lake via pre-signed URL
*
* @param {(string | Buffer)} file
* @param {string} signedUrl
* @returns {Promise<Headers>}
*
* @memberOf DataLakeClient
*/
public async PutFile(file: string | Buffer, signedUrl: string): Promise<Headers> {
const myBuffer = typeof file === "string" ? fs.readFileSync(file) : (file as Buffer);
const proxy = process.env.http_proxy || process.env.HTTP_PROXY;
const proxyHttpAgent: any = proxy ? new HttpsProxyAgent(proxy) : null;
// x-ms-blob is necessary on eu2 and is ignored on eu1
const request: any = { method: "PUT", headers: { "x-ms-blob-type": "BlockBlob" }, agent: proxyHttpAgent };
request.body = myBuffer;
const response = await fetch(signedUrl, request);
return response.headers;
}
/**
* * Object Access Operations
* * Create a cross account
*
* Create a cross account on which access needs to be given for paths.
* If, in request body subtenant is denoted as "**", it is a special cross account.
* In this case, on this cross account, tenant implicitly gets Read Only access to the storage
* account's root level data path for itself and for all its subtenants.
* For this case, the authorization token should be that of the tenant.
*
* @param {DataLakeModels.CrossAccountRequest} crossAccountRequest
* @returns {Promise<DataLakeModels.CrossAccount>}
*
* @memberOf DataLakeClient
*/
public async PostCrossAccount(
crossAccountRequest: DataLakeModels.CrossAccountRequest
): Promise<DataLakeModels.CrossAccount> {
return (await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/crossAccounts`,
body: crossAccountRequest,
})) as DataLakeModels.CrossAccount;
}
/**
* * Object Access Operations
* * Get list of cross accounts on which access was given.
*
* If requester is tenant, all the cross account for the tenant as well as its all subtenants are returned.
* If requester is a subtenant, all the cross accounts for the subtenant are returned.
* If tenant wants to filter results for a particular subtenant, filter query parameter subtenantId can be used. This filter query parameter is applicable only if the requester is tenant.
*
* @param {{
* page?: number;
* size?: number;
* filter?: string;
* }} [params]
* @returns {Promise<DataLakeModels.CrossAccountListResource>}
*
* @memberOf DataLakeClient
*/
public async GetCrossAccounts(params?: {
page?: number;
size?: number;
filter?: string;
}): Promise<DataLakeModels.CrossAccountListResource> {
return (await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/crossAccounts?${toQueryString(params)}`,
})) as DataLakeModels.CrossAccountListResource;
}
/**
*
* * Object Access Operations
* * Get details of selected cross account.
*
* @param {string} id unique identifier of the cross account
* @returns {Promise<DataLakeModels.CrossAccount>}
*
* @memberOf DataLakeClient
*/
public async GetCrossAccount(id: string): Promise<DataLakeModels.CrossAccount> {
return (await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/crossAccounts/${id}`,
})) as DataLakeModels.CrossAccount;
}
/**
* * Object Access Operations
* * Update a cross account on which access needs to be managed.
*
* @param {string} id
* @param {DataLakeModels.CrossAccountUpdateRequest} crossAccountUpdateRequest
* @param {{ ifMatch: number }} params
* @returns {Promise<DataLakeModels.CrossAccount>}
*
* @memberOf DataLakeClient
*/
public async PatchCrossAccount(
id: string,
crossAccountUpdateRequest: DataLakeModels.CrossAccountUpdateRequest,
params: { ifMatch: number }
): Promise<DataLakeModels.CrossAccount> {
return (await this.HttpAction({
verb: "PATCH",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/crossAccounts/${id}`,
additionalHeaders: { "If-Match": params.ifMatch },
body: crossAccountUpdateRequest,
})) as DataLakeModels.CrossAccount;
}
/**
* * Object Access Operations
* * Delete cross account and corresponding accesses.
*
* @param {string} id
* @param {{ ifMatch: number }} params
* @returns
*
* @memberOf DataLakeClient
*/
public async DeleteCrossAccount(id: string, params: { ifMatch: number }) {
return await this.HttpAction({
verb: "DELETE",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/crossAccounts/${id}`,
additionalHeaders: { "If-Match": params.ifMatch },
noResponse: true,
});
}
/**
* * Object Access Operations
* * Create a cross account access.
* If the cross account is created for tenant and all subtenants (**),
* then this operation is implicitly handled and not allowed through API.
* Maximum 5 cross account accesses can be created with ENABLED status.
* Maximum 10 cross accounts can be created with DISABLED status.
* @param {string} id
* @param {DataLakeModels.CrossAccountAccessRequest} crossAccountAccessRequest
* @returns {Promise<DataLakeModels.CrossAccountAccess>}
*
* @memberOf DataLakeClient
*/
public async PostCrossAccountAccess(
id: string,
crossAccountAccessRequest: DataLakeModels.CrossAccountAccessRequest
): Promise<DataLakeModels.CrossAccountAccess> {
return (await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/crossAccounts${id}/accesses`,
body: crossAccountAccessRequest,
})) as DataLakeModels.CrossAccountAccess;
}
/**
* * Object Access Operations
* *Get list of cross account accesses.
*
* @param {string} id
* @param {{
* page?: number;
* size?: number;
* }} [params]
* @returns {Promise<DataLakeModels.CrossAccountAccessListResource>}
*
* @memberOf DataLakeClient
*/
public async GetCrossAccountAccesses(
id: string,
params?: {
page?: number;
size?: number;
}
): Promise<DataLakeModels.CrossAccountAccessListResource> {
return (await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/crossAccounts/${id}/accesses?${toQueryString(params)}`,
})) as DataLakeModels.CrossAccountAccessListResource;
}
/**
* * Object Access Operations
* * Get a selected access for a selected cross account.
*
* @param {string} id
* @param {string} accessId
* @returns {Promise<DataLakeModels.CrossAccountAccess>}
*
* @memberOf DataLakeClient
*/
public async GetCrossAccountAccess(id: string, accessId: string): Promise<DataLakeModels.CrossAccountAccess> {
return (await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/crossAccounts/${id}/accesses/${accessId}`,
})) as DataLakeModels.CrossAccountAccess;
}
/**
* * Object Access Operations
* * Update a cross account access.
*
* This operation is not allowed when the cross account is created
* for special case of tenant and all subtenants (**).
* Maximum 5 cross account accesses can be present with ENABLED status.
* Maximum 10 cross accounts can be present with DISABLED status.
*
* @param {string} id
* @param {string} accessId
* @param {DataLakeModels.CrossAccountAccessRequest} crossAcccountAccessRequest
* @param {{ ifMatch: number }} params
* @returns {Promise<DataLakeModels.CrossAccountAccess>}
*
* @memberOf DataLakeClient
*/
public async PatchCrossAccountAccess(
id: string,
accessId: string,
crossAcccountAccessRequest: DataLakeModels.CrossAccountAccessRequest,
params: { ifMatch: number }
): Promise<DataLakeModels.CrossAccountAccess> {
return (await this.HttpAction({
verb: "PATCH",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/crossAccounts/${id}/accesses/${accessId}`,
body: crossAcccountAccessRequest,
additionalHeaders: { "If-Match": params.ifMatch },
})) as DataLakeModels.CrossAccountAccess;
}
/**
* * Delete a cross account access.
*
* If the cross account is created for tenant and all subtenants (**),
* then this operation is implicitly handled by deletion of cross account and not allowed through API
*
*
* @param {string} id
* @param {string} accessId
* @param {{ ifMatch: number }} params
* @returns
*
* @memberOf DataLakeClient
*/
public async DeleteCrossAccountAccess(id: string, accessId: string, params: { ifMatch: number }) {
return await this.HttpAction({
verb: "DELETE",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/crossAccounts/${id}/accesses/${accessId}`,
additionalHeaders: { "If-Match": params.ifMatch },
noResponse: true,
});
}
/**
* * Object Event Subscription Operations
* * Create Object Event Subscription
*
* Allows users to subscribe for event notifications generated
* when the objects of a tenant or subtenant are created,
* updated, or deleted. Multiple subscriptions for the same path
* can be created when each has a different destination. Similarly, multiple subscriptions
* for the same destination can be created when each has a different path.
* Maximum 15 subscriptions can be created for a tenant or for a subtenant.
* Path in request payload should be upto folders and not upto object e.g. "myfolder/mysubfolder"
* Notification Content
* Based on the configured subscriptions, event notification
* messages are published to the destination.
* The event notification content is formatted in JSON according to this example.
* If object operation happened in subtenant folder, both tenantId and subtenantId
* will be part of the message. If object operation happened in tenant folder, only
* tenantId will be part of the message.:
*
* @param {DataLakeModels.Subscription} subscription
* @returns {Promise<DataLakeModels.Subscription>}
*
* @memberOf DataLakeClient
*/
public async PostObjectEventSubscriptions(
subscription: DataLakeModels.Subscription
): Promise<DataLakeModels.Subscription> {
return (await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/objectEventSubscriptions`,
body: subscription,
})) as DataLakeModels.Subscription;
}
/**
* * Object Event Subscription Operations
* * List object event subscriptions for the tenant or subtenant.
*
* If requester is tenant, all the subscriptions for the tenant as well as its all
* subtenants are returned. If requester is a subtenant, all the subscriptions for
* the subtenant are returned. If tenant wants to filter results for a particular subtenant,
* filter query parameter subtenantId can be used. This filter query parameter is applicable
* only if the requester is tenant.
*
* @param {{
* page?: number;
* size?: number;
* filter?: string;
* }} [params]
* @param params.filter
* JSON-based filter expression. Supported values: 'subtenantId'. Supported operations: 'eq'.
* Decoded example value:
* @example { "subtenantId": "204a896c-a23a-11e9-a2a3-2a2ae2dbcce4" }
*
* @returns {Promise<DataLakeModels.SubscriptionListResource>}
*
* @memberOf DataLakeClient
*/
public async GetObjectEventSubscriptions(params?: {
page?: number;
size?: number;
filter?: string;
}): Promise<DataLakeModels.SubscriptionListResource> {
return (await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/objectEventSubscriptions?${toQueryString(params)}`,
})) as DataLakeModels.SubscriptionListResource;
}
/**
* * Object Event Subscription Operations
* * Read event subscription by id
*
* Read object event subscription for the tenant
*
* @param {string} id
* @returns {Promise<DataLakeModels.SubscriptionResponse>}
*
* @memberOf DataLakeClient
*/
public async GetObjectEventSubscription(id: string): Promise<DataLakeModels.SubscriptionResponse> {
return (await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/objectEventSubscriptions/${id}`,
})) as DataLakeModels.SubscriptionResponse;
}
/**
* * Object Event Subscription Operations
* * Update object event subscription by id
*
* @param {string} id
* @param {DataLakeModels.SubscriptionUpdate} subscriptionUpdate
* @param {{ ifMatch: number }} params
* @returns {Promise<DataLakeModels.SubscriptionResponse>}
*
* @memberOf DataLakeClient
*/
public async PatchObjectEventSubscription(
id: string,
subscriptionUpdate: DataLakeModels.SubscriptionUpdate,
params: { ifMatch: number }
): Promise<DataLakeModels.SubscriptionResponse> {
return (await this.HttpAction({
verb: "PATCH",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/objectEventSubscriptions/${id}`,
additionalHeaders: { "If-Match": params.ifMatch },
body: subscriptionUpdate,
})) as DataLakeModels.SubscriptionResponse;
}
/**
* * Object Event Subscription Operations
* * Delete object event subscription by id
*
* @param {string} id
* @param {{ ifMatch: number }} params
* @returns
*
* @memberOf DataLakeClient
*/
public async DeleteObjectEventSubscription(id: string, params: { ifMatch: number }) {
return await this.HttpAction({
verb: "DELETE",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/objectEventSubscriptions/${id}`,
additionalHeaders: { "If-Match": params.ifMatch },
noResponse: true,
});
}
/**
* * Time Series Bulk Import Operations
* * Creates a bulk import job of time series data into data
*
* Creates an asynchronous job to bulk import time series data into data lake.
* The import takes into account time series data from the provided aspects associated to the provided assets,
* in the given time range
*
* @param {DataLakeModels.ImportJobRequest} importJob
* @returns {Promise<DataLakeModels.ImportJobResponse>}
*
* @memberOf DataLakeClient
*/
public async PostTimeSeriesImportJob(
importJob: DataLakeModels.ImportJobRequest
): Promise<DataLakeModels.ImportJobResponse> {
return (await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/timeSeriesImportJobs`,
body: importJob,
})) as DataLakeModels.ImportJobResponse;
}
/**
*
* * Time Series Bulk Import Operations
* * Query all time series bulk import jobs
*
* Query all time series bulk import jobs currently existing,
* which are owned by the client's tenant or subtenant.
* If requester is tenant, all the import jobs for the tenant as well as
* its all subtenants are returned. If requester is a subtenant,
* all the iport jobs for the subtenant are returned. If tenant wants to filter results
* for a particular subtenant, filter query parameter subtenantId can be used.
* This filter query parameter is applicable only if the requester is tenant.
*
* @param {{
* page?: number;
* size?: number;
* filter?: string;
* }} [params]
* @param params.filter
* JSON-based filter expression. Supported values: 'subtenantId'. Supported operations: 'eq'.
* Decoded example value:
* @example { "subtenantId": "204a896c-a23a-11e9-a2a3-2a2ae2dbcce4" }
* @returns {Promise<DataLakeModels.ImportJobListResource>}
*
* @memberOf DataLakeClient
*/
public async GetTimeSeriesImportJobs(params?: {
page?: number;
size?: number;
filter?: string;
}): Promise<DataLakeModels.ImportJobListResource> {
return (await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/timeSeriesImportJobs?${toQueryString(params)}`,
})) as DataLakeModels.ImportJobListResource;
}
/**
* * Time Series Bulk Import Operations
* * Retrieve status of time series bulk import job.
*
* @param {string} id
* @returns {Promise<DataLakeModels.ImportJobResponse>}
*
* @memberOf DataLakeClient
*/
public async GetTimeSeriesImportJob(id: string): Promise<DataLakeModels.ImportJobResponse> {
return (await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/timeSeriesImportJobs/${id}`,
})) as DataLakeModels.ImportJobResponse;
}
/**
* * Time Series Bulk Import Operations
* * Delete completed time series bulk import job.
*
* @param {string} id
* @returns
*
* @memberOf DataLakeClient
*/
public async DeleteTimeSeriesImportJob(id: string) {
return await this.HttpAction({
verb: "DELETE",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/timeSeriesImportJobs/${id}`,
noResponse: true,
});
}
/**
* * Time Series Bulk Import Operations
* * Retreive details of a time series bulk import job.
*
* Details are only available once a job is not any longer in status PENDING.
*
* @param {string} id
* @returns {Promise<DataLakeModels.ImportJobDetails>}
*
* @memberOf DataLakeClient
*/
public async GetTimeSeriesImportJobDetails(id: string): Promise<DataLakeModels.ImportJobDetails> {
return (await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/timeSeriesImportJobs/${id}/details`,
})) as DataLakeModels.ImportJobDetails;
}
/**
*
* * Object Operations with Access Token
*
* Allows users to request temporary, limited-privilege AWS credentials to get read-only or write-only access on the URI returned in the response.
* Read permission will always be on the root level.
* Path field is optional for READ permission - If value for path is not provided then it will be considered on root level (/).
* Ensure to enable write access on the path before requesting token with write permission.
* Write access can be enabled using POST /accessTokenPermissions endpoint.
* An access token requested for a given path also automatically gives access to all subpaths of the path. For example, if an access token is requested for path /a and there are subpaths /a/b and /a/b/c, the token allows to access those too.
* An access token with write permissions can only be requested for the paths defined by resource accessTokenPermissions. An acecss token with read permissions can only be requested for the root path /.
*
* @param {DataLakeModels.GenerateSTSPayload} stsPayload
* @returns {Promise<DataLakeModels.AccessTokens>}
*
* @memberOf DataLakeClient
*/
public async GenerateAccessToken(
stsPayload: DataLakeModels.GenerateSTSPayload
): Promise<DataLakeModels.AccessTokens> {
return (await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/generateAccessToken`,
body: stsPayload,
})) as DataLakeModels.AccessTokens;
}
/**
* * Object Operations with Access Token
* * List all folders having write permission.
* This API can be accessed by tenant admin, to list all write permission folders including of subtenants.
* Subtenant can access this API, to get list write permission folders owned by subtenant.
*
* * Size parameter value should not be more than 1000.
* @param {{
* page?: number;
* size?: number;
* }} [optional]
* @returns {Promise<DataLakeModels.AccessTokenPermissionResources>}
*
* @memberOf DataLakeClient
*/
public async GetAccessTokenPermissions(optional?: {
page?: number;
size?: number;
}): Promise<DataLakeModels.AccessTokenPermissionResources> {
const qs = toQueryString(optional);
return (await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/accessTokenPermissions?${qs}`,
})) as DataLakeModels.AccessTokenPermissionResources;
}
/**
* * Object Operations with Access Token
* * Details of the write folder request for the given id
*
* This API can be accessed by tenant admin, to get details of the request including for subtenants.
* Subtenant can access this API, to get details of the request belongs to their write folder.
* @param {string} id
* @returns {Promise<DataLakeModels.AccessTokenPermissionResource>}
*
* @memberOf DataLakeClient
*/
public async GetAccessTokenPermission(id: string): Promise<DataLakeModels.AccessTokenPermissionResource> {
return (await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/accessTokenPermissions/${id}`,
})) as DataLakeModels.AccessTokenPermissionResource;
}
/**
* * Object Operations with Access Token
* * Delete write permission on folder for the given id
*
* @param {string} id Unique identifier of the write enabled folders
* @returns {Promise<DataLakeModels.AccessTokenPermissionResource>}
*
* @memberOf DataLakeClient
*/
public async DeleteAccessTokenPermission(id: string) {
return await this.HttpAction({
verb: "DELETE",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/accessTokenPermissions/${id}`,
noResponse: true,
});
}
/**
* * Object Operations with Access Token
* * Allows to give write premission on folder/path
*
* @param {DataLakeModels.AccessTokenPermissionRequest} writePathPayload
* @returns {Promise<DataLakeModels.AccessTokenPermissionResource>}
*
* @memberOf DataLakeClient
*/
public async PostAccessTokenPermissions(
writePathPayload: DataLakeModels.AccessTokenPermissionRequest
): Promise<DataLakeModels.AccessTokenPermissionResource> {
return (await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/accessTokenPermissions`,
body: writePathPayload,
})) as DataLakeModels.AccessTokenPermissionResource;
}
} | the_stack |
export namespace UsageTransparencyModels {
/**
*
* @export
* @class RequiredError
* @extends {Error}
*/
export class RequiredError extends Error {
name: "RequiredError" = "RequiredError";
constructor(public field: string, msg?: string) {
super(msg);
}
}
/**
*
* @export
* @interface ApplicationResource
*/
export interface ApplicationResource {
/**
* an application that consumes or manipulates a resource and provides some service. an application is the main actor that generates usages. the name should be same as the registered application name. in case no application is specified, alias name will be considered as the application name.
* @type {string}
* @memberof ApplicationResource
*/
application: string;
/**
* an application may realize multiple business cases, in such a case aliases can be used to distinguish between the business cases realized by same application. alias should be named so that it conveys the underlying business case. in case no alias is provided, application name will be considered as the alias.
* @type {string}
* @memberof ApplicationResource
*/
alias?: string;
/**
* a resource for which the usage is being reported by the application, e.g asset, user, app, action, URL, operation, etc.
* @type {string}
* @memberof ApplicationResource
*/
resource: string;
/**
*
* @type {Array<Usage>}
* @memberof ApplicationResource
*/
usages: Array<Usage>;
}
/**
*
* @export
* @interface ApplicationUsage
*/
export interface ApplicationUsage {
/**
* an application that consumes or manipulates a resource and provides some service. an application is the main actor that generates usages
* @type {string}
* @memberof ApplicationUsage
*/
resourceAlias?: string;
/**
* a resource for which the usage is being reported by the application (resourceAlias), e.g asset, user, app, action, url, operation
* @type {string}
* @memberof ApplicationUsage
*/
resourceName?: string;
/**
*
* @type {Array<ResourceUsage>}
* @memberof ApplicationUsage
*/
UsageData?: Array<ResourceUsage>;
}
/**
*
* @export
* @interface BadRequestErrorSchema
*/
export interface BadRequestErrorSchema {}
/**
*
* @export
* @interface BillingError
*/
export interface BillingError extends UsageError {
/**
* list of billing data ids that failed
* @type {string}
* @memberof BillingError
*/
errorData?: string;
}
/**
* @export
* @namespace BillingError
*/
export namespace BillingError {}
/**
*
* @export
* @interface ErrorMessageParameters
*/
export interface ErrorMessageParameters {
/**
*
* @type {string}
* @memberof ErrorMessageParameters
*/
name?: string;
/**
*
* @type {string}
* @memberof ErrorMessageParameters
*/
value?: string;
}
/**
*
* @export
* @interface ForbiddenErrorSchema
*/
export interface ForbiddenErrorSchema {}
/**
*
* @export
* @interface HTTPErrors
*/
export interface HTTPErrors {
/**
*
* @type {Array<Error>}
* @memberof HTTPErrors
*/
errors?: Array<Error>;
}
/**
*
* @export
* @interface HTTPErrorsWithStatus
*/
export interface HTTPErrorsWithStatus {
/**
* UTS specific error code
* @type {string}
* @memberof HTTPErrorsWithStatus
*/
code?: string;
/**
* error message in english
* @type {string}
* @memberof HTTPErrorsWithStatus
*/
message?: string;
/**
* log correlation-id
* @type {string}
* @memberof HTTPErrorsWithStatus
*/
logref?: string;
/**
*
* @type {number}
* @memberof HTTPErrorsWithStatus
*/
status?: number;
}
/**
*
* @export
* @interface ModelError
*/
export interface ModelError {
/**
* mdsp.<provider>.<service/app>.<errorid>
* @type {string}
* @memberof ModelError
*/
code?: string;
/**
* error message in english
* @type {string}
* @memberof ModelError
*/
message?: string;
/**
*
* @type {Array<ErrorMessageParameters>}
* @memberof ModelError
*/
messageParameters?: Array<ErrorMessageParameters>;
/**
* log correlation-id
* @type {string}
* @memberof ModelError
*/
logref?: string;
}
/**
*
* @export
* @interface OtherUsageError
*/
export interface OtherUsageError extends UsageError {
/**
* description of error
* @type {string}
* @memberof OtherUsageError
*/
errorData?: string;
}
/**
* @export
* @namespace OtherUsageError
*/
export namespace OtherUsageError {}
/**
*
* @export
* @interface Page
*/
export interface Page {
/**
*
* @type {number}
* @memberof Page
*/
number?: number;
/**
*
* @type {number}
* @memberof Page
*/
size?: number;
/**
*
* @type {number}
* @memberof Page
*/
totalElements?: number;
/**
*
* @type {number}
* @memberof Page
*/
totalPages?: number;
}
/**
*
* @export
* @interface ResourceUsage
*/
export interface ResourceUsage {
/**
*
* @type {number}
* @memberof ResourceUsage
*/
usage?: number;
/**
* represents asnaction performed by the application, e.g. sending sms, onboarding of asset, etc.
* @type {string}
* @memberof ResourceUsage
*/
usageUnit?: string;
/**
*
* @type {string}
* @memberof ResourceUsage
*/
usageDate?: string;
}
/**
*
* @export
* @interface UnauthorisedErrorSchema
*/
export interface UnauthorisedErrorSchema {}
/**
*
* @export
* @interface Usage
*/
export interface Usage {
/**
* represents the amount of units consumed.
* @type {number}
* @memberof Usage
*/
value: number;
/**
* represents a trackable or billable action performed by the application, e.g. sending SMS, onboarding of asset, etc.
* @type {string}
* @memberof Usage
*/
unit: string;
/**
* time at which the usage occurred, in UTC clock time.
* @type {string}
* @memberof Usage
*/
datetime: string;
}
/**
*
* @export
* @interface UsageError
*/
export interface UsageError extends Error {
/**
*
* @type {string}
* @memberof UsageError
*/
errorType?: UsageError.ErrorTypeEnum;
/**
* reference to more information if available
* @type {string}
* @memberof UsageError
*/
info?: string;
}
/**
* @export
* @namespace UsageError
*/
export namespace UsageError {
/**
* @export
* @enum {string}
*/
export enum ErrorTypeEnum {
ValidationError = <any>"ValidationError",
BillingError = <any>"BillingError",
OtherError = <any>"OtherError",
}
}
/**
*
* @export
* @interface UsageErrors
*/
export interface UsageErrors {
/**
*
* @type {Array<UsageError>}
* @memberof UsageErrors
*/
errors?: Array<UsageError>;
/**
*
* @type {Page}
* @memberof UsageErrors
*/
page?: Page;
}
/**
*
* @export
* @interface UsageUser
*/
export interface UsageUser {}
/**
*
* @export
* @interface UsagesJob
*/
export interface UsagesJob {
/**
*
* @type {string}
* @memberof UsagesJob
*/
id?: string;
/**
*
* @type {string}
* @memberof UsagesJob
*/
time?: string;
/**
* The status is based on the status of the usages that satisfy the query.
* @type {string}
* @memberof UsagesJob
*/
status?: UsagesJob.StatusEnum;
/**
* Number of usages that satisfy the query and were added by addUsagesJob identified by the id.
* @type {number}
* @memberof UsagesJob
*/
usagesCount?: number;
}
/**
* @export
* @namespace UsagesJob
*/
export namespace UsagesJob {
/**
* @export
* @enum {string}
*/
export enum StatusEnum {
ACCEPTED = <any>"ACCEPTED",
INPROGRESS = <any>"INPROGRESS",
ERRORS = <any>"ERRORS",
COMPLETED = <any>"COMPLETED",
}
}
/**
*
* @export
* @interface UsagesJobQueryResult
*/
export interface UsagesJobQueryResult {
/**
*
* @type {Array<UsagesJob>}
* @memberof UsagesJobQueryResult
*/
jobs?: Array<UsagesJob>;
/**
*
* @type {Page}
* @memberof UsagesJobQueryResult
*/
page?: Page;
}
/**
*
* @export
* @interface UsagesJobSummary
*/
export interface UsagesJobSummary extends UsagesJob {
/**
*
* @type {Array<UsagesSummary>}
* @memberof UsagesJobSummary
*/
usagesSummary?: Array<UsagesSummary>;
/**
*
* @type {Page}
* @memberof UsagesJobSummary
*/
page?: Page;
}
/**
* @export
* @namespace UsagesJobSummary
*/
export namespace UsagesJobSummary {}
/**
*
* @export
* @interface UsagesSummary
*/
export interface UsagesSummary {
/**
*
* @type {string}
* @memberof UsagesSummary
*/
application?: string;
/**
*
* @type {string}
* @memberof UsagesSummary
*/
unit?: string;
/**
* number of usages that satisfy the query within the application, unit, and job id.
* @type {number}
* @memberof UsagesSummary
*/
usagesCount?: number;
/**
*
* @type {string}
* @memberof UsagesSummary
*/
processStatus?: UsagesSummary.ProcessStatusEnum;
}
/**
* @export
* @namespace UsagesSummary
*/
export namespace UsagesSummary {
/**
* @export
* @enum {string}
*/
export enum ProcessStatusEnum {
ACCEPTED = <any>"ACCEPTED",
VERIFIED = <any>"VERIFIED",
VERIFICATIONFAILED = <any>"VERIFICATIONFAILED",
NOVERIFICATION = <any>"NOVERIFICATION",
AGGREGATED = <any>"AGGREGATED",
SENTFORBILLING = <any>"SENTFORBILLING",
FAILEDTOSENDFORBILLING = <any>"FAILEDTOSENDFORBILLING",
RECEIVEDFORBILLING = <any>"RECEIVEDFORBILLING",
}
}
/**
*
* @export
* @interface User
*/
export interface User {
/**
*
* @type {string}
* @memberof User
*/
tenantId: string;
/**
*
* @type {string}
* @memberof User
*/
userId?: string;
/**
* type of user i.e. interactive user, an agent or usage corresponds to entire tenant. if not specified, default is ‘user
* @type {string}
* @memberof User
*/
userType?: User.UserTypeEnum;
/**
*
* @type {Array<ApplicationResource>}
* @memberof User
*/
resources: Array<ApplicationResource>;
}
/**
* @export
* @namespace User
*/
export namespace User {
/**
* @export
* @enum {string}
*/
export enum UserTypeEnum {
Tenant = "tenant",
User = "user",
Agent = "agent",
}
}
/**
*
* @export
* @interface UserUsage
*/
export interface UserUsage {
/**
*
* @type {string}
* @memberof UserUsage
*/
CustomerTenantID: string;
/**
*
* @type {string}
* @memberof UserUsage
*/
CustomerUserID: string;
/**
*
* @type {Array<ApplicationUsage>}
* @memberof UserUsage
*/
UTSUsageData: Array<ApplicationUsage>;
}
/**
*
* @export
* @interface Users
*/
export interface Users {
/**
*
* @type {Array<User>}
* @memberof Users
*/
users: Array<User>;
}
/**
*
* @export
* @interface ValidationError
*/
export interface ValidationError extends UsageError {
/**
*
* @type {Array<User>}
* @memberof ValidationError
*/
errorData?: Array<User>;
}
/**
* @export
* @namespace ValidationError
*/
export namespace ValidationError {}
} | the_stack |
import { HttpClient, HttpResponse } from '@angular/common/http';
import * as assert from 'assert';
import { findPrefix } from './utils';
import * as _ from 'lodash';
import uuid4 from 'uuid/v4';
import { from, Observable, throwError } from 'rxjs';
import { flatMap, map } from 'rxjs/operators';
import { Multipart } from './multipart';
import { SoapAttachment } from './soapAttachment';
const nonIdentifierChars = /[^a-z$_0-9]/i;
export const Client = function(wsdl, endpoint, options) {
options = options || {};
this.wsdl = wsdl;
this._initializeOptions(options);
this._initializeServices(endpoint);
this.httpClient = options.httpClient as HttpClient;
const promiseOptions: any = { multiArgs: true };
if (options.overridePromiseSuffix) {
promiseOptions.suffix = options.overridePromiseSuffix;
}
Promise.all([this, promiseOptions]);
};
Client.prototype.addSoapHeader = function(soapHeader, name, namespace, xmlns) {
if (!this.soapHeaders) {
this.soapHeaders = [];
}
if (typeof soapHeader === 'object') {
soapHeader = this.wsdl.objectToXML(soapHeader, name, namespace, xmlns, true);
}
return this.soapHeaders.push(soapHeader) - 1;
};
Client.prototype.changeSoapHeader = function(index, soapHeader, name, namespace, xmlns) {
if (!this.soapHeaders) {
this.soapHeaders = [];
}
if (typeof soapHeader === 'object') {
soapHeader = this.wsdl.objectToXML(soapHeader, name, namespace, xmlns, true);
}
this.soapHeaders[index] = soapHeader;
};
Client.prototype.getSoapHeaders = function() {
return this.soapHeaders;
};
Client.prototype.clearSoapHeaders = function() {
this.soapHeaders = null;
};
Client.prototype.addHttpHeader = function(name, value) {
if (!this.httpHeaders) {
this.httpHeaders = {};
}
this.httpHeaders[name] = value;
};
Client.prototype.getHttpHeaders = function() {
return this.httpHeaders;
};
Client.prototype.clearHttpHeaders = function() {
this.httpHeaders = {};
};
Client.prototype.addBodyAttribute = function(bodyAttribute, name, namespace, xmlns) {
if (!this.bodyAttributes) {
this.bodyAttributes = [];
}
if (typeof bodyAttribute === 'object') {
let composition = '';
Object.getOwnPropertyNames(bodyAttribute).forEach(function(prop, idx, array) {
composition += ' ' + prop + '="' + bodyAttribute[prop] + '"';
});
bodyAttribute = composition;
}
if (bodyAttribute.substr(0, 1) !== ' ') bodyAttribute = ' ' + bodyAttribute;
this.bodyAttributes.push(bodyAttribute);
};
Client.prototype.getBodyAttributes = function() {
return this.bodyAttributes;
};
Client.prototype.clearBodyAttributes = function() {
this.bodyAttributes = null;
};
Client.prototype.setEndpoint = function(endpoint) {
this.endpoint = endpoint;
this._initializeServices(endpoint);
};
Client.prototype.describe = function() {
const types = this.wsdl.definitions.types;
return this.wsdl.describeServices();
};
Client.prototype.setSecurity = function(security) {
this.security = security;
};
Client.prototype.setSOAPAction = function(SOAPAction) {
this.SOAPAction = SOAPAction;
};
Client.prototype._initializeServices = function(endpoint) {
const definitions = this.wsdl.definitions,
services = definitions.services;
for (const name in services) {
this[name] = this._defineService(services[name], endpoint);
}
};
Client.prototype._initializeOptions = function(options) {
this.streamAllowed = options.stream;
this.normalizeNames = options.normalizeNames;
this.wsdl.options.attributesKey = options.attributesKey || 'attributes';
this.wsdl.options.envelopeKey = options.envelopeKey || 'soap';
this.wsdl.options.preserveWhitespace = !!options.preserveWhitespace;
if (options.ignoredNamespaces !== undefined) {
if (options.ignoredNamespaces.override !== undefined) {
if (options.ignoredNamespaces.override === true) {
if (options.ignoredNamespaces.namespaces !== undefined) {
this.wsdl.options.ignoredNamespaces = options.ignoredNamespaces.namespaces;
}
}
}
}
if (options.overrideRootElement !== undefined) {
this.wsdl.options.overrideRootElement = options.overrideRootElement;
}
this.wsdl.options.forceSoap12Headers = !!options.forceSoap12Headers;
};
Client.prototype._defineService = function(service, endpoint) {
const ports = service.ports,
def = {};
for (const name in ports) {
def[name] = this._definePort(ports[name], endpoint ? endpoint : ports[name].location);
}
return def;
};
Client.prototype._definePort = function(port, endpoint) {
const location = endpoint,
binding = port.binding,
methods = binding.methods,
def = {};
for (const name in methods) {
def[name] = this._defineMethod(methods[name], location);
const methodName = this.normalizeNames ? name.replace(nonIdentifierChars, '_') : name;
this[methodName] = def[name];
}
return def;
};
Client.prototype._defineMethod = function(method, location) {
const self = this;
let temp = null;
return function(args, options, extraHeaders): Observable<any> {
return self._invoke(method, args, location, options, extraHeaders);
};
};
Client.prototype._invoke = function(method, args, location, options, extraHeaders): Observable<any> {
let self = this,
name = method.$name,
input = method.input,
output = method.output,
style = method.style,
defs = this.wsdl.definitions,
envelopeKey = this.wsdl.options.envelopeKey,
ns = defs.$targetNamespace,
encoding = '',
message = '',
xml = null,
req = null,
soapAction = null,
alias = findPrefix(defs.xmlns, ns),
headers: any = {
'Content-Type': 'text/xml; charset=utf-8'
},
xmlnsSoap = 'xmlns:' + envelopeKey + '="http://schemas.xmlsoap.org/soap/envelope/"';
if (this.wsdl.options.forceSoap12Headers) {
headers['Content-Type'] = 'application/soap+xml; charset=utf-8';
xmlnsSoap = 'xmlns:' + envelopeKey + '="http://www.w3.org/2003/05/soap-envelope"';
}
if (this.SOAPAction) {
soapAction = this.SOAPAction;
} else if (method.soapAction !== undefined && method.soapAction !== null) {
soapAction = method.soapAction;
} else {
soapAction = (ns.lastIndexOf('/') !== ns.length - 1 ? ns + '/' : ns) + name;
}
if (!this.wsdl.options.forceSoap12Headers) {
headers.SOAPAction = '"' + soapAction + '"';
}
options = options || {};
//Add extra headers
for (const header in this.httpHeaders) {
headers[header] = this.httpHeaders[header];
}
for (const attr in extraHeaders) {
headers[attr] = extraHeaders[attr];
}
// Allow the security object to add headers
if (self.security && self.security.addHeaders) self.security.addHeaders(headers);
if (self.security && self.security.addOptions) self.security.addOptions(options);
if (style === 'rpc' && (input.parts || input.name === 'element' || args === null)) {
assert.ok(!style || style === 'rpc', 'invalid message definition for document style binding');
message = self.wsdl.objectToRpcXML(name, args, alias, ns, input.name !== 'element');
method.inputSoap === 'encoded' && (encoding = 'soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" ');
} else {
assert.ok(!style || style === 'document', 'invalid message definition for rpc style binding');
// pass `input.$lookupType` if `input.$type` could not be found
message = self.wsdl.objectToDocumentXML(input.$name, args, input.targetNSAlias, input.targetNamespace, input.$type || input.$lookupType);
}
xml =
'<?xml version="1.0" encoding="utf-8"?>' +
'<' +
envelopeKey +
':Envelope ' +
xmlnsSoap +
' ' +
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
encoding +
this.wsdl.xmlnsInEnvelope +
'>' +
(self.soapHeaders || self.security
? '<' +
envelopeKey +
':Header>' +
(self.soapHeaders ? self.soapHeaders.join('\n') : '') +
(self.security && !self.security.postProcess ? self.security.toXML() : '') +
'</' +
envelopeKey +
':Header>'
: '') +
'<' +
envelopeKey +
':Body' +
(self.bodyAttributes ? self.bodyAttributes.join(' ') : '') +
(self.security && self.security.postProcess ? ' Id="_0"' : '') +
'>' +
message +
'</' +
envelopeKey +
':Body>' +
'</' +
envelopeKey +
':Envelope>';
if (self.security && self.security.postProcess) {
xml = self.security.postProcess(xml, envelopeKey);
}
if (options && options.postProcess) {
xml = options.postProcess(xml);
}
self.lastMessage = message;
self.lastRequest = xml;
self.lastEndpoint = location;
const tryJSONparse = function(body) {
try {
return JSON.parse(body);
} catch (err) {
return undefined;
}
};
return from(SoapAttachment.fromFormFiles(options.attachments)).pipe(
map((soapAttachments: SoapAttachment[]) => {
if (!soapAttachments.length) {
return xml;
}
if (options.forceMTOM || soapAttachments.length > 0) {
const start = uuid4();
const boundry = uuid4();
let action = null;
if (headers['Content-Type'].indexOf('action') > -1) {
for (const ct of headers['Content-Type'].split('; ')) {
if (ct.indexOf('action') > -1) {
action = ct;
}
}
}
headers['Content-Type'] =
'multipart/related; type="application/xop+xml"; start="<' + start + '>"; start-info="text/xml"; boundary="' + boundry + '"';
if (action) {
headers['Content-Type'] = headers['Content-Type'] + '; ' + action;
}
const multipart: any[] = [
{
'Content-Type': 'application/xop+xml; charset=UTF-8; type="text/xml"',
'Content-ID': '<' + start + '>',
body: xml
}
];
soapAttachments.forEach((attachment: SoapAttachment) => {
multipart.push({
'Content-Type': attachment.mimetype + ';',
'Content-Transfer-Encoding': 'binary',
'Content-ID': '<' + (attachment.contentId || attachment.name) + '>',
'Content-Disposition': 'attachment; name="' + attachment.name + '"; filename="' + attachment.name + '"',
body: attachment.body
});
});
return new Multipart().build(multipart, boundry);
}
}),
flatMap((body: any) =>
(<HttpClient>self.httpClient)
.post(location, body, {
headers: headers,
responseType: 'text',
observe: 'response'
})
.pipe(
map((response: HttpResponse<any>) => {
self.lastResponse = response.body;
self.lastResponseHeaders = response && response.headers;
return parseSync(response.body, response);
})
)
)
);
function parseSync(body, response: HttpResponse<any>) {
let obj;
try {
obj = self.wsdl.xmlToObject(body);
} catch (error) {
// When the output element cannot be looked up in the wsdl and the body is JSON
// instead of sending the error, we pass the body in the response.
if (!output || !output.$lookupTypes) {
// debug('Response element is not present. Unable to convert response xml to json.');
// If the response is JSON then return it as-is.
const json = _.isObject(body) ? body : tryJSONparse(body);
if (json) {
return { err: null, response, responseBody: json, header: undefined, xml };
}
}
error.response = response;
error.body = body;
// self.emit('soapError', error, eid);
throw error;
}
return finish(obj, body, response);
}
function finish(obj, responseBody, response) {
let result = null;
if (!output) {
// one-way, no output expected
return { err: null, response: null, responseBody, header: obj.Header, xml };
}
// If it's not HTML and Soap Body is empty
if (!obj.html && !obj.Body) {
return { err: null, obj, responseBody, header: obj.Header, xml };
}
if (typeof obj.Body !== 'object') {
const error: any = new Error('Cannot parse response');
error.response = response;
error.body = responseBody;
return { err: error, obj, responseBody, header: undefined, xml };
}
result = obj.Body[output.$name];
// RPC/literal response body may contain elements with added suffixes I.E.
// 'Response', or 'Output', or 'Out'
// This doesn't necessarily equal the ouput message name. See WSDL 1.1 Section 2.4.5
if (!result) {
result = obj.Body[output.$name.replace(/(?:Out(?:put)?|Response)$/, '')];
}
if (!result) {
['Response', 'Out', 'Output'].forEach(function(term) {
if (obj.Body.hasOwnProperty(name + term)) {
return (result = obj.Body[name + term]);
}
});
}
return { err: null, result, responseBody, header: obj.Header, xml };
}
};
Client.prototype.call = function(method: string, body: any, options?: any, extraHeaders?: any): Observable<any> {
if (!this[method]) {
return throwError(`Method ${method} not found`);
}
return (<Function>this[method]).call(this, body, options, extraHeaders);
}; | the_stack |
import {ConvertedSyntaxKind} from '../../lib/json/converted_syntax_kinds';
import {expectTranslateJSON, prettyStringify} from './json_test_support';
describe('merging variables with types', () => {
describe('upgrading variables whose types contain construct signatures', () => {
it('supports type literals with construct signatures', () => {
expectTranslateJSON(`
declare interface XType {
a: number;
b: string;
c(): boolean;
}
declare var X: { new(a: number, b: string): XType };
`).to.equal(prettyStringify({
kind: ConvertedSyntaxKind.SourceFile,
fileName: 'demo/some/main.ts',
statements: [
{
kind: ConvertedSyntaxKind.InterfaceDeclaration,
modifiers: [],
name: 'XType',
members: [
{
kind: ConvertedSyntaxKind.PropertyDeclaration,
name: 'a',
optional: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'number'},
},
{
kind: ConvertedSyntaxKind.PropertyDeclaration,
name: 'b',
optional: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'string'},
},
{
kind: ConvertedSyntaxKind.MethodDeclaration,
name: 'c',
optional: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'boolean'},
parameters: []
}
]
},
{
kind: ConvertedSyntaxKind.InterfaceDeclaration,
modifiers: [],
name: 'X',
members: [
{
kind: ConvertedSyntaxKind.PropertyDeclaration,
name: 'a',
optional: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'number'},
},
{
kind: ConvertedSyntaxKind.PropertyDeclaration,
name: 'b',
optional: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'string'},
},
{
kind: ConvertedSyntaxKind.MethodDeclaration,
name: 'c',
optional: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'boolean'},
parameters: []
},
{
kind: ConvertedSyntaxKind.ConstructSignature,
name: 'X',
parameters: [
{
kind: ConvertedSyntaxKind.Parameter,
name: 'a',
optional: false,
destructured: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'number'}
},
{
kind: ConvertedSyntaxKind.Parameter,
name: 'b',
optional: false,
destructured: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'string'}
}
],
type: {kind: ConvertedSyntaxKind.TypeReference, typeName: 'XType'}
}
]
},
]
}));
});
it('supports interfaces with construct signatures', () => {
expectTranslateJSON(`
declare interface XType {
a: number;
b: string;
c(): boolean;
}
declare interface X {
new(a: number, b: string): XType;
}
declare var X: X;
`).to.equal(prettyStringify({
kind: ConvertedSyntaxKind.SourceFile,
fileName: 'demo/some/main.ts',
statements: [
{
kind: ConvertedSyntaxKind.InterfaceDeclaration,
modifiers: [],
name: 'XType',
members: [
{
kind: ConvertedSyntaxKind.PropertyDeclaration,
name: 'a',
optional: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'number'},
},
{
kind: ConvertedSyntaxKind.PropertyDeclaration,
name: 'b',
optional: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'string'},
},
{
kind: ConvertedSyntaxKind.MethodDeclaration,
name: 'c',
optional: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'boolean'},
parameters: []
}
]
},
{
kind: ConvertedSyntaxKind.InterfaceDeclaration,
modifiers: [],
name: 'X',
members: [
{
kind: ConvertedSyntaxKind.PropertyDeclaration,
name: 'a',
optional: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'number'},
},
{
kind: ConvertedSyntaxKind.PropertyDeclaration,
name: 'b',
optional: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'string'},
},
{
kind: ConvertedSyntaxKind.MethodDeclaration,
name: 'c',
optional: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'boolean'},
parameters: []
},
{
kind: ConvertedSyntaxKind.ConstructSignature,
name: 'X',
parameters: [
{
kind: ConvertedSyntaxKind.Parameter,
name: 'a',
optional: false,
destructured: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'number'}
},
{
kind: ConvertedSyntaxKind.Parameter,
name: 'b',
optional: false,
destructured: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'string'}
}
],
type: {kind: ConvertedSyntaxKind.TypeReference, typeName: 'XType'}
}
]
},
]
}));
});
it('makes members of the type static in the upgraded class by default', () => {
expectTranslateJSON(`
declare interface XType {
n: number;
}
declare var X: {
new(n: number): XType
m: string;
};
`).to.equal(prettyStringify({
kind: ConvertedSyntaxKind.SourceFile,
fileName: 'demo/some/main.ts',
statements: [
{
kind: ConvertedSyntaxKind.InterfaceDeclaration,
modifiers: [],
name: 'XType',
members: [
{
kind: ConvertedSyntaxKind.PropertyDeclaration,
name: 'n',
optional: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'number'},
},
]
},
{
kind: ConvertedSyntaxKind.InterfaceDeclaration,
modifiers: [],
name: 'X',
members: [
{
kind: ConvertedSyntaxKind.PropertyDeclaration,
name: 'n',
optional: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'number'},
},
{
kind: ConvertedSyntaxKind.ConstructSignature,
name: 'X',
parameters: [{
kind: ConvertedSyntaxKind.Parameter,
name: 'n',
optional: false,
destructured: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'number'}
}],
type: {kind: ConvertedSyntaxKind.TypeReference, typeName: 'XType'}
},
{
kind: ConvertedSyntaxKind.PropertyDeclaration,
modifiers: [{kind: ConvertedSyntaxKind.StaticModifier}],
name: 'm',
optional: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'string'},
},
]
},
]
}));
});
it('does not make members of the type static when the --explicit-static flag is set', () => {
const explicitStaticOpts = {toJSON: true, failFast: true, explicitStatic: true};
expectTranslateJSON(
`
declare interface XType {
n: number;
}
declare var X: {
new(n: number): XType
m: string;
};
`,
explicitStaticOpts,
)
.to.equal(prettyStringify({
kind: ConvertedSyntaxKind.SourceFile,
fileName: 'demo/some/main.ts',
statements: [
{
kind: ConvertedSyntaxKind.InterfaceDeclaration,
modifiers: [],
name: 'XType',
members: [
{
kind: ConvertedSyntaxKind.PropertyDeclaration,
name: 'n',
optional: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'number'},
},
]
},
{
kind: ConvertedSyntaxKind.InterfaceDeclaration,
modifiers: [],
name: 'X',
members: [
{
kind: ConvertedSyntaxKind.PropertyDeclaration,
name: 'n',
optional: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'number'},
},
{
kind: ConvertedSyntaxKind.ConstructSignature,
name: 'X',
parameters: [{
kind: ConvertedSyntaxKind.Parameter,
name: 'n',
optional: false,
destructured: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'number'}
}],
type: {kind: ConvertedSyntaxKind.TypeReference, typeName: 'XType'}
},
{
kind: ConvertedSyntaxKind.PropertyDeclaration,
name: 'm',
optional: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'string'},
},
]
},
]
}));
});
});
describe('merging variables with types based on their names', () => {
it('merges variables with types if they have the exact same name by default', () => {
expectTranslateJSON(`
declare interface X {
a: number;
b: string;
c(): boolean;
}
declare var X: { d: number; }
`).to.equal(prettyStringify({
kind: ConvertedSyntaxKind.SourceFile,
fileName: 'demo/some/main.ts',
statements: [
{
kind: ConvertedSyntaxKind.InterfaceDeclaration,
modifiers: [],
name: 'X',
members: [
{
kind: ConvertedSyntaxKind.PropertyDeclaration,
name: 'a',
optional: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'number'},
},
{
kind: ConvertedSyntaxKind.PropertyDeclaration,
name: 'b',
optional: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'string'},
},
{
kind: ConvertedSyntaxKind.MethodDeclaration,
name: 'c',
optional: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'boolean'},
parameters: []
},
{
kind: ConvertedSyntaxKind.PropertyDeclaration,
modifiers: [{kind: ConvertedSyntaxKind.StaticModifier}],
name: 'd',
optional: false,
type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'number'},
}
]
},
// TODO(derekx): Small fix to make the JSON cleaner: in mergeVariablesIntoClasses we
// should detect when deleting a VariableDeclartion makes the parent
// VariableDeclarationList empty, and delete the list node as well.
{
kind: ConvertedSyntaxKind.VariableStatement,
modifiers: [],
keyword: 'var',
declarations: []
}
]
}));
});
// TODO(derekx): The following test should pass, but currently the type of var x is incorrect.
// It is currently a TypeReference to 'X', but it should be to 'XType'.
// it('renames types that conflict with unrelated variables when --rename-conflicting-types
// is set',
// () => {
// const renameTypesOpts = {toJSON: true, failFast: true, renameConflictingTypes:
// true}; expectTranslateJSON(
// `
// declare interface X {
// a: number;
// b: string;
// }
// declare var X: { y: number; }
// declare var x: X;
// `,
// renameTypesOpts,
// )
// .to.equal(prettyStringify({
// kind: ConvertedSyntaxKind.SourceFile,
// fileName: 'demo/some/main.ts',
// statements: [
// {
// kind: ConvertedSyntaxKind.InterfaceDeclaration,
// modifiers: [],
// name: 'XType',
// members: [
// {
// kind: ConvertedSyntaxKind.PropertyDeclaration,
// name: 'a',
// optional: false,
// type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'number'},
// },
// {
// kind: ConvertedSyntaxKind.PropertyDeclaration,
// name: 'b',
// optional: false,
// type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'string'},
// },
// ]
// },
// {
// kind: ConvertedSyntaxKind.VariableStatement,
// keyword: 'var',
// declarations: [{
// kind: ConvertedSyntaxKind.VariableDeclaration,
// name: 'X',
// type: {
// kind: ConvertedSyntaxKind.TypeLiteral,
// members: [{
// kind: ConvertedSyntaxKind.PropertyDeclaration,
// name: 'y',
// type: {kind: ConvertedSyntaxKind.KeywordType, typeName: 'number'}
// }]
// }
// }]
// },
// {
// kind: ConvertedSyntaxKind.VariableStatement,
// keyword: 'var',
// declarations: [{
// kind: ConvertedSyntaxKind.VariableDeclaration,
// name: 'x',
// type: {kind: ConvertedSyntaxKind.TypeReference, typeName: 'XType'}
// }]
// }
// ]
// }));
// });
});
}); | the_stack |
// NOTE: Chipmunk's partial copying of VSCode solution. Related modules/libs:
// https://github.com/microsoft/vscode/blob/main/src/vs/workbench/contrib/terminal/node/terminalProfiles.ts
// https://github.com/microsoft/vscode/blob/main/src/vs/workbench/contrib/terminal/node/terminalEnvironment.ts
// https://github.com/microsoft/vscode/blob/main/src/vs/base/node/pfs.ts
import * as fs from 'fs';
import * as os from 'os';
import * as cp from 'child_process';
import * as paths from 'path';
import * as ps from './powershell';
const ENOENT: string = 'ENOENT';
export interface ITerminalProfile {
profileName: string;
path: string;
args?: string | string[] | undefined;
env?: ITerminalEnvironment;
}
export interface ITerminalEnvironment {
[key: string]: string | null | undefined;
}
export const enum ProfileSource {
GitBash = 'Git Bash',
Pwsh = 'PowerShell'
}
export interface ITerminalExecutable {
path: string | string[];
args?: string | string[] | undefined;
env?: ITerminalEnvironment;
}
export interface ITerminalProfileSource {
source: ProfileSource;
args?: string | string[] | undefined;
env?: ITerminalEnvironment;
}
export type ITerminalProfileObject = ITerminalExecutable | ITerminalProfileSource | null;
export function exists(filename: string): Promise<boolean> {
return new Promise((resolve, reject) => {
fs.access(filename, fs.constants.F_OK, (err: NodeJS.ErrnoException | null) => {
if (err) {
if (err.code === ENOENT) {
return resolve(false);
} else {
return reject(err);
}
} else {
resolve(true);
}
});
});
}
let profileSources: Map<string, IPotentialTerminalProfile> | undefined;
export function getWindowsBuildNumber(): number {
const osVersion = (/(\d+)\.(\d+)\.(\d+)/g).exec(os.release());
let buildNumber: number = 0;
if (osVersion && osVersion.length === 4) {
buildNumber = parseInt(osVersion[3]);
}
return buildNumber;
}
export function getCaseInsensitive(target: any, key: string): any {
const lowercaseKey = key.toLowerCase();
const equivalentKey = Object.keys(target).find(k => k.toLowerCase() === lowercaseKey);
return equivalentKey ? target[equivalentKey] : target[key];
}
export async function findExecutable(
command: string,
cwd?: string,
pathsToCheck?: string[],
env: ITerminalEnvironment = process.env as ITerminalEnvironment): Promise<string | undefined> {
// If we have an absolute path then we take it.
if (paths.isAbsolute(command)) {
return await exists(command) ? command : undefined;
}
if (cwd === undefined) {
cwd = process.cwd();
}
const dir = paths.dirname(command);
if (dir !== '.') {
// We have a directory and the directory is relative (see above). Make the path absolute
// to the current working directory.
const fullPath = paths.join(cwd, command);
return await exists(fullPath) ? fullPath : undefined;
}
const envPath = getCaseInsensitive(env, 'PATH');
if (pathsToCheck === undefined && typeof envPath === 'string') {
pathsToCheck = envPath.split(paths.delimiter);
}
// No PATH environment. Make path absolute to the cwd.
if (pathsToCheck === undefined || pathsToCheck.length === 0) {
const fullPath = paths.join(cwd, command);
return await exists(fullPath) ? fullPath : undefined;
}
// We have a simple file name. We get the path variable from the env
// and try to find the executable on the path.
for (let pathEntry of pathsToCheck) {
// The path entry is absolute.
let fullPath: string;
if (paths.isAbsolute(pathEntry)) {
fullPath = paths.join(pathEntry, command);
} else {
fullPath = paths.join(cwd, pathEntry, command);
}
if (await exists(fullPath)) {
return fullPath;
}
if (process.platform === 'win32') {
let withExtension = fullPath + '.com';
if (await exists(withExtension)) {
return withExtension;
}
withExtension = fullPath + '.exe';
if (await exists(withExtension)) {
return withExtension;
}
}
}
const fullPath = paths.join(cwd, command);
return await exists(fullPath) ? fullPath : undefined;
}
export function detectAvailableProfiles(): Promise<ITerminalProfile[]> {
if (process.platform === 'win32') {
return detectAvailableWindowsProfiles();
}
return detectAvailableUnixProfiles();
}
async function detectAvailableWindowsProfiles(): Promise<ITerminalProfile[]> {
// Determine the correct System32 path. We want to point to Sysnative
// when the 32-bit version of VS Code is running on a 64-bit machine.
// The reason for this is because PowerShell's important PSReadline
// module doesn't work if this is not the case. See #27915.
const is32ProcessOn64Windows = process.env.hasOwnProperty('PROCESSOR_ARCHITEW6432');
const system32Path = `${process.env['windir']}\\${is32ProcessOn64Windows ? 'Sysnative' : 'System32'}`;
let useWSLexe = false;
if (getWindowsBuildNumber() >= 16299) {
useWSLexe = true;
}
await initializeWindowsProfiles();
const detectedProfiles: Map<string, ITerminalProfileObject> = new Map();
// Add auto detected profiles
detectedProfiles.set('PowerShell', {
source: ProfileSource.Pwsh,
});
detectedProfiles.set('Windows PowerShell', {
path: `${system32Path}\\WindowsPowerShell\\v1.0\\powershell.exe`,
});
detectedProfiles.set('Git Bash', { source: ProfileSource.GitBash });
detectedProfiles.set('Cygwin', {
path: [
`${process.env['HOMEDRIVE']}\\cygwin64\\bin\\bash.exe`,
`${process.env['HOMEDRIVE']}\\cygwin\\bin\\bash.exe`
],
args: ['--login'],
});
detectedProfiles.set('Command Prompt',
{
path: `${system32Path}\\cmd.exe`,
},
);
const resultProfiles: ITerminalProfile[] = await transformToTerminalProfiles(detectedProfiles.entries());
try {
const result = await getWslProfiles(`${system32Path}\\${useWSLexe ? 'wsl.exe' : 'bash.exe'}`, useWSLexe);
if (result) {
resultProfiles.push(...result);
}
} catch (e) {
console.info('WSL is not installed, so could not detect WSL profiles');
}
return resultProfiles;
}
async function transformToTerminalProfiles(entries: IterableIterator<[string, ITerminalProfileObject]>): Promise<ITerminalProfile[]> {
const resultProfiles: ITerminalProfile[] = [];
for (const [profileName, profile] of entries) {
if (profile === null) { continue; }
let originalPaths: string[];
let args: string[] | string | undefined;
if ('source' in profile) {
const source = profileSources?.get(profile.source);
if (!source) {
continue;
}
originalPaths = source.paths;
// if there are configured args, override the default ones
args = profile.args || source.args;
} else {
originalPaths = Array.isArray(profile.path) ? profile.path : [profile.path];
args = process.platform === 'win32' ? profile.args : Array.isArray(profile.args) ? profile.args : undefined;
}
const paths = originalPaths.slice();
const validatedProfile = await validateProfilePaths(profileName, paths, args, profile.env);
if (validatedProfile) {
resultProfiles.push(validatedProfile);
}
}
return resultProfiles;
}
async function initializeWindowsProfiles(): Promise<void> {
if (profileSources) {
return;
}
profileSources = new Map();
profileSources.set(
'Git Bash', {
profileName: 'Git Bash',
paths: [
`${process.env['ProgramW6432']}\\Git\\bin\\bash.exe`,
`${process.env['ProgramW6432']}\\Git\\usr\\bin\\bash.exe`,
`${process.env['ProgramFiles']}\\Git\\bin\\bash.exe`,
`${process.env['ProgramFiles']}\\Git\\usr\\bin\\bash.exe`,
`${process.env['LocalAppData']}\\Programs\\Git\\bin\\bash.exe`
],
args: ['--login']
});
profileSources.set('PowerShell', {
profileName: 'PowerShell',
paths: await getPowershellPaths(),
});
}
async function getPowershellPaths(): Promise<string[]> {
const paths: string[] = [];
// Add all of the different kinds of PowerShells
for await (const pwshExe of ps.enumeratePowerShellInstallations()) {
paths.push(pwshExe.exePath);
}
return paths;
}
async function getWslProfiles(wslPath: string, useWslProfiles?: boolean): Promise<ITerminalProfile[]> {
const profiles: ITerminalProfile[] = [];
if (useWslProfiles) {
const distroOutput = await new Promise<string>((resolve, reject) => {
// wsl.exe output is encoded in utf16le (ie. A -> 0x4100)
cp.exec('wsl.exe -l -q', { encoding: 'utf16le' }, (err, stdout) => {
if (err) {
return reject('Problem occurred when getting wsl distros');
}
resolve(stdout);
});
});
if (distroOutput) {
const regex = new RegExp(/[\r?\n]/);
const distroNames = distroOutput.split(regex).filter(t => t.trim().length > 0 && t !== '');
for (let distroName of distroNames) {
// Skip empty lines
if (distroName === '') {
continue;
}
// docker-desktop and docker-desktop-data are treated as implementation details of
// Docker Desktop for Windows and therefore not exposed
if (distroName.startsWith('docker-desktop')) {
continue;
}
const profile: ITerminalProfile = {
profileName: `${distroName} (WSL)`,
path: wslPath,
args: [`-d`, `${distroName}`]
};
// Add the profile
profiles.push(profile);
}
return profiles;
}
}
return [];
}
async function detectAvailableUnixProfiles(): Promise<ITerminalProfile[]> {
const detectedProfiles: Map<string, ITerminalProfileObject> = new Map();
const contents = await fs.promises.readFile('/etc/shells', 'utf8');
const profiles = contents.split('\n').filter(e => e.trim().indexOf('#') !== 0 && e.trim().length > 0);
const counts: Map<string, number> = new Map();
for (const profile of profiles) {
let profileName = paths.basename(profile);
let count = counts.get(profileName) || 0;
count++;
if (count > 1) {
profileName = `${profileName} (${count})`;
}
counts.set(profileName, count);
detectedProfiles.set(profileName, { path: profile });
}
return await transformToTerminalProfiles(detectedProfiles.entries());
}
function applyConfigProfilesToMap(configProfiles: { [key: string]: ITerminalProfileObject } | undefined, profilesMap: Map<string, ITerminalProfileObject>) {
if (!configProfiles) {
return;
}
for (const [profileName, value] of Object.entries(configProfiles)) {
if (value === null || (!('path' in value) && !('source' in value))) {
profilesMap.delete(profileName);
} else {
profilesMap.set(profileName, value);
}
}
}
async function validateProfilePaths(profileName: string, potentialPaths: string[], args?: string[] | string, env?: ITerminalEnvironment): Promise<ITerminalProfile | undefined> {
if (potentialPaths.length === 0) {
return Promise.resolve(undefined);
}
const path = potentialPaths.shift()!;
if (path === '') {
return validateProfilePaths(profileName, potentialPaths, args, env);
}
const profile: ITerminalProfile = { profileName, path, args, env };
// For non-absolute paths, check if it's available on $PATH
if (paths.basename(path) === path) {
// The executable isn't an absolute path, try find it on the PATH
const envPaths: string[] | undefined = process.env.PATH ? process.env.PATH.split(paths.delimiter) : undefined;
const executable = await findExecutable(path, undefined, envPaths, undefined);
if (!executable) {
return validateProfilePaths(profileName, potentialPaths, args);
}
return profile;
}
const result = await exists(paths.normalize(path));
if (result) {
return profile;
}
return validateProfilePaths(profileName, potentialPaths, args, env);
}
export interface IFsProvider {
existsFile(path: string): Promise<boolean>,
readFile(path: string, options: { encoding: BufferEncoding, flag?: string | number } | BufferEncoding): Promise<string>;
}
interface IPotentialTerminalProfile {
profileName: string;
paths: string[];
args?: string[];
} | the_stack |
import uuid from "uuid";
import App from "../app";
import Team from "./teams";
import DamageStep from "./generic/damageStep";
import DamageTask from "./generic/damageTask";
import {Station, Card} from "./stationSet";
import {noCase, camelCase} from "change-case";
import {Record, RecordSnippet} from "./records";
import Assets from "./simulatorAssets";
import SoundEffects from "./simulatorSoundEffects";
import TimelineInstance from "./timelineInstance";
import Ship from "./ship";
import Ambiance from "./ambiance";
import Lighting from "./lighting";
import RemoteAccess from "./remoteAccess";
import Document from "./document";
export default class Simulator {
id: string;
name: string;
layout: string;
caps: boolean;
hasLegs: boolean;
alertLevel: "1" | "2" | "3" | "4" | "5" | "p";
alertLevelLock: boolean;
template: boolean;
templateId: string | null;
class: "Simulator";
assets: Assets;
soundEffects: SoundEffects;
stationSet: string;
stations: Station[];
exocomps: number;
mission: string;
currentTimelineStep: number;
executedTimelineSteps: string[];
timelines: TimelineInstance[];
missionConfigs: any;
bridgeOfficerMessaging: boolean;
teams: Team[];
training: boolean;
ship: Ship;
panels: string[];
commandLines: string[];
triggers: string[];
triggersPaused: boolean;
interfaces: string[];
lighting: Lighting;
ambiance: Ambiance[];
midiSets: string[];
crackedClients: {[key: string]: boolean};
clientCards: {[key: string]: string};
stationAssignedCards: {[key: string]: Card[]};
flipped: boolean;
hasPrinter: boolean;
stepDamage: boolean;
verifyStep: boolean;
requiredDamageSteps: DamageStep[];
optionalDamageSteps: DamageStep[];
damageTasks: DamageTask[];
commandLineOutputs: {[key: string]: string[]};
commandLineFeedback: any;
records: Record[];
recordSnippets: RecordSnippet[];
documents: Document[];
spaceEdventuresId: string | null;
constructor(params: Partial<Simulator> = {}, newlyCreated: boolean = false) {
this.id = params.id || uuid.v4();
this.name = params.name || "Simulator";
this.layout = params.layout || "LayoutCorners";
this.caps = params.caps || false;
// TODO: Move this property to the ship class
this.hasLegs = params.hasLegs || false;
this.alertLevel = params.alertLevel || "5";
this.alertLevelLock = params.alertLevelLock || false;
this.template = params.template || false;
this.templateId = params.templateId || null;
this.class = "Simulator";
this.assets = new Assets({...params.assets});
this.soundEffects = new SoundEffects({...params.soundEffects});
this.stationSet = params.stationSet || null;
this.stations = [];
this.exocomps = params.exocomps || 0;
// Mission Stuff
this.mission = params.mission || null;
this.currentTimelineStep = params.currentTimelineStep || 0;
this.executedTimelineSteps = params.executedTimelineSteps || [];
this.timelines = [];
params.timelines &&
params.timelines.forEach(t =>
this.timelines.push(new TimelineInstance(t)),
);
this.missionConfigs = params.missionConfigs || {};
this.bridgeOfficerMessaging = params.bridgeOfficerMessaging ?? true;
this.teams = [];
this.training = params.training || false;
this.ship = new Ship({...params.ship}, newlyCreated);
this.panels = params.panels || [];
this.commandLines = params.commandLines || [];
this.triggers = params.triggers || [];
this.triggersPaused = params.triggersPaused || false;
this.interfaces = params.interfaces || [];
params.stations &&
params.stations.forEach(s => this.stations.push(new Station(s)));
// Effects Control
this.lighting = new Lighting({...params.lighting});
this.ambiance = [];
if (params.ambiance)
params.ambiance.forEach(a => this.ambiance.push(new Ambiance(a)));
this.midiSets = params.midiSets || [];
this.crackedClients = params.crackedClients || {};
// The name of the current card which each
// station is on.
this.clientCards = params.clientCards || {};
// Cards assigned to another station from a different station.
this.stationAssignedCards = params.stationAssignedCards || {};
this.flipped = params.flipped || false;
// Set up the teams
if (params.teams) {
params.teams.forEach(t => this.teams.push(new Team(t)));
}
this.hasPrinter = params.hasPrinter ?? true;
// Damage reports
this.stepDamage = params.stepDamage ?? true;
this.verifyStep = params.verifyStep || false;
this.requiredDamageSteps = [];
this.optionalDamageSteps = [];
params.requiredDamageSteps &&
params.requiredDamageSteps.forEach(s =>
this.requiredDamageSteps.push(new DamageStep(s)),
);
params.optionalDamageSteps &&
params.optionalDamageSteps.forEach(s =>
this.optionalDamageSteps.push(new DamageStep(s)),
);
// Task-based damage reports
this.damageTasks = [];
params.damageTasks &&
params.damageTasks.forEach(s => this.damageTasks.push(new DamageTask(s)));
// Command Lines
this.commandLineOutputs = {};
this.commandLineFeedback = {};
// Records
this.records = [];
this.recordSnippets = [];
params.records &&
params.records.forEach(r => this.records.push(new Record(r)));
params.recordSnippets &&
params.recordSnippets.forEach(r =>
this.recordSnippets.push(
new RecordSnippet({...r, simulatorId: this.id}),
),
);
this.documents = params.documents || [];
// For Space EdVentures
this.spaceEdventuresId = params.spaceEdventuresId || null;
}
get alertlevel() {
const stealthField = App.systems.find(
s => s.simulatorId === this.id && s.type === "StealthField",
);
if (!stealthField) return this.alertLevel;
if (
stealthField.changeAlert &&
stealthField.activated &&
stealthField.state
)
return "p";
return this.alertLevel;
}
set alertlevel(level) {
this.alertLevel = level;
}
trainingMode(tf: boolean) {
this.training = tf;
}
rename(name: string) {
this.name = name;
}
setAlertLevel(alertlevel: "1" | "2" | "3" | "4" | "5" | "p" = "5") {
if (["5", "4", "3", "2", "1", "p"].indexOf(alertlevel) === -1) {
return;
}
this.alertlevel = alertlevel;
}
setAlertLevelLock(lock: boolean) {
this.alertLevelLock = lock;
}
setLayout(layout: string) {
this.layout = layout;
}
setClientCard(client: string, cardName: string) {
this.clientCards[client] = cardName;
}
addStationAssignedCard(station: string, card: Card) {
const stationCards = this.stationAssignedCards[station];
this.stationAssignedCards[station] = stationCards
? stationCards.concat(card)
: [card];
}
removeStationAssignedCard(cardName: string) {
const stationEntry = Object.entries(
this.stationAssignedCards,
).find(([key, value]) => value.find(c => c.name === cardName));
const station = stationEntry?.[0];
if (!station) return;
const stationCards = this.stationAssignedCards[station];
this.stationAssignedCards[station] = stationCards
? stationCards.filter(c => c.name !== cardName)
: [];
}
setTimelineStep(step: number, timelineId: string = null) {
if (timelineId) {
this.setAuxTimelineStep(timelineId, step);
} else {
this.currentTimelineStep = step;
}
}
executeTimelineStep(stepId: string) {
this.executedTimelineSteps.push(stepId);
this.executedTimelineSteps = this.executedTimelineSteps.filter(
(a, i, arr) => arr.indexOf(a) === i,
);
}
addAuxTimeline(missionId: string) {
const timeline = new TimelineInstance({missionId});
this.timelines.push(timeline);
return timeline.id;
}
setAuxTimelineStep(timelineId: string, step: number) {
const timeline = this.timelines.find(t => t.id === timelineId);
timeline && timeline.setTimelineStep(step);
}
setMissionConfig(
missionId: string,
stationSetId: string,
actionId: string,
args: any,
) {
this.missionConfigs[missionId] = this.missionConfigs[missionId] || {};
this.missionConfigs[missionId][stationSetId] =
this.missionConfigs[missionId][stationSetId] || {};
this.missionConfigs[missionId][stationSetId][actionId] = {
...this.missionConfigs[missionId][stationSetId][actionId],
...args,
};
}
updateLighting(lighting: Partial<Lighting>) {
this.lighting.update(lighting);
}
updateAmbiance(ambiance: Ambiance) {
this.ambiance.find(a => a.id === ambiance.id).update(ambiance);
}
addAmbiance(ambiance: Partial<Ambiance>) {
this.ambiance.push(new Ambiance(ambiance));
}
removeAmbiance(id: string) {
this.ambiance = this.ambiance.filter(a => a.id !== id);
}
// Ship
clamps(tf: boolean) {
this.ship.clamps = tf;
}
ramps(tf: boolean) {
this.ship.ramps = tf;
}
airlock(tf: boolean) {
this.ship.airlock = tf;
}
legs(tf: boolean) {
this.ship.legs = tf;
}
bridgeCrew(num: number) {
this.ship.bridgeCrew = num;
}
extraPeople(num: number) {
this.ship.extraPeople = num;
}
radiation(num: number) {
this.ship.radiation = num;
}
speed(num: number) {
this.ship.speed = num;
}
sendCode(code: string, station: string) {
this.ship.remoteAccessCodes.push(new RemoteAccess({code, station}));
}
updateCode(codeId: string, state: "Denied" | "Accepted" | "sent") {
this.ship.remoteAccessCodes.find(c => c.id === codeId).state = state;
}
setSelfDestructTime(time: number) {
this.ship.selfDestructTime = time;
}
setSelfDestructCode(code: string) {
this.ship.selfDestructCode = code;
}
setSelfDestructAuto(tf: boolean) {
this.ship.selfDestructAuto = tf;
}
updatePanels(panels: string[]) {
this.panels = panels || [];
}
updateCommandLines(commandLines: string[]) {
this.commandLines = commandLines || [];
}
updateTriggers(triggers: string[]) {
this.triggers = triggers || [];
}
setTriggersPaused(paused: boolean) {
this.triggersPaused = paused;
}
updateInterfaces(interfaces: string[]) {
this.interfaces = interfaces || [];
}
setAssets(assets: Assets) {
this.assets = new Assets(assets);
}
setSoundEffects(effects: SoundEffects) {
this.soundEffects = new SoundEffects(effects);
}
setHasPrinter(hasPrinter: boolean) {
this.hasPrinter = hasPrinter;
}
setHasLegs(hasLegs: boolean) {
this.hasLegs = hasLegs;
}
// Damage Steps
addDamageStep({name, args, type}: {name: string; args: any; type: string}) {
this[`${type}DamageSteps`].push(new DamageStep({name, args}));
}
updateDamageStep({id, name, args}: {name: string; args: any; id: string}) {
const step =
this.requiredDamageSteps.find(s => s.id === id) ||
this.optionalDamageSteps.find(s => s.id === id);
step.update({name, args});
}
removeDamageStep(stepId: string) {
// Check both required and optional
this.requiredDamageSteps = this.requiredDamageSteps.filter(
s => s.id !== stepId,
);
this.optionalDamageSteps = this.optionalDamageSteps.filter(
s => s.id !== stepId,
);
}
// Damage Tasks
// As a side note, can I just say how much more elegant
// the damage tasks system is already? Look at this!
// It's much simpler. Why didn't I do it this
// way in the first place? ~A
addDamageTask(task: DamageTask) {
if (!task || !task.id || this.damageTasks.find(t => t.id === task.id))
return;
this.damageTasks.push(new DamageTask(task));
}
updateDamageTask(task: DamageTask) {
this.damageTasks.find(t => t.id === task.id).update(task);
}
removeDamageTask(id: string) {
this.damageTasks = this.damageTasks.filter(t => t.id !== id);
}
hideCard(cardName: string) {
const name = noCase(camelCase(cardName));
const cards = this.stations
? this.stations.reduce((acc, s) => acc.concat(s.cards), [])
: [];
cards.forEach(card => {
if (
card &&
(noCase(camelCase(card.name)) === name ||
noCase(camelCase(card.component)) === name)
) {
card.hidden = true;
}
});
}
unhideCard(cardName: string) {
const name = noCase(camelCase(cardName));
const cards = this.stations
? this.stations.reduce((acc, s) => acc.concat(s.cards), [])
: [];
cards.forEach(card => {
if (
card &&
(noCase(camelCase(card.name)) === name ||
noCase(camelCase(card.component)) === name)
) {
card.hidden = false;
}
});
}
// Command Line
addCommandLineOutput(clientId: string, line: string) {
if (!this.commandLineOutputs[clientId])
this.commandLineOutputs[clientId] = [];
this.commandLineOutputs[clientId].push(line);
}
addCommandLineFeedback(clientId: string, feedback: any) {
if (!this.commandLineFeedback[clientId])
this.commandLineFeedback[clientId] = [];
this.commandLineFeedback[clientId].push(feedback);
}
removeCommandLineFeedback(clientId: string, id: string) {
this.commandLineFeedback[clientId] = this.commandLineFeedback[
clientId
].filter(c => c.id !== id);
}
clearCommandLine(clientId: string) {
this.commandLineOutputs[clientId] = [];
}
crackClient(clientId: string) {
this.crackedClients[clientId] = true;
}
uncrackClient(clientId: string) {
this.crackedClients[clientId] = false;
}
flip(flip: boolean) {
this.flipped = flip;
}
// Records
createRecord(record: Record) {
const r = new Record(record);
this.records.push(r);
return r;
}
createRecordOnSnippet({
snippetId,
snippetName = "",
contents,
timestamp = 0,
category,
}) {
const snippet = this.recordSnippets.find(
s =>
s.id === snippetId ||
s.name.toLowerCase() === snippetName.toLowerCase(),
);
if (!snippet) return null;
function isValidDate(d: unknown): d is Date {
return d instanceof Date && !isNaN(Number(d));
}
// Get the latest record in this snippet and
// add the timestamp value to it.
const ts = snippet.records
.map(r => this.records.find(({id}) => id === r))
.reduce((acc, record) => {
const d = new Date(record.timestamp);
if (!isValidDate(d)) return acc;
if (acc > d) return acc;
return d;
}, 0);
const record = new Record({
contents,
timestamp: new Date(
new Date(ts).getTime() + Number(timestamp),
).toISOString(),
category,
snippetId: snippet.id,
});
this.records.push(record);
this.addRecordToSnippet(snippet.id, [record.id]);
return snippet;
}
createRecordSnippet(snippet: RecordSnippet) {
const s = new RecordSnippet({...snippet, simulatorId: this.id});
this.recordSnippets.push(s);
return s.id;
}
addRecordToSnippet(snippetId: string, recordIds: string[]) {
const snippet = this.recordSnippets.find(s => s.id === snippetId);
snippet.addRecords(recordIds);
}
removeRecordFromSnippet(snippetId: string, recordId: string) {
const snippet = this.recordSnippets.find(s => s.id === snippetId);
snippet.removeRecord(recordId);
}
showSnippet(snippetId: string) {
const snippet = this.recordSnippets.find(s => s.id === snippetId);
snippet.visible = true;
return snippet;
}
hideSnippet(snippetId: string) {
const snippet = this.recordSnippets.find(s => s.id === snippetId);
snippet.visible = false;
return snippet;
}
deleteRecord(recordId: string) {
this.records = this.records.filter(r => r.id !== recordId);
}
setSpaceEdventuresId(id: string) {
this.spaceEdventuresId = id;
}
} | the_stack |
import {ColorMode, Destination, DestinationConnectionStatus, DestinationOrigin, DestinationState, DestinationType, Margins, MarginsType, NativeInitialSettings, NativeLayerImpl, PluginProxyImpl, PreviewTicket, PrintPreviewAppElement, PrintPreviewDestinationSettingsElement, Range, ScalingType} from 'chrome://print/print_preview.js';
import {assert} from 'chrome://resources/js/assert.m.js';
import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js';
// <if expr="chromeos_ash or chromeos_lacros">
import {setNativeLayerCrosInstance} from './native_layer_cros_stub.js';
// </if>
import {NativeLayerStub} from './native_layer_stub.js';
import {getCddTemplate, getDefaultInitialSettings} from './print_preview_test_utils.js';
import {TestPluginProxy} from './test_plugin_proxy.js';
const preview_generation_test = {
suiteName: 'PreviewGenerationTest',
TestNames: {
Color: 'color',
CssBackground: 'css background',
HeaderFooter: 'header/footer',
Layout: 'layout',
Margins: 'margins',
CustomMargins: 'custom margins',
MediaSize: 'media size',
PageRange: 'page range',
Rasterize: 'rasterize',
PagesPerSheet: 'pages per sheet',
Scaling: 'scaling',
ScalingPdf: 'scalingPdf',
SelectionOnly: 'selection only',
Destination: 'destination',
ChangeMarginsByPagesPerSheet: 'change margins by pages per sheet',
ZeroDefaultMarginsClearsHeaderFooter:
'zero default margins clears header/footer',
}
};
Object.assign(window, {preview_generation_test: preview_generation_test});
type ValidateScalingChangeParams = {
printTicket: string,
scalingTypeKey: string,
expectedTicketId: number,
expectedTicketScaleFactor: number,
expectedScalingValue: string,
expectedScalingType: ScalingType,
};
suite(preview_generation_test.suiteName, function() {
let page: PrintPreviewAppElement;
let nativeLayer: NativeLayerStub;
const initialSettings: NativeInitialSettings = getDefaultInitialSettings();
setup(function() {
nativeLayer = new NativeLayerStub();
NativeLayerImpl.setInstance(nativeLayer);
// <if expr="chromeos_ash or chromeos_lacros">
setNativeLayerCrosInstance();
// </if>
document.body.innerHTML = '';
});
/**
* Initializes the UI with a default local destination and a 3 page document
* length.
* @return Promise that resolves when initialization is done,
* destination is set, and initial preview request is complete.
*/
function initialize(): Promise<{printTicket: string}> {
nativeLayer.setInitialSettings(initialSettings);
nativeLayer.setLocalDestinations(
[{deviceName: initialSettings.printerName, printerName: 'FooName'}]);
nativeLayer.setPageCount(3);
const pluginProxy = new TestPluginProxy();
PluginProxyImpl.setInstance(pluginProxy);
page = document.createElement('print-preview-app');
document.body.appendChild(page);
const documentInfo = page.$.documentInfo;
documentInfo.documentSettings.pageCount = 3;
documentInfo.margins = new Margins(10, 10, 10, 10);
return Promise
.all([
nativeLayer.whenCalled('getInitialSettings'),
nativeLayer.whenCalled('getPrinterCapabilities'),
])
.then(function() {
return nativeLayer.whenCalled('getPreview');
});
}
type SimpleSettingType = boolean|string|number;
/**
* @param settingName The name of the setting to test.
* @param initialSettingValue The default setting value.
* @param updatedSettingValue The setting value to update
* to.
* @param ticketKey The field in the print ticket that corresponds
* to the setting.
* @param initialTicketValue The ticket value
* corresponding to the default setting value.
* @param updatedTicketValue The ticket value
* corresponding to the updated setting value.
* @return Promise that resolves when the setting has been
* changed, the preview has been regenerated, and the print ticket and
* UI state have been verified.
*/
function testSimpleSetting(
settingName: string, initialSettingValue: SimpleSettingType,
updatedSettingValue: SimpleSettingType, ticketKey: string,
initialTicketValue: SimpleSettingType,
updatedTicketValue: SimpleSettingType): Promise<void> {
return initialize()
.then(function(args) {
const originalTicket: PreviewTicket = JSON.parse(args.printTicket);
assertEquals(0, originalTicket.requestID);
assertEquals(
initialTicketValue,
(originalTicket as {[key: string]: any})[ticketKey]);
nativeLayer.resetResolver('getPreview');
assertEquals(initialSettingValue, page.getSettingValue(settingName));
page.setSetting(settingName, updatedSettingValue);
return nativeLayer.whenCalled('getPreview');
})
.then(function(args) {
assertEquals(updatedSettingValue, page.getSettingValue(settingName));
const ticket: PreviewTicket = JSON.parse(args.printTicket);
assertEquals(
updatedTicketValue, (ticket as {[key: string]: any})[ticketKey]);
assertEquals(1, ticket.requestID);
});
}
function validateScalingChange(input: ValidateScalingChangeParams) {
const ticket: PreviewTicket = JSON.parse(input.printTicket);
assertEquals(input.expectedTicketId, ticket.requestID);
assertEquals(input.expectedTicketScaleFactor, ticket.scaleFactor);
assertEquals(input.expectedScalingValue, page.getSettingValue('scaling'));
assertEquals(
input.expectedScalingType, page.getSettingValue(input.scalingTypeKey));
}
/** Validate changing the color updates the preview. */
test(assert(preview_generation_test.TestNames.Color), function() {
return testSimpleSetting(
'color', true, false, 'color', ColorMode.COLOR, ColorMode.GRAY);
});
/** Validate changing the background setting updates the preview. */
test(assert(preview_generation_test.TestNames.CssBackground), function() {
return testSimpleSetting(
'cssBackground', false, true, 'shouldPrintBackgrounds', false, true);
});
/** Validate changing the header/footer setting updates the preview. */
test(assert(preview_generation_test.TestNames.HeaderFooter), function() {
return testSimpleSetting(
'headerFooter', true, false, 'headerFooterEnabled', true, false);
});
/** Validate changing the orientation updates the preview. */
test(assert(preview_generation_test.TestNames.Layout), function() {
return testSimpleSetting('layout', false, true, 'landscape', false, true);
});
/** Validate changing the margins updates the preview. */
test(assert(preview_generation_test.TestNames.Margins), function() {
return testSimpleSetting(
'margins', MarginsType.DEFAULT, MarginsType.MINIMUM, 'marginsType',
MarginsType.DEFAULT, MarginsType.MINIMUM);
});
/**
* Validate changing the custom margins updates the preview, only after all
* values have been set.
*/
test(assert(preview_generation_test.TestNames.CustomMargins), function() {
return initialize()
.then(function(args) {
const originalTicket: PreviewTicket = JSON.parse(args.printTicket);
assertEquals(MarginsType.DEFAULT, originalTicket.marginsType);
// Custom margins should not be set in the ticket.
assertEquals(undefined, originalTicket.marginsCustom);
assertEquals(0, originalTicket.requestID);
// This should do nothing.
page.setSetting('margins', MarginsType.CUSTOM);
// Sets only 1 side, not valid.
page.setSetting('customMargins', {marginTop: 25});
// 2 sides, still not valid.
page.setSetting('customMargins', {marginTop: 25, marginRight: 40});
// This should trigger a preview.
nativeLayer.resetResolver('getPreview');
page.setSetting('customMargins', {
marginTop: 25,
marginRight: 40,
marginBottom: 20,
marginLeft: 50
});
return nativeLayer.whenCalled('getPreview');
})
.then(function(args) {
const ticket: PreviewTicket = JSON.parse(args.printTicket);
assertEquals(MarginsType.CUSTOM, ticket.marginsType);
assertEquals(25, ticket.marginsCustom!.marginTop);
assertEquals(40, ticket.marginsCustom!.marginRight);
assertEquals(20, ticket.marginsCustom!.marginBottom);
assertEquals(50, ticket.marginsCustom!.marginLeft);
assertEquals(1, ticket.requestID);
page.setSetting('margins', MarginsType.DEFAULT);
// Set setting to something invalid and then set margins to CUSTOM.
page.setSetting('customMargins', {marginTop: 25, marginRight: 40});
page.setSetting('margins', MarginsType.CUSTOM);
nativeLayer.resetResolver('getPreview');
page.setSetting('customMargins', {
marginTop: 25,
marginRight: 40,
marginBottom: 20,
marginLeft: 50
});
return nativeLayer.whenCalled('getPreview');
})
.then(function(args) {
const ticket: PreviewTicket = JSON.parse(args.printTicket);
assertEquals(MarginsType.CUSTOM, ticket.marginsType);
assertEquals(25, ticket.marginsCustom!.marginTop);
assertEquals(40, ticket.marginsCustom!.marginRight);
assertEquals(20, ticket.marginsCustom!.marginBottom);
assertEquals(50, ticket.marginsCustom!.marginLeft);
// Request 3. Changing to default margins should have triggered a
// preview, and the final setting of valid custom margins should
// have triggered another one.
assertEquals(3, ticket.requestID);
});
});
/**
* Validate changing the pages per sheet updates the preview, and resets
* margins to MarginsType.DEFAULT.
*/
test(
assert(preview_generation_test.TestNames.ChangeMarginsByPagesPerSheet),
function() {
return initialize()
.then(function(args) {
const originalTicket: PreviewTicket =
JSON.parse(args.printTicket);
assertEquals(0, originalTicket.requestID);
assertEquals(MarginsType.DEFAULT, originalTicket['marginsType']);
assertEquals(
MarginsType.DEFAULT, page.getSettingValue('margins'));
assertEquals(1, page.getSettingValue('pagesPerSheet'));
assertEquals(1, originalTicket['pagesPerSheet']);
nativeLayer.resetResolver('getPreview');
page.setSetting('margins', MarginsType.MINIMUM);
return nativeLayer.whenCalled('getPreview');
})
.then(function(args) {
assertEquals(
MarginsType.MINIMUM, page.getSettingValue('margins'));
const ticket: PreviewTicket = JSON.parse(args.printTicket);
assertEquals(MarginsType.MINIMUM, ticket['marginsType']);
nativeLayer.resetResolver('getPreview');
assertEquals(1, ticket.requestID);
page.setSetting('pagesPerSheet', 4);
return nativeLayer.whenCalled('getPreview');
})
.then(function(args) {
assertEquals(
MarginsType.DEFAULT, page.getSettingValue('margins'));
assertEquals(4, page.getSettingValue('pagesPerSheet'));
const ticket: PreviewTicket = JSON.parse(args.printTicket);
assertEquals(MarginsType.DEFAULT, ticket['marginsType']);
assertEquals(4, ticket['pagesPerSheet']);
assertEquals(2, ticket.requestID);
});
});
/** Validate changing the paper size updates the preview. */
test(assert(preview_generation_test.TestNames.MediaSize), function() {
const mediaSizeCapability =
getCddTemplate('FooDevice').capabilities!.printer!.media_size!;
const letterOption = mediaSizeCapability.option[0]!;
const squareOption = mediaSizeCapability.option[1]!;
return initialize()
.then(function(args) {
const originalTicket: PreviewTicket = JSON.parse(args.printTicket);
assertEquals(
letterOption.width_microns,
originalTicket.mediaSize.width_microns);
assertEquals(
letterOption.height_microns,
originalTicket.mediaSize.height_microns);
assertEquals(0, originalTicket.requestID);
nativeLayer.resetResolver('getPreview');
const mediaSizeSetting = page.getSettingValue('mediaSize');
assertEquals(
letterOption.width_microns, mediaSizeSetting.width_microns);
assertEquals(
letterOption.height_microns, mediaSizeSetting.height_microns);
page.setSetting('mediaSize', squareOption);
return nativeLayer.whenCalled('getPreview');
})
.then(function(args) {
const mediaSizeSettingUpdated = page.getSettingValue('mediaSize');
assertEquals(
squareOption.width_microns,
mediaSizeSettingUpdated.width_microns);
assertEquals(
squareOption.height_microns,
mediaSizeSettingUpdated.height_microns);
const ticket: PreviewTicket = JSON.parse(args.printTicket);
assertEquals(
squareOption.width_microns, ticket.mediaSize.width_microns);
assertEquals(
squareOption.height_microns, ticket.mediaSize.height_microns);
nativeLayer.resetResolver('getPreview');
assertEquals(1, ticket.requestID);
});
});
/** Validate changing the page range updates the preview. */
test(assert(preview_generation_test.TestNames.PageRange), function() {
return initialize()
.then(function(args) {
const originalTicket: PreviewTicket = JSON.parse(args.printTicket);
// Ranges is empty for full document.
assertEquals(0, page.getSettingValue('ranges').length);
assertEquals(0, originalTicket.pageRange.length);
nativeLayer.resetResolver('getPreview');
page.setSetting('ranges', [{from: 1, to: 2}]);
return nativeLayer.whenCalled('getPreview');
})
.then(function(args) {
const setting = page.getSettingValue('ranges') as Range[];
assertEquals(1, setting.length);
assertEquals(1, setting[0]!.from);
assertEquals(2, setting[0]!.to);
const ticket: PreviewTicket = JSON.parse(args.printTicket);
assertEquals(1, ticket.pageRange.length);
assertEquals(1, ticket.pageRange[0]!.from);
assertEquals(2, ticket.pageRange[0]!.to);
});
});
/** Validate changing the selection only setting updates the preview. */
test(assert(preview_generation_test.TestNames.SelectionOnly), function() {
// Set has selection to true so that the setting is available.
initialSettings.documentHasSelection = true;
return testSimpleSetting(
'selectionOnly', false, true, 'shouldPrintSelectionOnly', false, true);
});
/** Validate changing the pages per sheet updates the preview. */
test(assert(preview_generation_test.TestNames.PagesPerSheet), function() {
return testSimpleSetting('pagesPerSheet', 1, 2, 'pagesPerSheet', 1, 2);
});
/** Validate changing the scaling updates the preview. */
test(assert(preview_generation_test.TestNames.Scaling), function() {
return initialize()
.then(function(args) {
validateScalingChange({
printTicket: args.printTicket,
scalingTypeKey: 'scalingType',
expectedTicketId: 0,
expectedTicketScaleFactor: 100,
expectedScalingValue: '100',
expectedScalingType: ScalingType.DEFAULT,
});
nativeLayer.resetResolver('getPreview');
// DEFAULT -> CUSTOM
page.setSetting('scalingType', ScalingType.CUSTOM);
// Need to set custom value !== '100' for preview to regenerate.
page.setSetting('scaling', '90');
return nativeLayer.whenCalled('getPreview');
})
.then(function(args) {
validateScalingChange({
printTicket: args.printTicket,
scalingTypeKey: 'scalingType',
expectedTicketId: 1,
expectedTicketScaleFactor: 90,
expectedScalingValue: '90',
expectedScalingType: ScalingType.CUSTOM,
});
nativeLayer.resetResolver('getPreview');
// CUSTOM -> DEFAULT
// This should regenerate the preview, since the custom value is not
// 100.
page.setSetting('scalingType', ScalingType.DEFAULT);
return nativeLayer.whenCalled('getPreview');
})
.then(function(args) {
validateScalingChange({
printTicket: args.printTicket,
scalingTypeKey: 'scalingType',
expectedTicketId: 2,
expectedTicketScaleFactor: 100,
expectedScalingValue: '90',
expectedScalingType: ScalingType.DEFAULT,
});
nativeLayer.resetResolver('getPreview');
// DEFAULT -> CUSTOM
page.setSetting('scalingType', ScalingType.CUSTOM);
return nativeLayer.whenCalled('getPreview');
})
.then(function(args) {
validateScalingChange({
printTicket: args.printTicket,
scalingTypeKey: 'scalingType',
expectedTicketId: 3,
expectedTicketScaleFactor: 90,
expectedScalingValue: '90',
expectedScalingType: ScalingType.CUSTOM,
});
nativeLayer.resetResolver('getPreview');
// CUSTOM 90 -> CUSTOM 80
// When custom scaling is set, changing scaling updates preview.
page.setSetting('scaling', '80');
return nativeLayer.whenCalled('getPreview');
})
.then(function(args) {
validateScalingChange({
printTicket: args.printTicket,
scalingTypeKey: 'scalingType',
expectedTicketId: 4,
expectedTicketScaleFactor: 80,
expectedScalingValue: '80',
expectedScalingType: ScalingType.CUSTOM,
});
});
});
/** Validate changing the scalingTypePdf setting updates the preview. */
test(assert(preview_generation_test.TestNames.ScalingPdf), function() {
// Set PDF document so setting is available.
initialSettings.previewModifiable = false;
return initialize()
.then(function(args) {
validateScalingChange({
printTicket: args.printTicket,
scalingTypeKey: 'scalingTypePdf',
expectedTicketId: 0,
expectedTicketScaleFactor: 100,
expectedScalingValue: '100',
expectedScalingType: ScalingType.DEFAULT,
});
nativeLayer.resetResolver('getPreview');
// DEFAULT -> FIT_TO_PAGE
page.setSetting('scalingTypePdf', ScalingType.FIT_TO_PAGE);
return nativeLayer.whenCalled('getPreview');
})
.then(function(args) {
validateScalingChange({
printTicket: args.printTicket,
scalingTypeKey: 'scalingTypePdf',
expectedTicketId: 1,
expectedTicketScaleFactor: 100,
expectedScalingValue: '100',
expectedScalingType: ScalingType.FIT_TO_PAGE,
});
nativeLayer.resetResolver('getPreview');
// FIT_TO_PAGE -> CUSTOM
page.setSetting('scalingTypePdf', ScalingType.CUSTOM);
return nativeLayer.whenCalled('getPreview');
})
.then(function(args) {
validateScalingChange({
printTicket: args.printTicket,
scalingTypeKey: 'scalingTypePdf',
expectedTicketId: 2,
expectedTicketScaleFactor: 100,
expectedScalingValue: '100',
expectedScalingType: ScalingType.CUSTOM,
});
nativeLayer.resetResolver('getPreview');
// CUSTOM -> FIT_TO_PAGE
page.setSetting('scalingTypePdf', ScalingType.FIT_TO_PAGE);
return nativeLayer.whenCalled('getPreview');
})
.then(function(args) {
validateScalingChange({
printTicket: args.printTicket,
scalingTypeKey: 'scalingTypePdf',
expectedTicketId: 3,
expectedTicketScaleFactor: 100,
expectedScalingValue: '100',
expectedScalingType: ScalingType.FIT_TO_PAGE,
});
nativeLayer.resetResolver('getPreview');
// FIT_TO_PAGE -> DEFAULT
page.setSetting('scalingTypePdf', ScalingType.DEFAULT);
return nativeLayer.whenCalled('getPreview');
})
.then(function(args) {
validateScalingChange({
printTicket: args.printTicket,
scalingTypeKey: 'scalingTypePdf',
expectedTicketId: 4,
expectedTicketScaleFactor: 100,
expectedScalingValue: '100',
expectedScalingType: ScalingType.DEFAULT,
});
nativeLayer.resetResolver('getPreview');
// DEFAULT -> FIT_TO_PAPER
page.setSetting('scalingTypePdf', ScalingType.FIT_TO_PAPER);
return nativeLayer.whenCalled('getPreview');
})
.then(function(args) {
validateScalingChange({
printTicket: args.printTicket,
scalingTypeKey: 'scalingTypePdf',
expectedTicketId: 5,
expectedTicketScaleFactor: 100,
expectedScalingValue: '100',
expectedScalingType: ScalingType.FIT_TO_PAPER,
});
nativeLayer.resetResolver('getPreview');
// FIT_TO_PAPER -> DEFAULT
page.setSetting('scalingTypePdf', ScalingType.DEFAULT);
return nativeLayer.whenCalled('getPreview');
})
.then(function(args) {
validateScalingChange({
printTicket: args.printTicket,
scalingTypeKey: 'scalingTypePdf',
expectedTicketId: 6,
expectedTicketScaleFactor: 100,
expectedScalingValue: '100',
expectedScalingType: ScalingType.DEFAULT,
});
nativeLayer.resetResolver('getPreview');
// DEFAULT -> CUSTOM
page.setSetting('scalingTypePdf', ScalingType.CUSTOM);
// Need to set custom value !== '100' for preview to regenerate.
page.setSetting('scaling', '120');
return nativeLayer.whenCalled('getPreview');
})
.then(function(args) {
// DEFAULT -> CUSTOM will result in a scaling change only if the
// scale factor changes. Therefore, the requestId should only be one
// more than the last set of scaling changes.
validateScalingChange({
printTicket: args.printTicket,
scalingTypeKey: 'scalingTypePdf',
expectedTicketId: 7,
expectedTicketScaleFactor: 120,
expectedScalingValue: '120',
expectedScalingType: ScalingType.CUSTOM,
});
nativeLayer.resetResolver('getPreview');
// CUSTOM -> DEFAULT
page.setSetting('scalingTypePdf', ScalingType.DEFAULT);
return nativeLayer.whenCalled('getPreview');
})
.then(function(args) {
validateScalingChange({
printTicket: args.printTicket,
scalingTypeKey: 'scalingTypePdf',
expectedTicketId: 8,
expectedTicketScaleFactor: 100,
expectedScalingValue: '120',
expectedScalingType: ScalingType.DEFAULT,
});
});
});
/**
* Validate changing the rasterize setting updates the preview. Setting is
* always available on Linux and CrOS. Availability on Windows and macOS
* depends upon policy (see policy_test.js).
*/
test(assert(preview_generation_test.TestNames.Rasterize), function() {
// Set PDF document so setting is available.
initialSettings.previewModifiable = false;
return testSimpleSetting(
'rasterize', false, true, 'rasterizePDF', false, true);
});
/**
* Validate changing the destination updates the preview, if it results
* in a settings change.
*/
test(assert(preview_generation_test.TestNames.Destination), function() {
let destinationSettings: PrintPreviewDestinationSettingsElement;
return initialize()
.then(function(args) {
const originalTicket: PreviewTicket = JSON.parse(args.printTicket);
destinationSettings =
page.shadowRoot!.querySelector('print-preview-sidebar')!
.shadowRoot!.querySelector(
'print-preview-destination-settings')!;
assertEquals('FooDevice', destinationSettings.destination!.id);
assertEquals('FooDevice', originalTicket.deviceName);
const barDestination = new Destination(
'BarDevice', DestinationType.LOCAL, DestinationOrigin.LOCAL,
'BarName', DestinationConnectionStatus.ONLINE);
const capabilities = getCddTemplate(barDestination.id).capabilities!;
capabilities.printer!.media_size = {
option: [
{
name: 'ISO_A4',
width_microns: 210000,
height_microns: 297000,
custom_display_name: 'A4',
},
],
};
barDestination.capabilities = capabilities;
nativeLayer.resetResolver('getPreview');
destinationSettings.destinationState = DestinationState.SELECTED;
destinationSettings.set('destination', barDestination);
destinationSettings.destinationState = DestinationState.UPDATED;
return nativeLayer.whenCalled('getPreview');
})
.then(function(args) {
assertEquals('BarDevice', destinationSettings.destination.id);
const ticket: PreviewTicket = JSON.parse(args.printTicket);
assertEquals('BarDevice', ticket.deviceName);
});
});
/**
* Validate that if the document layout has 0 default margins, the
* header/footer setting is set to false.
*/
test(
assert(preview_generation_test.TestNames
.ZeroDefaultMarginsClearsHeaderFooter),
async () => {
/**
* @param ticket The parsed print ticket
* @param expectedId The expected ticket request ID
* @param expectedMargins The expected ticket margins type
* @param expectedHeaderFooter The expected ticket
* header/footer value
*/
function assertMarginsFooter(
ticket: PreviewTicket, expectedId: number,
expectedMargins: MarginsType, expectedHeaderFooter: boolean) {
assertEquals(expectedId, ticket.requestID);
assertEquals(expectedMargins, ticket.marginsType);
assertEquals(expectedHeaderFooter, ticket.headerFooterEnabled);
}
nativeLayer.setPageLayoutInfo({
marginTop: 0,
marginLeft: 0,
marginBottom: 0,
marginRight: 0,
contentWidth: 612,
contentHeight: 792,
printableAreaX: 0,
printableAreaY: 0,
printableAreaWidth: 612,
printableAreaHeight: 792,
});
let previewArgs = await initialize();
let ticket: PreviewTicket = JSON.parse(previewArgs.printTicket);
// The ticket recorded here is the original, which requests default
// margins with headers and footers (Print Preview defaults).
assertMarginsFooter(ticket, 0, MarginsType.DEFAULT, true);
// After getting the new layout, a second request should have been
// sent.
assertEquals(2, nativeLayer.getCallCount('getPreview'));
assertEquals(MarginsType.DEFAULT, page.getSettingValue('margins'));
assertFalse(page.getSettingValue('headerFooter'));
// Check the last ticket sent by the preview area. It should not
// have the same settings as the original (headers and footers
// should have been turned off).
const previewArea =
page.shadowRoot!.querySelector('print-preview-preview-area')!;
assertMarginsFooter(
previewArea.getLastTicketForTest()!, 1, MarginsType.DEFAULT, false);
nativeLayer.resetResolver('getPreview');
page.setSetting('margins', MarginsType.MINIMUM);
previewArgs = await nativeLayer.whenCalled('getPreview');
// Setting minimum margins allows space for the headers and footers,
// so they should be enabled again.
ticket = JSON.parse(previewArgs.printTicket);
assertMarginsFooter(ticket, 2, MarginsType.MINIMUM, true);
assertEquals(
MarginsType.MINIMUM,
page.getSettingValue('margins') as MarginsType);
assertTrue(page.getSettingValue('headerFooter') as boolean);
nativeLayer.resetResolver('getPreview');
page.setSetting('margins', MarginsType.DEFAULT);
previewArgs = await nativeLayer.whenCalled('getPreview');
// With default margins, there is no space for headers/footers, so
// they are removed.
ticket = JSON.parse(previewArgs.printTicket);
assertMarginsFooter(ticket, 3, MarginsType.DEFAULT, false);
assertEquals(MarginsType.DEFAULT, page.getSettingValue('margins'));
assertEquals(false, page.getSettingValue('headerFooter'));
});
}); | the_stack |
import { AuthSdkError, OktaAuth, TokenResponse, Tokens } from '@okta/okta-auth-js';
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
import getOktaSignIn from './getOktaSignIn';
import ConfigArea, { ConfigTemplate } from './configArea';
import {
getBaseUrl,
getConfigFromStorage
} from './config';
import { Config, OktaSignIn, RenderResponse } from './types';
const ActionsTemplate = `
<div id="actions-container" class="pure-menu">
<ul class="pure-menu-list">
<li class="pure-menu-item">
<button name="showSignIn" class="pure-menu-link">
showSignIn
</button>
</li>
<li class="pure-menu-item">
<button name="showSignInAndRedirect" class="pure-menu-link">
showSignInAndRedirect
</button>
</li>
<li class="pure-menu-item">
<button name="showSignInToGetTokens" class="pure-menu-link">
showSignInToGetTokens
</button>
</li>
<li class="pure-menu-item">
<button name="renderEl" class="pure-menu-link">
renderEl
</button>
</li>
<li class="pure-menu-item">
<button name="start" class="pure-menu-link">Start</button>
</li>
<li class="pure-menu-item">
<button name="hide" class="pure-menu-link">Hide</button>
</li>
<li class="pure-menu-item">
<button name="show" class="pure-menu-link">Show</button>
</li>
<li class="pure-menu-item">
<button name="remove" class="pure-menu-link">Remove</button>
</li>
<li class="pure-menu-item">
<button name="fail-csp" class="pure-menu-link">
Trigger CSP Fail
</button>
</li>
<li class="pure-menu-item visible-on-callback">
<button name="clearTransaction" class="pure-menu-link">clear transaction storage</button>
</li>
<li class="pure-menu-item visible-on-callback">
<button name="signOut" class="pure-menu-link">signOut</button>
</li>
</ul>
</div>
`;
const TokensTemplate = `
<pre id="tokens-container"></pre>
`;
const CodeTemplate = `
<div id="code-container"></div>
`;
const ErrorsTemplate = `
<div id="errors-container"></div>
`;
const CSPErrorsTemplate = `
<div id="csp-errors-container"></div>
`;
const OIDCErrorTemplate = `
<div id="oidc-error-container"></div>
`;
const CallbackTemplate = `
<div id="callback-container">
<div class="header">
<strong>OAuth Callback Page</strong>
<div id="callback-controls">
<a href="/">Return Home</a>
</div>
</div>
</div>
`;
const LayoutTemplate = `
<div id="layout">
<div class="flex-row">
${ActionsTemplate}
<div id="main-column">
<div id="okta-login-container">
<!-- widget renders here -->
</div>
${CallbackTemplate}
${TokensTemplate}
${CodeTemplate}
${ErrorsTemplate}
${CSPErrorsTemplate}
${OIDCErrorTemplate}
</div>
<div class="right-column">
${ConfigTemplate}
</div>
</div>
</div>
`;
export default class TestApp {
authClient: OktaAuth;
oktaSignIn: OktaSignIn;
errors: Error[];
cspErrors: SecurityPolicyViolationEvent[] = [];
// config
configArea: ConfigArea;
configEditor: HTMLElement;
configPreview: HTMLElement;
// action buttons
startButton: HTMLElement;
hideButton: HTMLElement;
showButton: HTMLElement;
removeButton: HTMLElement;
showSignInButton: HTMLElement;
showSignInAndRedirectButton: HTMLElement;
showSignInToGetTokensButton: HTMLElement;
renderElButton: HTMLElement;
failCspButton: HTMLElement;
signOutButton: HTMLElement;
clearTransaction: HTMLElement;
// containers
configContainer: HTMLElement;
callbackContainer: HTMLElement;
codeContainer: HTMLElement;
tokensContainer: HTMLElement;
errorsContainer: HTMLElement;
cspErrorsContainer: HTMLElement;
oidcErrorContainer: HTMLElement;
bootstrap(rootElem: Element): void {
rootElem.innerHTML = LayoutTemplate;
// set elements
this.callbackContainer = document.getElementById('callback-container');
this.configContainer = document.getElementById('config-container');
this.configEditor = document.getElementById('config-editor');
this.configPreview = document.getElementById('config-preview');
this.startButton = document.querySelector('#actions-container button[name="start"]');
this.hideButton = document.querySelector('#actions-container button[name="hide"]');
this.showButton = document.querySelector('#actions-container button[name="show"]');
this.removeButton = document.querySelector('#actions-container button[name="remove"]');
this.showSignInButton = document.querySelector('#actions-container button[name="showSignIn"]');
this.showSignInAndRedirectButton = document.querySelector('#actions-container button[name="showSignInAndRedirect"]');
this.showSignInToGetTokensButton = document.querySelector('#actions-container button[name="showSignInToGetTokens"]');
this.renderElButton = document.querySelector('#actions-container button[name="renderEl"]')
this.failCspButton = document.querySelector('#actions-container button[name="fail-csp"]');
this.clearTransaction = document.querySelector('#actions-container button[name="clearTransaction"]');
this.signOutButton = document.querySelector('#actions-container button[name="signOut"]');
this.tokensContainer = document.getElementById('tokens-container');
this.codeContainer = document.getElementById('code-container');
this.errorsContainer = document.getElementById('errors-container');
this.cspErrorsContainer = document.getElementById('csp-errors-container');
this.oidcErrorContainer = document.getElementById('oidc-error-container');
this.callbackContainer.style.display = 'none';
this.addEventListeners();
if (window.location.pathname === '/done') {
return this.handleLoginCallback();
}
this.configArea = new ConfigArea();
this.configArea.bootstrap();
}
renderError(err?: Error): void {
if (err) {
console.error(err);
this.errors.push(err);
}
this.errors.forEach(err => {
const errorEl = document.createElement('div');
const message = err.message || err.toString();
errorEl.innerHTML = `${message}`;
this.errorsContainer.appendChild(errorEl);
});
}
addEventListeners(): void {
// csp listener
document.addEventListener('securitypolicyviolation', (err) => {
this.cspErrors = [...this.cspErrors, err];
this.cspErrors.forEach(err => {
const errorEl = document.createElement('div');
errorEl.innerHTML = `${err.blockedURI} blocked due to CSP rule ${err.violatedDirective} from ${err.originalPolicy}`;
this.cspErrorsContainer.appendChild(errorEl);
});
});
// actions
this.startButton.addEventListener('click', async () => {
const config = this.getConfig();
this.oktaSignIn = await getOktaSignIn(config);
this.oktaSignIn.renderEl({
el: '#okta-login-container'
}, (res: RenderResponse) => {
if (res.status === 'SUCCESS' && res.session) {
const baseUrl = getBaseUrl(config);
res.session.setCookieAndRedirect(baseUrl + '/app/UserHome');
}
if (res.tokens) {
this.setTokens(res.tokens);
this.oktaSignIn.remove();
}
});
});
this.hideButton.addEventListener('click', () => {
this.oktaSignIn.hide();
});
this.showButton.addEventListener('click', () => {
this.oktaSignIn.show();
});
this.removeButton.addEventListener('click', () => {
this.oktaSignIn.remove();
this.oktaSignIn = null;
});
this.showSignInButton.addEventListener('click', async () => {
const config = this.getConfig();
this.oktaSignIn = await getOktaSignIn(config);
this.oktaSignIn.showSignIn({ el: '#okta-login-container' }).then((res: TokenResponse) => {
if (res.tokens) {
this.setTokens(res.tokens);
this.oktaSignIn.remove();
}
});
});
this.showSignInAndRedirectButton.addEventListener('click', async () => {
const config = this.getConfig();
this.oktaSignIn = await getOktaSignIn(config);
this.oktaSignIn.showSignInAndRedirect({ el: '#okta-login-container' });
});
this.showSignInToGetTokensButton.addEventListener('click', async () => {
const config = this.getConfig();
this.oktaSignIn = await getOktaSignIn(config);
this.oktaSignIn.showSignInToGetTokens({ el: '#okta-login-container' }).then((tokens: Tokens) => {
this.setTokens(tokens);
this.oktaSignIn.remove();
});
});
this.renderElButton.addEventListener('click', async () => {
const config = this.getConfig();
this.oktaSignIn = await getOktaSignIn(config);
this.oktaSignIn.renderEl(
{ el: '#okta-login-container' },
(res: RenderResponse) => {
if (res.status !== 'SUCCESS') {
return;
}
this.setTokens(res.tokens);
this.oktaSignIn.remove();
},
(err: AuthSdkError) => {
this.setOidcError(err);
}
);
this.oktaSignIn.on('afterError', (context: never, error: Error) => {
console.log(context, error);
});
});
this.failCspButton.addEventListener('click', () => {
try {
/* eslint-disable-next-line no-eval */
eval('var cspTrigger = true;');
} catch (e) {
console.warn(e);
}
});
this.clearTransaction.addEventListener('click', async () => {
if (!this.oktaSignIn) {
const config = this.getConfig();
this.oktaSignIn = await getOktaSignIn(config);
}
this.oktaSignIn.authClient.transactionManager.clear();
});
this.signOutButton.addEventListener('click', async () => {
if (!this.oktaSignIn) {
const config = this.getConfig();
this.oktaSignIn = await getOktaSignIn(config);
}
this.oktaSignIn.authClient.signOut();
});
}
getConfig(): Config {
let config;
try {
config = JSON.parse(this.configPreview.innerHTML);
} catch (err) {
throw new Error('Config need to be set in config editor before rendering the widget');
}
return config;
}
setTokens(tokens: Tokens): void {
this.tokensContainer.innerHTML = JSON.stringify(tokens, null, 2);
}
setCode(code: string): void {
this.codeContainer.innerHTML = code;
}
setOidcError(err: AuthSdkError): void {
this.oidcErrorContainer.innerHTML = JSON.stringify(err);
}
handleLoginCallback(): void {
this.callbackContainer.style.display = 'block';
this.configContainer.style.display = 'none';
document.querySelectorAll('#actions-container .pure-menu-item:not(.visible-on-callback').forEach(el => {
(el as HTMLElement).style.display = 'none';
});
// add responseMode to config
let responseMode;
if (window.location.search.indexOf('code') >= 0) {
responseMode = 'query';
} else if (window.location.hash.indexOf('code') >= 0) {
responseMode = 'fragment';
}
const config = getConfigFromStorage();
config.authParams = config.authParams || {};
config.authParams.responseMode = responseMode;
// get authClient
const oktaSign = getOktaSignIn(config);
const authClient = oktaSign.authClient;
// handle redirect
if (authClient.token.isLoginRedirect()) {
let promise;
if (/(interaction_code=)/i.test(window.location.search)) {
promise = authClient.idx.handleInteractionCodeRedirect(window.location.href)
.then(() => {
const tokens = authClient.tokenManager.getTokensSync();
this.setTokens(tokens);
})
} else {
promise = authClient.token.parseFromUrl()
.then((res: TokenResponse) => {
this.setTokens(res.tokens);
this.setCode(res.code);
});
}
promise
.catch(function(err: Error) {
this.renderError(err);
});
}
}
} | the_stack |
import {CurrentWallpaper, WallpaperLayout, WallpaperType} from 'chrome://personalization/trusted/personalization_app.mojom-webui.js';
import {DisplayableImage} from 'chrome://personalization/trusted/personalization_reducers.js';
import {WallpaperFullscreen} from 'chrome://personalization/trusted/wallpaper/wallpaper_fullscreen_element.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js';
import {flushTasks, waitAfterNextRender} from 'chrome://webui-test/test_util.js';
import {baseSetup, initElement} from './personalization_app_test_utils.js';
import {TestPersonalizationStore} from './test_personalization_store.js';
import {TestWallpaperProvider} from './test_wallpaper_interface_provider.js';
export function WallpaperFullscreenTest() {
let wallpaperFullscreenElement: WallpaperFullscreen|null = null;
let wallpaperProvider: TestWallpaperProvider;
let personalizationStore: TestPersonalizationStore;
const currentSelectedCustomImage: CurrentWallpaper = {
attribution: ['Custom image'],
layout: WallpaperLayout.kCenter,
key: 'testing',
type: WallpaperType.kCustomized,
url: {url: 'data://testing'},
};
const pendingSelectedCustomImage:
DisplayableImage = {path: '/local/image/path.jpg'};
setup(() => {
const mocks = baseSetup();
wallpaperProvider = mocks.wallpaperProvider;
wallpaperProvider.isInTabletModeResponse = true;
personalizationStore = mocks.personalizationStore;
loadTimeData.overrideValues({fullScreenPreviewEnabled: true});
});
teardown(async () => {
if (wallpaperFullscreenElement) {
wallpaperFullscreenElement.remove();
}
wallpaperFullscreenElement = null;
await flushTasks();
});
function mockFullscreenApis() {
const container =
wallpaperFullscreenElement!.shadowRoot!.getElementById('container');
let fullscreenElement: HTMLElement|null = null;
const requestFullscreenPromise = new Promise<void>((resolve) => {
container!.requestFullscreen = () => {
fullscreenElement = container;
container!.dispatchEvent(new Event('fullscreenchange'));
resolve();
return requestFullscreenPromise;
};
});
wallpaperFullscreenElement!.getFullscreenElement = () => fullscreenElement;
const exitFullscreenPromise = new Promise<void>((resolve) => {
wallpaperFullscreenElement!.exitFullscreen = () => {
assertTrue(!!fullscreenElement);
fullscreenElement = null;
container!.dispatchEvent(new Event('fullscreenchange'));
resolve();
return exitFullscreenPromise;
};
});
return {requestFullscreenPromise, exitFullscreenPromise};
}
test('toggles element visibility on full screen change', async () => {
wallpaperFullscreenElement = initElement(WallpaperFullscreen);
const {requestFullscreenPromise, exitFullscreenPromise} =
mockFullscreenApis();
await waitAfterNextRender(wallpaperFullscreenElement);
const container =
wallpaperFullscreenElement.shadowRoot!.getElementById('container');
assertTrue(container!.hidden);
personalizationStore.data.wallpaper.fullscreen = true;
personalizationStore.data.wallpaper.currentSelected =
currentSelectedCustomImage;
personalizationStore.notifyObservers();
await requestFullscreenPromise;
assertFalse(container!.hidden);
personalizationStore.data.wallpaper.fullscreen = false;
personalizationStore.notifyObservers();
await exitFullscreenPromise;
assertTrue(container!.hidden);
});
test('sets default layout option on when entering preview', async () => {
wallpaperFullscreenElement = initElement(WallpaperFullscreen);
const {requestFullscreenPromise, exitFullscreenPromise} =
mockFullscreenApis();
await waitAfterNextRender(wallpaperFullscreenElement);
assertEquals(null, wallpaperFullscreenElement['selectedLayout_']);
personalizationStore.data.wallpaper.fullscreen = true;
personalizationStore.data.wallpaper.currentSelected =
currentSelectedCustomImage;
personalizationStore.notifyObservers();
await requestFullscreenPromise;
assertEquals(
WallpaperLayout.kCenterCropped,
wallpaperFullscreenElement['selectedLayout_']);
personalizationStore.data.wallpaper.fullscreen = false;
personalizationStore.notifyObservers();
await exitFullscreenPromise;
assertEquals(null, wallpaperFullscreenElement['selectedLayout_']);
});
test('sets fullscreen class on body when entering fullscreen', async () => {
wallpaperFullscreenElement = initElement(WallpaperFullscreen);
const {requestFullscreenPromise, exitFullscreenPromise} =
mockFullscreenApis();
await waitAfterNextRender(wallpaperFullscreenElement);
assertEquals('', document.body.className);
personalizationStore.data.wallpaper.fullscreen = true;
personalizationStore.data.wallpaper.currentSelected =
currentSelectedCustomImage;
personalizationStore.notifyObservers();
await requestFullscreenPromise;
assertEquals('fullscreen-preview', document.body.className);
wallpaperFullscreenElement.exitFullscreen();
await exitFullscreenPromise;
assertEquals('', document.body.className);
});
test('exits full screen on exit button click', async () => {
wallpaperFullscreenElement = initElement(WallpaperFullscreen);
const {requestFullscreenPromise, exitFullscreenPromise} =
mockFullscreenApis();
await waitAfterNextRender(wallpaperFullscreenElement);
personalizationStore.data.wallpaper.fullscreen = true;
personalizationStore.data.wallpaper.currentSelected =
currentSelectedCustomImage;
personalizationStore.notifyObservers();
await requestFullscreenPromise;
const exitButton =
wallpaperFullscreenElement.shadowRoot!.getElementById('exit');
exitButton!.click();
await exitFullscreenPromise;
});
test('shows layout options for custom images', async () => {
wallpaperFullscreenElement = initElement(WallpaperFullscreen);
await waitAfterNextRender(wallpaperFullscreenElement);
assertEquals(
null,
wallpaperFullscreenElement.shadowRoot!.getElementById('layoutButtons'));
personalizationStore.data.wallpaper.pendingSelected =
pendingSelectedCustomImage;
personalizationStore.notifyObservers();
await waitAfterNextRender(wallpaperFullscreenElement);
assertTrue(!!wallpaperFullscreenElement.shadowRoot!.getElementById(
'layoutButtons'));
});
test('clicking layout option selects image with new layout', async () => {
wallpaperFullscreenElement = initElement(WallpaperFullscreen);
const {requestFullscreenPromise} = mockFullscreenApis();
await waitAfterNextRender(wallpaperFullscreenElement);
personalizationStore.data.wallpaper.currentSelected =
currentSelectedCustomImage;
personalizationStore.data.wallpaper.pendingSelected =
pendingSelectedCustomImage;
personalizationStore.data.wallpaper.fullscreen = true;
personalizationStore.notifyObservers();
await requestFullscreenPromise;
let button = wallpaperFullscreenElement.shadowRoot!.querySelector(
'cr-button[data-layout="FILL"]')! as HTMLButtonElement;
button.click();
const [fillImage, fillLayout, fillPreviewMode] =
await wallpaperProvider.whenCalled('selectLocalImage');
wallpaperProvider.reset();
assertEquals(pendingSelectedCustomImage, fillImage);
assertEquals(WallpaperLayout.kCenterCropped, fillLayout);
assertTrue(fillPreviewMode);
button = wallpaperFullscreenElement.shadowRoot!.querySelector(
'cr-button[data-layout="CENTER"]') as HTMLButtonElement;
button.click();
const [centerImage, centerLayout, centerPreviewMode] =
await wallpaperProvider.whenCalled('selectLocalImage');
assertEquals(pendingSelectedCustomImage, centerImage);
assertEquals(WallpaperLayout.kCenter, centerLayout);
assertTrue(centerPreviewMode);
});
test('aria pressed set for chosen layout option', async () => {
wallpaperFullscreenElement = initElement(WallpaperFullscreen);
const {requestFullscreenPromise} = mockFullscreenApis();
await waitAfterNextRender(wallpaperFullscreenElement);
personalizationStore.data.wallpaper.currentSelected =
currentSelectedCustomImage;
personalizationStore.data.wallpaper.pendingSelected =
pendingSelectedCustomImage;
personalizationStore.data.wallpaper.fullscreen = true;
personalizationStore.notifyObservers();
await requestFullscreenPromise;
// Current image is kCenter but initial state should reset to default.
assertEquals(
WallpaperLayout.kCenter,
personalizationStore.data.wallpaper.currentSelected.layout);
const center = wallpaperFullscreenElement.shadowRoot!.querySelector(
'cr-button[data-layout="CENTER"]');
const fill = wallpaperFullscreenElement.shadowRoot!.querySelector(
'cr-button[data-layout="FILL"]');
assertEquals('false', center!.getAttribute('aria-pressed'));
assertEquals('true', fill!.getAttribute('aria-pressed'));
wallpaperFullscreenElement['selectedLayout_'] = WallpaperLayout.kCenter;
await waitAfterNextRender(wallpaperFullscreenElement);
assertEquals('true', center!.getAttribute('aria-pressed'));
assertEquals('false', fill!.getAttribute('aria-pressed'));
});
test('clicking set as wallpaper confirms wallpaper', async () => {
wallpaperFullscreenElement = initElement(WallpaperFullscreen);
mockFullscreenApis();
await waitAfterNextRender(wallpaperFullscreenElement);
personalizationStore.data.wallpaper.fullscreen = true;
personalizationStore.data.wallpaper.currentSelected = {
...personalizationStore.data.wallpaper.currentSelected,
type: WallpaperType.kDaily,
};
personalizationStore.data.wallpaper.dailyRefresh.collectionId =
wallpaperProvider.collections![0]!.id;
personalizationStore.data.wallpaper.pendingSelected =
wallpaperProvider.images![1];
personalizationStore.notifyObservers();
await waitAfterNextRender(wallpaperFullscreenElement);
const setAsWallpaperButton =
wallpaperFullscreenElement.shadowRoot!.getElementById('confirm') as
HTMLButtonElement;
setAsWallpaperButton.click();
await wallpaperProvider.whenCalled('confirmPreviewWallpaper');
});
} | the_stack |
module Kiwi.Animations {
/**
* An Animation contains information about a single animation that is held on a AnimationManager.
* The information that is held is unique to this individual animation and will initially be the same as a Sequence,
* but if you do ever modify the information held in this Animation the corresponding Sequence will not be updated.
*
* @class Animation
* @namespace Kiwi.Animations
* @constructor
* @param name {string} The name of this anim.
* @param sequences {Kiwi.Animations.Sequences} The sequence that this anim will be using to animate.
* @param clock {Kiwi.Time.Clock} A game clock that this anim will be using to keep record of the time between frames. (Deprecated in v1.2.0, because there is no way to control it.)
* @param parent {Kiwi.Components.AnimationManager} The animation manager that this animation belongs to.
* @return {Kiwi.Animations.Animation}
*
*/
export class Animation {
constructor(name: string, sequence: Kiwi.Animations.Sequence, clock: Kiwi.Time.Clock, parent: Kiwi.Components.AnimationManager) {
this.name = name;
this._sequence = sequence;
this._speed = sequence.speed;
this._loop = sequence.loop;
this._parent = parent;
this._clock = clock;
this._lastFrameElapsed = this.clock.elapsed();
}
/**
* The type of object that this is.
* @method objType
* @return {String} "Animation"
* @public
*/
public objType(): string {
return "Animation";
}
/**
* The AnimationManager that this animation is a child of.
* @property _parent
* @type Kiwi.Components.AnimationManager
* @private
*/
private _parent: Kiwi.Components.AnimationManager;
/**
* The name of this animation.
* @property name
* @type string
* @public
*/
public name: string;
/**
* The sequence on the texture atlas that this animation is based off.
* @property _sequence
* @type Kiwi.Animations.Sequence
* @private
*/
private _sequence: Kiwi.Animations.Sequence;
/**
* If this animation should loop or not.
* @property _loop
* @type boolean
* @private
*/
private _loop: boolean;
/**
* If once the animation reaches the end, it should start again from the first cell in the sequence or not.
* @property loop
* @type boolean
* @public
*/
public get loop(): boolean {
return this._loop;
}
public set loop(value: boolean) {
this._loop = value;
}
/**
* The current frame index that the animation is currently upto.
* Note: A frame index is the index of a particular cell in the Sequence.
* @property _frameIndex
* @type number
* @private
*/
private _frameIndex: number = 0;
/**
* The current frame index that the animation is currently upto.
* Note: A frame index is the index of a particular cell in the Sequence.
*
* As of v1.3.0, this property will work properly with floating-point
* values. They will be rounded down and stored as integers.
* @property frameIndex
* @type number
* @public
*/
public get frameIndex(): number {
return this._frameIndex;
}
public set frameIndex(val: number) {
val = Math.floor( val );
if (this._validateFrame(val)) {
this._frameIndex = val;
}
}
/**
* Returns the current cell that the animation is up to. This is READ ONLY.
* @property currentCell
* @type number
* @public
*/
public get currentCell(): number {
return this._sequence.cells[ this.frameIndex ];
}
/**
* How fast the transition is between cells. Perhaps change to frames per second to reflect actual game speed?
* @property _speed
* @type number
* @private
*/
private _speed: number;
/**
* How long the each cell should stay on screen for. In seconds.
* @property speed
* @type number
* @public
*/
public get speed(): number {
return this._speed;
}
public set speed(value: number) {
this._speed = value;
}
/**
* The clock that is to be used to calculate the animations.
* @property _clock
* @type Kiwi.Time.Clock
* @private
*/
private _clock: Kiwi.Time.Clock;
/**
* Clock used by this Animation. If it was not set on creation,
* the Animation will use its parent's entity's clock.
* @property clock
* @type Kiwi.Time.Clock
* @public
* @since 1.2.0
*/
public get clock(): Kiwi.Time.Clock {
if ( this._clock ) {
return this._clock;
}
return this._parent.entity.clock;
}
/**
* The starting time of the animation from when it was played. Internal use only.
* @property _startTime
* @type number
* @private
*/
private _startTime: number = null;
/**
* Indicates whether the animation is playing in reverse or not.
* @property _reverse
* @type boolean
* @private
*/
private _reverse: boolean = false;
/**
* Whether the animation is to be played in reverse.
* @property reverse
* @type boolean
* @public
*/
public set reverse(value: boolean) {
this._reverse = value;
}
public get reverse(): boolean {
return this._reverse;
}
/**
* The time at which the animation should change to the next cell
* @property _tick
* @type number
* @private
* @deprecated Different private time management systems implemented in v1.2.0
*/
private _tick: number;
/**
* Whether the animation is currently playing or not.
* @property _isPlaying
* @type boolean
* @default false
* @private
*/
private _isPlaying: boolean = false;
/**
* Whether the animation is currently playing or not. Read-only.
* @property isPlaying
* @type boolean
* @public
*/
public get isPlaying(): boolean {
return this._isPlaying;
}
/**
* A Kiwi.Signal that dispatches an event when the animation has stopped playing.
* @property _onStop
* @type Signal
* @private
*/
private _onStop: Kiwi.Signal = null;
/**
* A Kiwi.Signal that dispatches an event when the animation has stopped playing.
* @property onStop
* @type Signal
* @public
*/
public get onStop(): Kiwi.Signal {
if (this._onStop == null) this._onStop = new Kiwi.Signal;
return this._onStop;
}
/**
* A Kiwi.Signal that dispatches an event when the animation has started playing.
* @property _onPlay
* @type Kiwi.Signal
* @private
*/
private _onPlay: Kiwi.Signal = null;
/**
* A Kiwi.Signal that dispatches an event when the animation has started playing.
* @property onPlay
* @type Kiwi.Signal
* @public
*/
public get onPlay(): Kiwi.Signal {
if (this._onPlay == null) this._onPlay = new Kiwi.Signal;
return this._onPlay;
}
/**
* A Kiwi.Signal that dispatches an event when the animation has updated/changed frameIndexs.
* @property _onUpdate
* @type Kiwi.Signal
* @private
*/
private _onUpdate: Kiwi.Signal = null;
/**
* A Kiwi.Signal that dispatches an event when the animation has updated/changed frameIndexs.
* @property onUpdate
* @type Kiwi.Signal
* @public
*/
public get onUpdate(): Kiwi.Signal {
if (this._onUpdate == null) this._onUpdate = new Kiwi.Signal;
return this._onUpdate;
}
/**
* A Kiwi.Signal that dispatches an event when the animation has come to the end of the animation and is going to play again.
* @property _onLoop
* @type Kiwi.Signal
* @private
*/
private _onLoop: Kiwi.Signal = null;
/**
* A Kiwi.Signal that dispatches an event when the animation has come to the end of the animation and is going to play again.
* @property onLoop
* @type Kiwi.Signal
* @public
*/
public get onLoop(): Kiwi.Signal {
if (this._onLoop == null) this._onLoop = new Kiwi.Signal;
return this._onLoop;
}
/**
* A Kiwi.Signal that dispatches an event when the animation has come to
* the end of the animation but is not going to play again.
* @property _onComplete
* @type Kiwi.Signal
* @private
* @since 1.2.0
*/
private _onComplete: Kiwi.Signal = null;
/**
* A Kiwi.Signal that dispatches an event when the animation has come to
* the end of the animation but is not going to play again.
* @property onComplete
* @type Kiwi.Signal
* @public
* @since 1.2.0
*/
public get onComplete(): Kiwi.Signal {
if (this._onComplete == null) this._onComplete = new Kiwi.Signal;
return this._onComplete;
}
/**
* Clock time on last frame, used to compute current animation frame.
* @property _lastFrameElapsed
* @type number
* @private
* @since 1.2.0
*/
private _lastFrameElapsed: number;
/**
* Start the animation.
* @method _start
* @param [index=null] {number} Index of the frame in the sequence that
* is to play. If left as null it just starts from where it left off.
* @private
*/
private _start(index: number = null) {
if (index !== null) {
this.frameIndex = index;
}
// If the animation is out of range then start it at the beginning
if ( this.frameIndex >= this.length - 1 || this.frameIndex < 0 ) {
this.frameIndex = 0;
}
this._isPlaying = true;
this._startTime = this.clock.elapsed();
this._lastFrameElapsed = this.clock.elapsed();
if ( this._onPlay !== null ) {
this._onPlay.dispatch();
}
}
/**
* Plays the animation.
* @method play
* @public
*/
public play() {
this.playAt( this._frameIndex );
}
/**
* Plays the animation at a particular frame.
* @method playAt
* @param index {number} Index of the cell in the sequence that the
* animation is to start at.
* @public
*/
public playAt( index: number ) {
this._start( index );
}
/**
* Pauses the current animation.
* @method pause
* @public
*/
public pause() {
this.stop();
}
/**
* Resumes the current animation after stopping.
* @method resume
* @public
*/
public resume() {
if (this._startTime !== null) {
this._isPlaying = true;
}
}
/**
* Stops the current animation from playing.
* @method stop
* @public
*/
public stop() {
if (this._isPlaying) {
this._isPlaying = false;
if(this._onStop !== null) this._onStop.dispatch();
}
}
/**
* Makes the animation go to the next frame. If the animation is at the end it goes back to the start.
* @method nextFrame
* @public
*/
public nextFrame() {
this._frameIndex++;
if (this._frameIndex >= this.length) this.frameIndex = 0;
}
/**
* Makes the animation go to the previous frame. If the animation is at the first frame it goes to the end.
* @method prevFrame
* @public
*/
public prevFrame() {
this._frameIndex--;
if (this._frameIndex < 0) this.frameIndex = this.length - 1;
}
/**
* The update loop.
*
* @method update
* @public
*/
public update() {
var frameDelta, i, repeats;
if ( this._isPlaying ) {
// How many frames do we move, ahead or behind?
frameDelta = ( ( this.clock.elapsed() -
this._lastFrameElapsed ) / this._speed ) % ( this.length + 1 );
if ( this._reverse ) {
frameDelta *= -1;
}
// Round delta, towards zero
if ( frameDelta > 0 ) {
frameDelta = Math.floor( frameDelta );
} else {
frameDelta = Math.ceil( frameDelta );
}
if ( frameDelta !== 0 ) {
this._frameIndex += frameDelta;
this._lastFrameElapsed = this.clock.elapsed();
// Loop check
if ( this._loop ) {
if ( this._frameIndex >= this.length ) {
repeats = Math.floor(
this._frameIndex / this.length );
this._frameIndex = this._frameIndex % this.length;
if ( this._onLoop != null ) {
for ( i = 0; i < repeats; i++ ) {
this._onLoop.dispatch();
}
}
} else if ( this._frameIndex < 0 ) {
repeats = Math.ceil(
Math.abs( this._frameIndex ) / this.length );
this._frameIndex = ( this.length +
this._frameIndex % this.length ) % this.length;
if ( this._onLoop != null ) {
for ( i = 0; i < repeats; i++ ) {
this._onLoop.dispatch();
}
}
}
} else if ( this._frameIndex < 0 ) {
this._frameIndex = ( this.length +
this._frameIndex % this.length ) % this.length;
// Execute the stop on the parent
// to allow the isPlaying boolean to remain consistent
this._parent.stop();
return;
} else if ( this._frameIndex >= this.length ) {
this._frameIndex = this._frameIndex % this.length;
// Execute the stop on the parent
// to allow the isPlaying boolean to remain consistent
this._parent.stop();
if ( this._onComplete != null ) {
this._onComplete.dispatch();
}
return;
}
this._parent.updateCellIndex();
if ( this._onUpdate !== null ) {
this._onUpdate.dispatch();
}
}
}
}
/**
* An internal method used to check to see if frame passed is valid or not
* @method _validateFrame
* @param frame {Number} The index of the frame that is to be validated.
* @private
*/
private _validateFrame(frame: number) {
return (frame < this.length && frame >= 0);
}
/**
* Returns the number of frames that in the animation. Thus the animations 'length'. Note this is READ ONLY.
* @property length
* @type number
* @public
*/
public get length():number {
return this._sequence.cells.length;
}
/**
* Destroys the anim and all of the properties that exist on it.
* @method destroy
* @public
*/
public destroy() {
this._isPlaying = false;
delete this._clock;
delete this._sequence;
delete this._parent;
if(this._onLoop) this._onLoop.dispose();
if(this._onStop) this._onStop.dispose();
if(this._onPlay) this._onPlay.dispose();
if(this._onUpdate) this._onUpdate.dispose();
delete this._onLoop;
delete this._onStop ;
delete this._onPlay ;
delete this._onUpdate ;
delete this.frameIndex ;
delete this.loop;
delete this._reverse;
delete this._tick;
}
}
} | the_stack |
import { expect } from 'chai';
import { describe, it } from 'mocha';
import { dedent } from '../../__testUtils__/dedent';
import { DirectiveLocation } from '../../language/directiveLocation';
import { printSchema } from '../../utilities/printSchema';
import { GraphQLSchema } from '../schema';
import { GraphQLDirective } from '../directives';
import { GraphQLInt, GraphQLString, GraphQLBoolean } from '../scalars';
import {
GraphQLList,
GraphQLScalarType,
GraphQLObjectType,
GraphQLInterfaceType,
GraphQLInputObjectType,
} from '../definition';
describe('Type System: Schema', () => {
it('Define sample schema', () => {
const BlogImage = new GraphQLObjectType({
name: 'Image',
fields: {
url: { type: GraphQLString },
width: { type: GraphQLInt },
height: { type: GraphQLInt },
},
});
const BlogAuthor: GraphQLObjectType = new GraphQLObjectType({
name: 'Author',
fields: () => ({
id: { type: GraphQLString },
name: { type: GraphQLString },
pic: {
args: { width: { type: GraphQLInt }, height: { type: GraphQLInt } },
type: BlogImage,
},
recentArticle: { type: BlogArticle },
}),
});
const BlogArticle: GraphQLObjectType = new GraphQLObjectType({
name: 'Article',
fields: {
id: { type: GraphQLString },
isPublished: { type: GraphQLBoolean },
author: { type: BlogAuthor },
title: { type: GraphQLString },
body: { type: GraphQLString },
},
});
const BlogQuery = new GraphQLObjectType({
name: 'Query',
fields: {
article: {
args: { id: { type: GraphQLString } },
type: BlogArticle,
},
feed: {
type: new GraphQLList(BlogArticle),
},
},
});
const BlogMutation = new GraphQLObjectType({
name: 'Mutation',
fields: {
writeArticle: {
type: BlogArticle,
},
},
});
const BlogSubscription = new GraphQLObjectType({
name: 'Subscription',
fields: {
articleSubscribe: {
args: { id: { type: GraphQLString } },
type: BlogArticle,
},
},
});
const schema = new GraphQLSchema({
description: 'Sample schema',
query: BlogQuery,
mutation: BlogMutation,
subscription: BlogSubscription,
});
expect(printSchema(schema)).to.equal(dedent`
"""Sample schema"""
schema {
query: Query
mutation: Mutation
subscription: Subscription
}
type Query {
article(id: String): Article
feed: [Article]
}
type Article {
id: String
isPublished: Boolean
author: Author
title: String
body: String
}
type Author {
id: String
name: String
pic(width: Int, height: Int): Image
recentArticle: Article
}
type Image {
url: String
width: Int
height: Int
}
type Mutation {
writeArticle: Article
}
type Subscription {
articleSubscribe(id: String): Article
}
`);
});
describe('Root types', () => {
const testType = new GraphQLObjectType({ name: 'TestType', fields: {} });
it('defines a query root', () => {
const schema = new GraphQLSchema({ query: testType });
expect(schema.getQueryType()).to.equal(testType);
expect(schema.getTypeMap()).to.include.keys('TestType');
});
it('defines a mutation root', () => {
const schema = new GraphQLSchema({ mutation: testType });
expect(schema.getMutationType()).to.equal(testType);
expect(schema.getTypeMap()).to.include.keys('TestType');
});
it('defines a subscription root', () => {
const schema = new GraphQLSchema({ subscription: testType });
expect(schema.getSubscriptionType()).to.equal(testType);
expect(schema.getTypeMap()).to.include.keys('TestType');
});
});
describe('Type Map', () => {
it('includes interface possible types in the type map', () => {
const SomeInterface = new GraphQLInterfaceType({
name: 'SomeInterface',
fields: {},
});
const SomeSubtype = new GraphQLObjectType({
name: 'SomeSubtype',
fields: {},
interfaces: [SomeInterface],
});
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
iface: { type: SomeInterface },
},
}),
types: [SomeSubtype],
});
expect(schema.getType('SomeInterface')).to.equal(SomeInterface);
expect(schema.getType('SomeSubtype')).to.equal(SomeSubtype);
expect(schema.isSubType(SomeInterface, SomeSubtype)).to.equal(true);
});
it("includes interface's thunk subtypes in the type map", () => {
const SomeInterface = new GraphQLInterfaceType({
name: 'SomeInterface',
fields: {},
interfaces: () => [AnotherInterface],
});
const AnotherInterface = new GraphQLInterfaceType({
name: 'AnotherInterface',
fields: {},
});
const SomeSubtype = new GraphQLObjectType({
name: 'SomeSubtype',
fields: {},
interfaces: () => [SomeInterface],
});
const schema = new GraphQLSchema({ types: [SomeSubtype] });
expect(schema.getType('SomeInterface')).to.equal(SomeInterface);
expect(schema.getType('AnotherInterface')).to.equal(AnotherInterface);
expect(schema.getType('SomeSubtype')).to.equal(SomeSubtype);
});
it('includes nested input objects in the map', () => {
const NestedInputObject = new GraphQLInputObjectType({
name: 'NestedInputObject',
fields: {},
});
const SomeInputObject = new GraphQLInputObjectType({
name: 'SomeInputObject',
fields: { nested: { type: NestedInputObject } },
});
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
something: {
type: GraphQLString,
args: { input: { type: SomeInputObject } },
},
},
}),
});
expect(schema.getType('SomeInputObject')).to.equal(SomeInputObject);
expect(schema.getType('NestedInputObject')).to.equal(NestedInputObject);
});
it('includes input types only used in directives', () => {
const directive = new GraphQLDirective({
name: 'dir',
locations: [DirectiveLocation.OBJECT],
args: {
arg: {
type: new GraphQLInputObjectType({ name: 'Foo', fields: {} }),
},
argList: {
type: new GraphQLList(
new GraphQLInputObjectType({ name: 'Bar', fields: {} }),
),
},
},
});
const schema = new GraphQLSchema({ directives: [directive] });
expect(schema.getTypeMap()).to.include.keys('Foo', 'Bar');
});
});
it('preserves the order of user provided types', () => {
const aType = new GraphQLObjectType({
name: 'A',
fields: {
sub: { type: new GraphQLScalarType({ name: 'ASub' }) },
},
});
const zType = new GraphQLObjectType({
name: 'Z',
fields: {
sub: { type: new GraphQLScalarType({ name: 'ZSub' }) },
},
});
const queryType = new GraphQLObjectType({
name: 'Query',
fields: {
a: { type: aType },
z: { type: zType },
sub: { type: new GraphQLScalarType({ name: 'QuerySub' }) },
},
});
const schema = new GraphQLSchema({
types: [zType, queryType, aType],
query: queryType,
});
const typeNames = Object.keys(schema.getTypeMap());
expect(typeNames).to.deep.equal([
'Z',
'ZSub',
'Query',
'QuerySub',
'A',
'ASub',
'Boolean',
'String',
'__Schema',
'__Type',
'__TypeKind',
'__Field',
'__InputValue',
'__EnumValue',
'__Directive',
'__DirectiveLocation',
]);
// Also check that this order is stable
const copySchema = new GraphQLSchema(schema.toConfig());
expect(Object.keys(copySchema.getTypeMap())).to.deep.equal(typeNames);
});
it('can be Object.toStringified', () => {
const schema = new GraphQLSchema({});
expect(Object.prototype.toString.call(schema)).to.equal(
'[object GraphQLSchema]',
);
});
describe('Validity', () => {
describe('when not assumed valid', () => {
it('configures the schema to still needing validation', () => {
expect(
new GraphQLSchema({
assumeValid: false,
}).__validationErrors,
).to.equal(undefined);
});
it('checks the configuration for mistakes', () => {
// @ts-expect-error
expect(() => new GraphQLSchema(JSON.parse)).to.throw();
// @ts-expect-error
expect(() => new GraphQLSchema({ types: {} })).to.throw();
// @ts-expect-error
expect(() => new GraphQLSchema({ directives: {} })).to.throw();
});
});
describe('A Schema must contain uniquely named types', () => {
it('rejects a Schema which redefines a built-in type', () => {
const FakeString = new GraphQLScalarType({ name: 'String' });
const QueryType = new GraphQLObjectType({
name: 'Query',
fields: {
normal: { type: GraphQLString },
fake: { type: FakeString },
},
});
expect(() => new GraphQLSchema({ query: QueryType })).to.throw(
'Schema must contain uniquely named types but contains multiple types named "String".',
);
});
it('rejects a Schema when a provided type has no name', () => {
const query = new GraphQLObjectType({
name: 'Query',
fields: { foo: { type: GraphQLString } },
});
const types = [{}, query, {}];
// @ts-expect-error
expect(() => new GraphQLSchema({ query, types })).to.throw(
'One of the provided types for building the Schema is missing a name.',
);
});
it('rejects a Schema which defines an object type twice', () => {
const types = [
new GraphQLObjectType({ name: 'SameName', fields: {} }),
new GraphQLObjectType({ name: 'SameName', fields: {} }),
];
expect(() => new GraphQLSchema({ types })).to.throw(
'Schema must contain uniquely named types but contains multiple types named "SameName".',
);
});
it('rejects a Schema which defines fields with conflicting types', () => {
const fields = {};
const QueryType = new GraphQLObjectType({
name: 'Query',
fields: {
a: { type: new GraphQLObjectType({ name: 'SameName', fields }) },
b: { type: new GraphQLObjectType({ name: 'SameName', fields }) },
},
});
expect(() => new GraphQLSchema({ query: QueryType })).to.throw(
'Schema must contain uniquely named types but contains multiple types named "SameName".',
);
});
});
describe('when assumed valid', () => {
it('configures the schema to have no errors', () => {
expect(
new GraphQLSchema({
assumeValid: true,
}).__validationErrors,
).to.deep.equal([]);
});
});
});
}); | the_stack |
import type {ExtendedError} from '@layr/utilities';
import {Component} from '../component';
import {EmbeddedComponent} from '../embedded-component';
import {Attribute} from './attribute';
import {isNumberValueTypeInstance} from './value-types';
import {sanitizers} from '../sanitization';
import {validators} from '../validation';
describe('Attribute', () => {
test('Creation', async () => {
class Movie extends Component {}
const attribute = new Attribute('limit', Movie, {valueType: 'number'});
expect(Attribute.isAttribute(attribute)).toBe(true);
expect(attribute.getName()).toBe('limit');
expect(attribute.getParent()).toBe(Movie);
expect(isNumberValueTypeInstance(attribute.getValueType())).toBe(true);
});
test('Value', async () => {
class Movie extends Component {}
const movie = new Movie();
const attribute = new Attribute('title', movie, {valueType: 'string'});
expect(attribute.isSet()).toBe(false);
expect(() => attribute.getValue()).toThrow(
"Cannot get the value of an unset attribute (attribute: 'Movie.prototype.title')"
);
expect(attribute.getValue({throwIfUnset: false})).toBeUndefined();
attribute.setValue('Inception');
expect(attribute.isSet()).toBe(true);
expect(attribute.getValue()).toBe('Inception');
attribute.unsetValue();
expect(attribute.isSet()).toBe(false);
expect(() => attribute.setValue(123)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'Movie.prototype.title', expected type: 'string', received type: 'number')"
);
expect(() => attribute.setValue(undefined)).toThrow(
"Cannot assign a value of an unexpected type (attribute: 'Movie.prototype.title', expected type: 'string', received type: 'undefined')"
);
});
test('Value source', async () => {
class Movie extends Component {}
const movie = new Movie();
const attribute = new Attribute('title', movie, {valueType: 'string'});
attribute.setValue('Inception');
expect(attribute.getValueSource()).toBe('local');
attribute.setValue('Inception', {source: 'server'});
expect(attribute.getValueSource()).toBe('server');
});
test('Accessors', async () => {
class Movie extends Component {}
const movie = new Movie();
const attribute = new Attribute('title', movie, {
valueType: 'string',
getter() {
expect(this).toBe(movie);
return this._title;
},
setter(title) {
expect(this).toBe(movie);
this._title = title.substr(0, 1).toUpperCase() + title.substr(1);
}
});
expect(attribute.isSet()).toBe(true);
expect(attribute.getValue()).toBeUndefined();
attribute.setValue('inception');
expect(attribute.getValue()).toBe('Inception');
expect(
() =>
new Attribute('title', movie, {
setter(title) {
this._title = title;
}
})
).toThrow(
"An attribute cannot have a setter without a getter (attribute: 'Movie.prototype.title')"
);
});
test('Initial value', async () => {
class Movie extends Component {}
let attribute = new Attribute('limit', Movie, {valueType: 'number'});
expect(attribute.isSet()).toBe(false);
attribute = new Attribute('limit', Movie, {valueType: 'number', value: 100});
expect(attribute.isSet()).toBe(true);
expect(attribute.getValue()).toBe(100);
expect(
() =>
new Attribute('limit', Movie, {
valueType: 'number',
value: 100,
getter() {
return 100;
}
})
).toThrow(
"An attribute cannot have both a getter or setter and an initial value (attribute: 'Movie.limit')"
);
});
test('Default value', async () => {
class Movie extends Component {}
const movie = new Movie();
let attribute = new Attribute('duration', movie, {valueType: 'number?'});
expect(attribute.getDefault()).toBe(undefined);
expect(attribute.evaluateDefault()).toBe(undefined);
attribute = new Attribute('title', movie, {valueType: 'string', default: ''});
expect(attribute.getDefault()).toBe('');
expect(attribute.evaluateDefault()).toBe('');
attribute = new Attribute('title', movie, {valueType: 'string', default: () => 1 + 1});
expect(typeof attribute.getDefault()).toBe('function');
expect(attribute.evaluateDefault()).toBe(2);
attribute = new Attribute('movieClass', movie, {valueType: 'string', default: Movie});
expect(typeof attribute.getDefault()).toBe('function');
expect(attribute.evaluateDefault()).toBe(Movie);
expect(
() =>
new Attribute('title', movie, {
valueType: 'number?',
default: '',
getter() {
return '';
}
})
).toThrow(
"An attribute cannot have both a getter or setter and a default value (attribute: 'Movie.prototype.title')"
);
});
test('isControlled() and markAsControlled()', async () => {
class Movie extends Component {}
const attribute = new Attribute('title', Movie.prototype);
expect(attribute.isControlled()).toBe(false);
attribute.setValue('Inception');
expect(attribute.getValue()).toBe('Inception');
attribute.markAsControlled();
expect(attribute.isControlled()).toBe(true);
expect(() => attribute.setValue('Inception 2')).toThrow(
"Cannot set the value of a controlled attribute when the source is different than 'server' or 'store' (attribute: 'Movie.prototype.title', source: 'local')"
);
expect(attribute.getValue()).toBe('Inception');
});
test('Sanitization', async () => {
class Movie extends Component {}
const movie = new Movie();
const {trim, compact} = sanitizers;
const titleAttribute = new Attribute('title', movie, {
valueType: 'string',
sanitizers: [trim()]
});
titleAttribute.setValue('Inception');
expect(titleAttribute.getValue()).toBe('Inception');
titleAttribute.setValue(' Inception ');
expect(titleAttribute.getValue()).toBe('Inception');
const genresAttribute = new Attribute('genres', movie, {
valueType: 'string[]',
sanitizers: [compact()],
items: {sanitizers: [trim()]}
});
genresAttribute.setValue(['drama', 'action']);
expect(genresAttribute.getValue()).toStrictEqual(['drama', 'action']);
genresAttribute.setValue(['drama ', ' action']);
expect(genresAttribute.getValue()).toStrictEqual(['drama', 'action']);
genresAttribute.setValue(['drama ', '']);
expect(genresAttribute.getValue()).toStrictEqual(['drama']);
genresAttribute.setValue(['', ' ']);
expect(genresAttribute.getValue()).toStrictEqual([]);
});
test('Validation', async () => {
class Movie extends Component {}
const movie = new Movie();
let notEmpty = validators.notEmpty();
let attribute = new Attribute('title', movie, {valueType: 'string?', validators: [notEmpty]});
expect(() => attribute.runValidators()).toThrow(
"Cannot run the validators of an unset attribute (attribute: 'Movie.prototype.title')"
);
attribute.setValue('Inception');
expect(() => attribute.validate()).not.toThrow();
expect(attribute.isValid()).toBe(true);
expect(attribute.runValidators()).toEqual([]);
attribute.setValue('');
expect(() => attribute.validate()).toThrow(
"The following error(s) occurred while validating the attribute 'title': The validator `notEmpty()` failed (path: '')"
);
expect(attribute.isValid()).toBe(false);
expect(attribute.runValidators()).toEqual([{validator: notEmpty, path: ''}]);
attribute.setValue(undefined);
expect(() => attribute.validate()).toThrow(
"The following error(s) occurred while validating the attribute 'title': The validator `notEmpty()` failed (path: '')"
);
expect(attribute.isValid()).toBe(false);
expect(attribute.runValidators()).toEqual([{validator: notEmpty, path: ''}]);
// --- With a custom message ---
notEmpty = validators.notEmpty('The title cannot be empty.');
attribute = new Attribute('title', movie, {valueType: 'string?', validators: [notEmpty]});
attribute.setValue('Inception');
expect(() => attribute.validate()).not.toThrow();
attribute.setValue('');
let error: ExtendedError;
try {
attribute.validate();
} catch (err) {
error = err;
}
expect(error!.message).toBe(
"The following error(s) occurred while validating the attribute 'title': The title cannot be empty. (path: '')"
);
expect(error!.displayMessage).toBe('The title cannot be empty.');
});
test('Observability', async () => {
class Movie extends Component {}
const movie = new Movie();
const movieObserver = jest.fn();
movie.addObserver(movieObserver);
const titleAttribute = new Attribute('title', movie, {valueType: 'string'});
const titleObserver = jest.fn();
titleAttribute.addObserver(titleObserver);
expect(titleObserver).toHaveBeenCalledTimes(0);
expect(movieObserver).toHaveBeenCalledTimes(0);
titleAttribute.setValue('Inception');
expect(titleObserver).toHaveBeenCalledTimes(1);
expect(movieObserver).toHaveBeenCalledTimes(1);
titleAttribute.setValue('Inception 2');
expect(titleObserver).toHaveBeenCalledTimes(2);
expect(movieObserver).toHaveBeenCalledTimes(2);
titleAttribute.setValue('Inception 2');
// Assigning the same value should not call the observers
expect(titleObserver).toHaveBeenCalledTimes(2);
expect(movieObserver).toHaveBeenCalledTimes(2);
const tagsAttribute = new Attribute('title', movie, {valueType: 'string[]'});
const tagsObserver = jest.fn();
tagsAttribute.addObserver(tagsObserver);
expect(tagsObserver).toHaveBeenCalledTimes(0);
expect(movieObserver).toHaveBeenCalledTimes(2);
tagsAttribute.setValue(['drama', 'action']);
expect(tagsObserver).toHaveBeenCalledTimes(1);
expect(movieObserver).toHaveBeenCalledTimes(3);
const tagArray = tagsAttribute.getValue() as string[];
tagArray[0] = 'Drama';
expect(tagsObserver).toHaveBeenCalledTimes(2);
expect(movieObserver).toHaveBeenCalledTimes(4);
tagArray[0] = 'Drama';
// Assigning the same value should not call the observers
expect(tagsObserver).toHaveBeenCalledTimes(2);
expect(movieObserver).toHaveBeenCalledTimes(4);
tagsAttribute.setValue(['Drama', 'Action']);
expect(tagsObserver).toHaveBeenCalledTimes(3);
expect(movieObserver).toHaveBeenCalledTimes(5);
const newTagArray = tagsAttribute.getValue() as string[];
newTagArray[0] = 'drama';
expect(tagsObserver).toHaveBeenCalledTimes(4);
expect(movieObserver).toHaveBeenCalledTimes(6);
tagArray[0] = 'DRAMA';
// Modifying the previous array should not call the observers
expect(tagsObserver).toHaveBeenCalledTimes(4);
expect(movieObserver).toHaveBeenCalledTimes(6);
tagsAttribute.unsetValue();
expect(tagsObserver).toHaveBeenCalledTimes(5);
expect(movieObserver).toHaveBeenCalledTimes(7);
tagsAttribute.unsetValue();
// Calling unset again should not call the observers
expect(tagsObserver).toHaveBeenCalledTimes(5);
expect(movieObserver).toHaveBeenCalledTimes(7);
newTagArray[0] = 'drama';
// Modifying the detached array should not call the observers
expect(tagsObserver).toHaveBeenCalledTimes(5);
expect(movieObserver).toHaveBeenCalledTimes(7);
// --- With an embedded component ---
class UserDetails extends EmbeddedComponent {}
const userDetails = new UserDetails();
const countryAttribute = new Attribute('country', userDetails, {valueType: 'string'});
class User extends Component {}
User.provideComponent(UserDetails);
let user = new User();
let userObserver = jest.fn();
user.addObserver(userObserver);
const detailsAttribute = new Attribute('details', user, {valueType: 'UserDetails?'});
expect(userObserver).toHaveBeenCalledTimes(0);
detailsAttribute.setValue(userDetails);
expect(userObserver).toHaveBeenCalledTimes(1);
countryAttribute.setValue('Japan');
expect(userObserver).toHaveBeenCalledTimes(2);
detailsAttribute.setValue(undefined);
expect(userObserver).toHaveBeenCalledTimes(3);
countryAttribute.setValue('France');
expect(userObserver).toHaveBeenCalledTimes(3);
// --- With an array of embedded components ---
class Organization extends EmbeddedComponent {}
const organization = new Organization();
const organizationNameAttribute = new Attribute('name', organization, {valueType: 'string'});
User.provideComponent(Organization);
user = new User();
userObserver = jest.fn();
user.addObserver(userObserver);
const organizationsAttribute = new Attribute('organizations', user, {
valueType: 'Organization[]'
});
expect(userObserver).toHaveBeenCalledTimes(0);
organizationsAttribute.setValue([]);
expect(userObserver).toHaveBeenCalledTimes(1);
(organizationsAttribute.getValue() as Organization[]).push(organization);
expect(userObserver).toHaveBeenCalledTimes(2);
organizationNameAttribute.setValue('The Inc.');
expect(userObserver).toHaveBeenCalledTimes(3);
(organizationsAttribute.getValue() as Organization[]).pop();
expect(userObserver).toHaveBeenCalledTimes(5);
organizationNameAttribute.setValue('Nice Inc.');
expect(userObserver).toHaveBeenCalledTimes(5);
// --- With a referenced component ---
class Blog extends Component {}
const blog = new Blog();
const blogNameAttribute = new Attribute('name', blog, {valueType: 'string'});
class Article extends Component {}
Article.provideComponent(Blog);
let article = new Article();
let articleObserver = jest.fn();
article.addObserver(articleObserver);
const blogAttribute = new Attribute('blog', article, {valueType: 'Blog?'});
expect(articleObserver).toHaveBeenCalledTimes(0);
blogAttribute.setValue(blog);
expect(articleObserver).toHaveBeenCalledTimes(1);
blogNameAttribute.setValue('My Blog');
expect(articleObserver).toHaveBeenCalledTimes(1);
blogAttribute.setValue(undefined);
expect(articleObserver).toHaveBeenCalledTimes(2);
blogNameAttribute.setValue('The Blog');
expect(articleObserver).toHaveBeenCalledTimes(2);
// --- With an array of referenced components ---
class Comment extends Component {}
const comment = new Comment();
const commentTextAttribute = new Attribute('text', comment, {valueType: 'string'});
Article.provideComponent(Comment);
article = new Article();
articleObserver = jest.fn();
article.addObserver(articleObserver);
const commentsAttribute = new Attribute('comments', article, {valueType: 'Comment[]'});
expect(articleObserver).toHaveBeenCalledTimes(0);
commentsAttribute.setValue([]);
expect(articleObserver).toHaveBeenCalledTimes(1);
(commentsAttribute.getValue() as Comment[]).push(comment);
expect(articleObserver).toHaveBeenCalledTimes(2);
commentTextAttribute.setValue('Hello');
expect(articleObserver).toHaveBeenCalledTimes(2);
(commentsAttribute.getValue() as Comment[]).pop();
expect(articleObserver).toHaveBeenCalledTimes(4);
commentTextAttribute.setValue('Hey');
expect(articleObserver).toHaveBeenCalledTimes(4);
});
test('Forking', async () => {
class Movie extends Component {}
const movie = new Movie();
const attribute = new Attribute('title', movie, {valueType: 'string'});
attribute.setValue('Inception');
expect(attribute.getValue()).toBe('Inception');
const forkedMovie = Object.create(movie);
const forkedAttribute = attribute.fork(forkedMovie);
expect(forkedAttribute.getValue()).toBe('Inception');
forkedAttribute.setValue('Inception 2');
expect(forkedAttribute.getValue()).toBe('Inception 2');
expect(attribute.getValue()).toBe('Inception');
});
test('Introspection', async () => {
class Movie extends Component {}
expect(
new Attribute('limit', Movie, {valueType: 'number', exposure: {get: true}}).introspect()
).toStrictEqual({
name: 'limit',
type: 'Attribute',
exposure: {get: true},
valueType: 'number'
});
expect(
new Attribute('limit', Movie, {
valueType: 'number',
value: 100,
exposure: {set: true}
}).introspect()
).toStrictEqual({name: 'limit', type: 'Attribute', exposure: {set: true}, valueType: 'number'});
expect(
new Attribute('limit', Movie, {
valueType: 'number',
value: 100,
exposure: {get: true}
}).introspect()
).toStrictEqual({
name: 'limit',
type: 'Attribute',
value: 100,
exposure: {get: true},
valueType: 'number'
});
const defaultTitle = function () {
return '';
};
expect(
new Attribute('title', Movie.prototype, {
valueType: 'string',
default: defaultTitle,
exposure: {get: true, set: true}
}).introspect()
).toStrictEqual({
name: 'title',
type: 'Attribute',
default: defaultTitle,
exposure: {get: true, set: true},
valueType: 'string'
});
// When 'set' is not exposed, the default value should not be exposed
expect(
new Attribute('title', Movie.prototype, {
valueType: 'string',
default: defaultTitle,
exposure: {get: true}
}).introspect()
).toStrictEqual({
name: 'title',
type: 'Attribute',
exposure: {get: true},
valueType: 'string'
});
const notEmpty = validators.notEmpty();
expect(
new Attribute('title', Movie.prototype, {
valueType: 'string?',
validators: [notEmpty],
exposure: {get: true}
}).introspect()
).toStrictEqual({
name: 'title',
type: 'Attribute',
valueType: 'string?',
exposure: {get: true},
validators: [notEmpty]
});
expect(
new Attribute('tags', Movie.prototype, {
valueType: 'string[]',
exposure: {get: true}
}).introspect()
).toStrictEqual({
name: 'tags',
type: 'Attribute',
valueType: 'string[]',
exposure: {get: true}
});
expect(
new Attribute('tags', Movie.prototype, {
valueType: 'string[]',
items: {validators: [notEmpty]},
exposure: {get: true}
}).introspect()
).toStrictEqual({
name: 'tags',
type: 'Attribute',
valueType: 'string[]',
items: {
validators: [notEmpty]
},
exposure: {get: true}
});
expect(
new Attribute('tags', Movie.prototype, {
valueType: 'string[][]',
items: {items: {validators: [notEmpty]}},
exposure: {get: true}
}).introspect()
).toStrictEqual({
name: 'tags',
type: 'Attribute',
valueType: 'string[][]',
items: {
items: {
validators: [notEmpty]
}
},
exposure: {get: true}
});
});
test('Unintrospection', async () => {
class Movie extends Component {}
let {name, options} = Attribute.unintrospect({
name: 'limit',
type: 'Attribute',
valueType: 'number',
exposure: {get: true}
});
expect({name, options}).toEqual({
name: 'limit',
options: {valueType: 'number', exposure: {get: true}}
});
expect(() => new Attribute(name, Movie, options)).not.toThrow();
({name, options} = Attribute.unintrospect({
name: 'limit',
type: 'Attribute',
valueType: 'number',
value: 100,
exposure: {get: true}
}));
expect({name, options}).toEqual({
name: 'limit',
options: {valueType: 'number', value: 100, exposure: {get: true}}
});
expect(() => new Attribute(name, Movie, options)).not.toThrow();
const defaultTitle = function () {
return '';
};
({name, options} = Attribute.unintrospect({
name: 'title',
type: 'Attribute',
valueType: 'string',
default: defaultTitle,
exposure: {get: true, set: true}
}));
expect({name, options}).toEqual({
name: 'title',
options: {valueType: 'string', default: defaultTitle, exposure: {get: true, set: true}}
});
expect(() => new Attribute(name, Movie.prototype, options)).not.toThrow();
const notEmptyValidator = validators.notEmpty();
({name, options} = Attribute.unintrospect({
name: 'title',
type: 'Attribute',
valueType: 'string?',
validators: [notEmptyValidator],
exposure: {get: true}
}));
expect(name).toBe('title');
expect(options.valueType).toBe('string?');
expect(options.validators).toEqual([notEmptyValidator]);
expect(options.exposure).toEqual({get: true});
expect(() => new Attribute(name, Movie.prototype, options)).not.toThrow();
({name, options} = Attribute.unintrospect({
name: 'tags',
type: 'Attribute',
valueType: 'string[]',
items: {
validators: [notEmptyValidator]
},
exposure: {get: true}
}));
expect(name).toBe('tags');
expect(options.valueType).toBe('string[]');
expect(options.validators).toBeUndefined();
expect(options.items!.validators).toEqual([notEmptyValidator]);
expect(options.exposure).toEqual({get: true});
expect(() => new Attribute(name, Movie.prototype, options)).not.toThrow();
({name, options} = Attribute.unintrospect({
name: 'tags',
type: 'Attribute',
valueType: 'string[][]',
items: {
items: {
validators: [notEmptyValidator]
}
},
exposure: {get: true}
}));
expect(name).toBe('tags');
expect(options.valueType).toBe('string[][]');
expect(options.validators).toBeUndefined();
expect(options.items!.validators).toBeUndefined();
expect(options.items!.items!.validators).toEqual([notEmptyValidator]);
expect(options.exposure).toEqual({get: true});
expect(() => new Attribute(name, Movie.prototype, options)).not.toThrow();
});
}); | the_stack |
import {polyglot} from '../../src/i18n/polyglot';
import {DiffFilesResolver} from '../../src/app/common/diffFilesResolver';
// TODO: This should be done using require.context
const preloadedFiles = {
'app.component.ts': require(`!raw-loader!./app.component.ts`),
'app.module.ts': require('!raw-loader!./app.module.ts'),
'app.html': require('!raw-loader!./app.html'),
'main.ts': require('!raw-loader!./main.ts'),
'video/video-item.ts': require('!raw-loader!./video/video-item.ts'),
'api.service.ts': require('!raw-loader!./api.service.ts'),
'video/video.service.ts': require('!raw-loader!./video/video.service.ts'),
'video/video.html': require('!raw-loader!./video/video.html'),
'video/video.component.ts': require('!raw-loader!./video/video.component.ts'),
'thumbs/thumbs.component.ts': require('!raw-loader!./thumbs/thumbs.component.ts'),
'thumbs/thumbs.html': require('!raw-loader!./thumbs/thumbs.html'),
'toggle-panel/toggle-panel.html': require('!raw-loader!./toggle-panel/toggle-panel.html'),
'toggle-panel/toggle-panel.component.ts': require('!raw-loader!./toggle-panel/toggle-panel.component.ts'),
'wrapper.component.ts': require('!raw-loader!./wrapper.component.ts'),
'context/context.component.ts': require('!raw-loader!./context/context.component.ts'),
'context/context.service.ts': require('!raw-loader!./context/context.service.ts'),
'context/context.html': require('!raw-loader!./context/context.html'),
'typescript-intro/Codelab.ts': require('!raw-loader!./typescript-intro/Codelab.ts'),
'typescript-intro/Main.ts': require('!raw-loader!./typescript-intro/Main.ts'),
'typescript-intro/Guest.ts': require('!raw-loader!./typescript-intro/Guest.ts'),
'fuzzy-pipe/fuzzy.pipe.ts': require('!raw-loader!./fuzzy-pipe/fuzzy.pipe.ts'),
'tests/codelabTest.ts': require('!raw-loader!./tests/codelabTest.ts'),
'tests/createComponentTest.ts': require('!raw-loader!./tests/createComponentTest.ts'),
'tests/createModuleTest.ts': require('!raw-loader!./tests/createModuleTest.ts'),
'tests/bootstrapTest.ts': require('!raw-loader!./tests/bootstrapTest.ts'),
'tests/templatePageSetupTest.ts': require('!raw-loader!./tests/templatePageSetupTest.ts'),
'tests/templateAddActionTest.ts': require('!raw-loader!./tests/templateAddActionTest.ts'),
'tests/templateAllVideosTest.ts': require('!raw-loader!./tests/templateAllVideosTest.ts'),
'tests/diInjectServiceTest.ts': require('!raw-loader!./tests/diInjectServiceTest.ts'),
'tests/videoComponentCreateTest.ts': require('!raw-loader!./tests/videoComponentCreateTest.ts'),
'tests/videoComponentUseTest.ts': require('!raw-loader!./tests/videoComponentUseTest.ts'),
'tests/ThumbsComponentCreateTest.ts': require('!raw-loader!./tests/ThumbsComponentCreateTest.ts'),
'tests/ThumbsComponentUseTest.ts': require('!raw-loader!./tests/ThumbsComponentUseTest.ts'),
'tests/togglePanelComponentCreateTest.ts': require('!raw-loader!./tests/togglePanelComponentCreateTest.ts'),
'tests/togglePanelComponentUseTest.ts': require('!raw-loader!./tests/togglePanelComponentUseTest.ts'),
'tests/contextComponentUseTest.ts': require('!raw-loader!./tests/contextComponentUseTest.ts'),
'tests/fuzzyPipeCreateTest.ts': require('!raw-loader!./tests/fuzzyPipeCreateTest.ts'),
'tests/fuzzyPipeUseTest.ts': require('!raw-loader!./tests/fuzzyPipeUseTest.ts'),
'thumbs.app.module.ts': require('!raw-loader!./thumbs.app.module.ts'),
'toggle-panel.app.module.ts': require('!raw-loader!./toggle-panel.app.module.ts'),
'index.html': '<my-thumbs></my-thumbs><my-wrapper></my-wrapper>'
};
const files = {
appComponent: 'app.component.ts',
appModule: 'app.module.ts',
appHtml: 'app.html',
main: 'main.ts',
video_videoItem: 'video/video-item.ts',
apiService: 'api.service.ts',
video_videoService: 'video/video.service.ts',
video_video_html: 'video/video.html',
video_video_component: 'video/video.component.ts',
thumbs_thumbs_component: 'thumbs/thumbs.component.ts',
thumbs_thumbs_html: 'thumbs/thumbs.html',
toggle_panel_toggle_panel_html: 'toggle-panel/toggle-panel.html',
toggle_panel_toggle_panel: 'toggle-panel/toggle-panel.component.ts',
wrapperComponent: 'wrapper.component.ts',
contextComponent: 'context/context.component.ts',
context_context_html: 'context/context.html',
contextService: 'context/context.service.ts',
typescript_intro_Codelab_ts: 'typescript-intro/Codelab.ts',
typescript_intro_Main_ts: 'typescript-intro/Main.ts',
typescript_intro_Guest_ts: 'typescript-intro/Guest.ts',
fuzzyPipe_fuzzyPipe: 'fuzzy-pipe/fuzzy.pipe.ts',
test: 'tests/test.ts',
indexHtml: 'index.html'
};
const fileOverrides = {
'app.module.ts': {
thumbsComponentCreate: 'thumbs.app.module.ts',
togglePanelComponentCreate: 'toggle-panel.app.module.ts'
},
'tests/test.ts': {
codelab: 'tests/codelabTest.ts',
createComponent: 'tests/createComponentTest.ts',
createModule: 'tests/createModuleTest.ts',
bootstrap: 'tests/bootstrapTest.ts',
templatePageSetup: 'tests/templatePageSetupTest.ts',
templateAddAction: 'tests/templateAddActionTest.ts',
templateAllVideos: 'tests/templateAllVideosTest.ts',
diInjectService: 'tests/diInjectServiceTest.ts',
videoComponentCreate: 'tests/videoComponentCreateTest.ts',
videoComponentUse: 'tests/videoComponentUseTest.ts',
thumbsComponentCreate: 'tests/ThumbsComponentCreateTest.ts',
thumbsComponentUse: 'tests/ThumbsComponentUseTest.ts',
togglePanelComponentCreate: 'tests/togglePanelComponentCreateTest.ts',
togglePanelComponentUse: 'tests/togglePanelComponentUseTest.ts',
contextComponentUse: 'tests/contextComponentUseTest.ts',
fuzzyPipeCreate: 'tests/fuzzyPipeCreateTest.ts',
fuzzyPipeUse: 'tests/fuzzyPipeUseTest.ts',
}
};
const stageOverrides = {
'main.ts': {
createComponent: 'bootstrapSolved',
createModule: 'bootstrapSolved',
},
'app.module.ts': {
createComponent: 'bootstrapSolved'
}
};
const stages: string[] = [
'codelab',
'createComponent',
'createModule',
'bootstrap',
'templatePageSetup',
'templateAddAction',
'templateAllVideos',
'diInjectService',
'dataBinding',
'videoComponentCreate',
'videoComponentUse',
'thumbsComponentCreate',
'thumbsComponentUse',
'togglePanelComponentCreate',
'togglePanelComponentUse',
'contextComponentUse',
'fuzzyPipeCreate',
'fuzzyPipeUse',
'neverShow'
];
const diffFilesResolver = new DiffFilesResolver(preloadedFiles, stages, {
file: fileOverrides,
stage: stageOverrides
});
export interface CodelabConfigTemplate {
name: string;
id: string,
defaultRunner: string,
milestones: MilestoneConfigTemplate[]
}
export interface SlideTemplate {
slide: true,
name: string,
description: string
}
export interface ExerciseConfigTemplate {
slide?: false,
name: string,
skipTests?: boolean,
description: string,
runner?: string,
files: {
exercise?: string[]
reference?: string[]
hidden?: string[]
bootstrap?: string[],
test?: string[]
}
}
export interface MilestoneConfigTemplate {
name: string,
exercises: Array<ExerciseConfigTemplate|SlideTemplate>
}
export const ng2tsConfig: CodelabConfigTemplate = {
name: 'Angular 101 Codelab (beta)',
id: 'ng2ts',
defaultRunner: 'Angular',
milestones: [
{
name: polyglot.t('Intro to TypeScript'),
exercises: [
{
name: polyglot.t(`Intro`),
slide: true,
description: `
<h1>${polyglot.t('Angular/TypeScript CodeLab!')}</h1>
<p>${polyglot.t(`In this codelab we're going to learn the basics of TypeScript and Angular.`)}</p>
<p>${polyglot.t(`This is a beta version of the codelab with limited access, please don't share it publically (yet).`)}</p>
<p>${polyglot.t(`This codelab is very new and only covers the basics of Angular. Please leave your feedback (in the end) and come back for more advanced exercises later.`)}</p>
<p>${polyglot.t(`We're using Angular version 2.3.0`)}</p>
<p>${polyglot.t(`The slides for the codelab are available using
<a href = "https://docs.google.com/presentation/d/1Wh4ZwTKG1h66f3mTD4GQO8rKwGDEJeBSvUDJ3udU1LA/edit?usp=sharing">this link</a>.`)}</p>
`
},
{
name: polyglot.t(`TypeScript`),
runner: 'TypeScript',
description: `
<p>${polyglot.t(`We created a TypeScript file for you, now let's add our first TS class
called Codelab.`)}</p>
<p>${polyglot.t(`It will take a list of guests, and will have a 'getGuestsComing' method, which will only return people who're coming.`)}</p>
<p>${polyglot.t(`As you can see in the 'Main.ts' file we have 4 people signed up, but Charles Darwin had a last minute change of plans,
so only 3 people should be returned.`)}</p>
`,
files: diffFilesResolver.resolve('codelab', {
exercise: [
files.typescript_intro_Codelab_ts,
files.typescript_intro_Guest_ts,
files.typescript_intro_Main_ts
],
test: [files.test],
bootstrap: [
files.typescript_intro_Main_ts
]
}),
}
]
},
{
name: polyglot.t(`Bootstrapping your app`),
exercises: [
{
name: polyglot.t(`Intro`),
slide: true,
description: `
<h1>${polyglot.t(`Let's build our first Angular app!`)}</h1>
<p>${polyglot.t(`This is how it will look:`)}</p>
<div class = "inBrowser">
<div class="smaller">
<h1>Hello CatTube!</h1>
</div>
</div>
<p>${polyglot.t(`3 simple steps:`)}</p>
<ol>
<li>${polyglot.t(`Create a Component`)}</li>
<li>${polyglot.t(`Create a NgModule`)}</li>
<li>${polyglot.t(`Bootstrap the NgModule`)}</li>
</ol>
`
},
{
name: polyglot.t(`Create a component`),
description: `<p>${polyglot.t(`Create first Angular component!`)}</p>`,
files: diffFilesResolver.resolve('createComponent', {
exercise: [files.appComponent],
reference: [files.appModule, files.main],
bootstrap: [files.main],
test: [files.test],
})
},
{
name: polyglot.t(`Create a NgModule`),
description: polyglot.t(`Now we got the component, we need to pass it to a NgModule.`),
files: diffFilesResolver.resolve('createModule', {
exercise: [files.appModule],
reference: [files.appComponent],
hidden: [files.main],
test: [files.test],
bootstrap: [files.main]
})
},
{
name: polyglot.t(`Bootstrap the module`),
skipTests: true,
description: `
<p>${polyglot.t(`Now we got both NgModule and component ready, let's bootstrap the app!`)}</p>
<p>${polyglot.t(`There's no simple way to test it, make sure your app displays: 'Hello CatTube!'`)}</p>`,
files: diffFilesResolver.resolve('bootstrap', {
exercise: [files.main],
reference: [files.appComponent, files.appModule],
test: [files.test],
bootstrap: [files.main]
})
}
]
},
{
name: polyglot.t(`Templates`),
exercises: [
{
name: polyglot.t(`Intro`),
slide: true,
description: `
<h1>${polyglot.t(`Exploring Angular templates!`)}</h1>
<p>${polyglot.t(`As a result we'll see our cats displayed.`)}</p>
<div class = "inBrowser">
<div class="smaller">
<my-app><div>
<h1>${polyglot.t(`CatTube`)}</h1>
<button>${polyglot.t(`Search!`)}</button>
<div>
<h2>${polyglot.t(`Cute kitten`)}</h2>
<img src="/assets/images/cat-0.png">
</div><div>
<h2>${polyglot.t(`Kitten on the tree`)}</h2>
<img src="/assets/images/cat-1.jpg">
</div><div>
<h2>${polyglot.t(`Serouis cat`)}</h2>
<img src="/assets/images/cat-2.jpg">
</div>
</div></my-app>
</div>
</div>
`
},
{
name: polyglot.t(`Set up the page`),
description: polyglot.t(`Setup a header, a search box, and a search button in the app component!`),
files: diffFilesResolver.resolve('templatePageSetup', {
exercise: [files.appHtml],
reference: [files.appComponent, files.appModule, files.main],
test: [files.test],
bootstrap: [files.main]
})
}, {
name: polyglot.t(`Add some action`),
description: `
<ul>
<li>${polyglot.t(`Add a search method to the AppComponent`)}</li>
<li>${polyglot.t(`Display a message when there are no videos.`)}</li>
</ul>
`,
files: diffFilesResolver.resolve('templateAddAction', {
exercise: [files.appComponent, files.appHtml],
reference: [files.appModule, files.main, files.video_videoItem],
test: [files.test],
bootstrap: [files.main],
})
},
{
name: polyglot.t(`Display all videos`),
description: polyglot.t(`Finally let's iterate over the videos.`),
files: diffFilesResolver.resolve('templateAllVideos', {
exercise: [files.appComponent, files.appHtml],
reference: [files.appModule, files.main, files.video_videoItem],
test: [files.test],
bootstrap: [files.main]
})
}
]
},
{
name: polyglot.t(`Dependency Injection`),
exercises: [{
name: polyglot.t(`Intro`),
slide: true,
description: `
<h1>${polyglot.t(`Let's inject a service.`)}</h1>
<p>${polyglot.t(`Using a service is way better than hardcoded data. As a result we get even more cats.`)}</p>
<div class = "inBrowser">
<div class="smaller">
<my-app><div>
<h1>${polyglot.t(`CatTube`)}</h1>
<input placeholder="video" type="text">
<button>${polyglot.t(`Search!`)}</button>
<div>
<h2>${polyglot.t(`Cute kitten`)}</h2>
<img src="/assets/images/cat-0.png">
</div><div>
<h2>${polyglot.t(`Kitten on the tree`)}</h2>
<img src="/assets/images/cat-1.jpg">
</div><div>
<h2>${polyglot.t(`More kitten`)}</h2>
<img src="/assets/images/cat-2.jpg">
</div><div>
<h2>${polyglot.t(`Another kitten`)}</h2>
<img src="/assets/images/cat-3.jpg">
</div><div>
<h2>${polyglot.t(`Serouis cat`)}</h2>
<img src="/assets/images/cat-4.jpg">
</div><div>
<h2>${polyglot.t(`Serouis cat`)}</h2>
<img src="/assets/images/cat-5.jpg">
</div><div>
<h2>${polyglot.t(`Serouis cat`)}</h2>
<img src="/assets/images/cat-6.jpg">
</div>
</div></my-app>
</div>
</div>
`,
}, {
name: polyglot.t(`Service injection`),
description: polyglot.t(`Fetch the videos using a service, instead of having them hardcoded.`),
files: diffFilesResolver.resolve('diInjectService', {
exercise: [files.video_videoService, files.appModule, files.appComponent],
reference: [files.appHtml, files.apiService, files.video_videoItem, files.main],
test: [files.test],
bootstrap: [files.main]
})
}]
},
{
name: polyglot.t(`Component Tree`),
exercises: [
{
name: polyglot.t(`Intro`),
slide: true,
description: `
<h1>${polyglot.t(`Create a Video component!`)}</h1>
<p>${polyglot.t(`Create a separate component with the video information.`)}</p>
<p>${polyglot.t(`Add description, amount of views and likes.`)}</p>
<div class = "inBrowser">
<div class="smaller">
<div>
<h2>${polyglot.t(`Cute kitten`)}</h2>
<img src="/assets/images/cat-0.png">
<div>${polyglot.t(`Date 2016-11-25`)}</div>
<div>${polyglot.t(`Views 100`)}</div>
<div>${polyglot.t(`Likes 20`)}</div>
<div>${polyglot.t(`Description todo`)}</div>
</div>
</div>
</div>
`,
},
{
name: polyglot.t(`Create VideoComponent`),
description: polyglot.t(`Create a video component.`),
files: diffFilesResolver.resolve('videoComponentCreate', {
exercise: [files.video_video_component, files.video_video_html],
reference: [
files.appModule,
files.video_videoService, files.appHtml,
files.appComponent, files.video_videoItem,
files.apiService, files.main
],
test: [files.test],
bootstrap: [files.main]
})
},
{
name: polyglot.t(`Use VideoComponent`),
description: polyglot.t(`Use the VideoComponent in the app.`),
files: diffFilesResolver.resolve('videoComponentUse', {
exercise: [files.appModule, files.appHtml,],
reference: [
files.video_video_html,
files.video_video_component, files.appComponent, files.video_videoService, files.video_videoItem, files.apiService, files.main
],
test: [files.test],
bootstrap: [files.main]
})
}]
}, {
name: polyglot.t(`Custom events`),
exercises: [
{
name: polyglot.t(`Intro`),
slide: true,
description: `
<h1>${polyglot.t(`Let's use custom events!`)}</h1>
<p>${polyglot.t(`Add a ThumbsComponent which will emit an 'onThumbs' event.`)}</p>
<p>${polyglot.t(`In the video component listen to the event and change the amount of likes accordingly.`)}</p>
<div class = "inBrowser">
<div class="smaller">
<div>
<h2>${polyglot.t(`Cute kitten`)}</h2>
<img src="/assets/images/cat-0.png">
<div>${polyglot.t(`Date 2016-11-25`)}</div>
<div>${polyglot.t(`Views 100`)}</div>
<div>${polyglot.t(`Likes 20`)}</div>
<div>${polyglot.t(`Description todo`)}</div>
<button>${polyglot.t(`Thumbs Up`)}</button> <button>${polyglot.t(`Thumbs Down`)}</button>
</div>
</div>
</div>
`,
},
{
name: polyglot.t(`Create ThumbsComponent`),
description: polyglot.t(`Create ThumbsComponent.`),
files: diffFilesResolver.resolve('thumbsComponentCreate', {
exercise: [files.thumbs_thumbs_component, files.thumbs_thumbs_html],
reference: [files.apiService, files.appModule, files.main, files.indexHtml],
test: [files.test],
bootstrap: [files.main]
})
},
{
name: polyglot.t(`Use ThumbsComponent`),
description: polyglot.t(`Use the 'ThumbsComponent' in the app.`),
files: diffFilesResolver.resolve('thumbsComponentUse', {
exercise: [files.video_video_component, files.video_video_html, files.appModule,],
reference: [
files.thumbs_thumbs_component, files.thumbs_thumbs_html, files.appHtml, files.appComponent, files.video_videoService, files.video_videoItem, files.apiService, files.main
],
test: [files.test],
bootstrap: [files.main]
})
}]
}, {
name: polyglot.t(`Content projection`),
exercises: [
{
name: polyglot.t(`Intro`),
slide: true,
description: `
<h1>${polyglot.t(`Let's project some content!`)}</h1>
<p>${polyglot.t(`In this milestone we'll create a component called 'TogglePanel'`)}</p>
<p>${polyglot.t(`It will actually take 2 divs, but only display one at a time.`)}</p>
<div class = "inBrowser">
<div class="smaller">
<div>
<h2>${polyglot.t(`Cute kitten`)}</h2>
<img src="/assets/images/cat-0.png">
<div>${polyglot.t(`This is the description. Once you click 'show meta' button it will be gone. (please don't try clicking it here, I'm just a screenshot)`)}</div>
<div>${polyglot.t(`Show meta`)}</div>
<button>${polyglot.t(`Thumbs Up`)}</button> <button>${polyglot.t(`Thumbs Down`)}</button>
</div>
</div>
</div>
<p>${polyglot.t(`So when you click the 'Show meta button', description is gone, likes and views are displayed instead.`)}</p>
<div class = "inBrowser">
<div class="smaller">
<div>
<h2>${polyglot.t(`Cute kitten`)}</h2>
<img src="/assets/images/cat-0.png">
<div>${polyglot.t(`Views 100`)}</div>
<div>${polyglot.t(`Likes 20`)}</div>
<div>${polyglot.t(`Show description`)}</div>
<button>${polyglot.t(`Thumbs Up`)}</button> <button>${polyglot.t(`Thumbs Down`)}</button>
</div>
</div>
</div>
`
},
{
name: polyglot.t(`Add TogglePanelComponent`),
description: polyglot.t(`Let's create a component which will use content projection to toggle between description and meta information. `),
files: diffFilesResolver.resolve('togglePanelComponentCreate', {
exercise: [files.toggle_panel_toggle_panel, files.toggle_panel_toggle_panel_html],
reference: [files.wrapperComponent, files.apiService, files.appModule, files.main, files.indexHtml],
test: [files.test],
bootstrap: [files.main]
})
},
{
name: polyglot.t(`Use TogglePanelComponent`),
description: polyglot.t(`Now let's use the component.`),
files: diffFilesResolver.resolve('togglePanelComponentUse', {
exercise: [files.video_video_html, files.appModule],
reference: [
files.video_video_component,
files.toggle_panel_toggle_panel,
files.toggle_panel_toggle_panel_html,
files.thumbs_thumbs_component,
files.thumbs_thumbs_html,
files.appHtml,
files.appComponent,
files.video_videoService,
files.video_videoItem,
files.apiService,
files.main
],
test: [files.test],
bootstrap: [files.main]
})
}]
},
/*
{
name: polyglot.t(`Parent-container`),
exercises: [{
name: polyglot.t(`Intro`),
slide: true,
description: polyglot.t(`
<h1>Let's inject parent component!</h1>
<p>In this milestone we'll create create a ContextAdComponent. </p>
<p>This component will not use inputs. Instead it will require parent (Video) component and directly look at it's properties. </p>
<p>It will display different text depending of if there's a word 'music' in the description. </p>
<div class = "inBrowser">
<div class="smaller">
<div>
<h2>Cute kitten dancing</h2>
<img src="/assets/images/cat-0.png">
<div>Decription: music</div>
<button>Show meta</button>
<button>Thumbs Up</button> <button>Thumbs Down</button>
<div>Context ad: Turn up your speakers</div>
</div>
<div>
<h2>Cute kitten sleeping</h2>
<img src="/assets/images/cat-0.png">
<div>Decription: sleeping</div>
<button>Show meta</button>
<button>Thumbs Up</button> <button>Thumbs Down</button>
<div>Context ad: Check out our web site.</div>
</div>
</div>
</div>
<p>Note, we are actually calling it ContextComponent, because when it was called ContextAdComponent, adblock blocked it, and I spent 2 hours debugging. </p>
`),
},
{
name: polyglot.t(`Inject parent component`),
description: polyglot.t(`<p>Create a Context(Ad)Component</p>
<p>Which will inject it's parent component, see what thedescription, and display the value accordingly.</p>
<p>Note: We had to get rid of the 'Ad' part of the component, because AdBlock blocked the template.</p>`),
files: diffFilesResolver.resolve('bootstrap', {
exercise: [files.contextComponent, files.context_context_html],
reference: [
files.contextService,
files.video_video_html,
files.appModule,
files.video_video_component,
files.toggle_panel_toggle_panel,
files.toggle_panel_toggle_panel_html,
files.thumbs_thumbs_component,
files.thumbs_thumbs_html,
files.appHtml,
files.appComponent,
files.video_videoService,
files.video_videoItem,
files.apiService,
files.main
],
test: [files.test],
bootstrap: [files.main]
}),
}]
},
*/
{
name: polyglot.t(`Pipes (bonus)`),
exercises: [{
name: polyglot.t(`Create a pipe`),
description: polyglot.t(`Create a fuzzy pipe, which takes a date in YYYY-MM-DD format, and returns how many days ago this was.`),
files: diffFilesResolver.resolve('fuzzyPipeCreate', {
exercise: [files.fuzzyPipe_fuzzyPipe],
test: [files.test],
bootstrap: [files.main]
})
}, {
name: polyglot.t(`Use the pipe`),
description: polyglot.t(`Now include the app in the module and use in the app.`),
files: diffFilesResolver.resolve('fuzzyPipeUse', {
exercise: [files.appModule, files.video_video_html],
reference: [files.fuzzyPipe_fuzzyPipe,
files.contextService,
files.contextComponent,
files.context_context_html,
files.video_video_component,
files.toggle_panel_toggle_panel,
files.toggle_panel_toggle_panel_html,
files.thumbs_thumbs_component,
files.thumbs_thumbs_html,
files.appHtml,
files.appComponent,
files.video_videoService,
files.video_videoItem,
files.apiService,
files.main
],
test: [files.test],
bootstrap: [files.main]
})
}]
},
{
name: polyglot.t(`Survey`),
exercises: [{
slide: true,
name: polyglot.t(`All done!`),
description: `
<h1>${polyglot.t('This is it for now!')}</h1>
<p>${polyglot.t(`This codelab is really new. We're working on adding more advanced and fun exercises. `)}
<p>${polyglot.t('Meanwhile please fill out <a href = "https://docs.google.com/forms/d/1lGPvmCftArLXVuJkO6L7sXZiqIDj-DtiPM0MQJXLJTA/edit">The survey</a>. This would help us to improve!')}
<p>${polyglot.t('This codelab is written in Angular! <a href = "https://github.com/kirjs/ng2-codelab">Check out the code at this git repo</a>')}
<p>${polyglot.t('If you want to learn more about angular check out <a href = "https://angular.io/">angular.io</a>')}
`
}]
}
]
}; | the_stack |
import { AddressZero, HashZero } from 'ethers/constants';
import { bigNumberify } from 'ethers/utils';
import {
TransactionsMessagesCount,
SubgraphOneTxSubscription,
SubgraphEventsThatAreActionsSubscription,
SubgraphEventsSubscription,
SubgraphMotionsSubscription,
} from '~data/index';
import {
Address,
ColonyActions,
FormattedAction,
FormattedEvent,
ColonyAndExtensionsEvents,
} from '~types/index';
import { ACTIONS_EVENTS } from '~dashboard/ActionsPage/staticMaps';
import { getValuesForActionType } from '~utils/colonyActions';
import { TEMP_getContext, ContextModule } from '~context/index';
import { createAddress, toHex } from '~utils/web3';
import { formatEventName, groupSetUserRolesActions } from '~utils/events';
import { log } from '~utils/debug';
import { ItemStatus } from '~core/ActionsList';
import { shouldDisplayMotion } from '~utils/colonyMotions';
enum FilteredUnformattedAction {
OneTxPayments = 'oneTxPayments',
Events = 'events',
Motions = 'motions',
}
interface ActionsThatNeedAttention {
transactionHash: string;
needsAction: boolean;
}
interface ActionsTransformerMetadata {
extensionAddresses?: Address[];
actionsThatNeedAttention?: ActionsThatNeedAttention[];
}
export const getActionsListData = (
installedExtensionsAddresses: Address[],
unformattedActions?: {
oneTxPayments?: SubgraphOneTxSubscription['oneTxPayments'];
events?: SubgraphEventsThatAreActionsSubscription['events'];
motions?: SubgraphMotionsSubscription['motions'];
},
transactionsCommentsCount?: TransactionsMessagesCount,
{
extensionAddresses,
actionsThatNeedAttention,
}: ActionsTransformerMetadata = {},
): FormattedAction[] => {
let formattedActions = [];
/*
* Filter out the move funds actions that are actually payment actions (before processing)
*
* This happens because internally the oneTxAction also triggers a Move Funds and
* we don't consider that one an action
*
* We only consider an action that we manually trigger ourselves, so if the transaction
* hashes match, throw them out.
*/
const filteredUnformattedActions = {
oneTxPayments:
unformattedActions?.oneTxPayments?.reduce((acc, action) => {
if (
installedExtensionsAddresses?.find(
(extensionAddress) => extensionAddress === action?.agent,
)
) {
return acc;
}
return [...acc, action];
}, []) || [],
events:
unformattedActions?.events?.reduce((acc, event) => {
if (
formatEventName(event.name) ===
ColonyAndExtensionsEvents.DomainMetadata
) {
const linkedDomainAddedEvent = (
unformattedActions?.events || []
).find(
(e) =>
formatEventName(e.name) ===
ColonyAndExtensionsEvents.DomainAdded &&
e.transaction?.hash === event.transaction?.hash,
);
if (linkedDomainAddedEvent) return acc;
}
/* filtering out events that are already shown in `oneTxPayments` */
const isTransactionRepeated = unformattedActions?.oneTxPayments?.some(
(paymentAction) =>
paymentAction.transaction?.hash === event.transaction?.hash,
);
if (isTransactionRepeated) return acc;
/*
* Filter out events that have the recipient or initiator an extension's address
*
* This is used to filter out setting root roles to extensions after
* they have been installed. This also filter out duplicated events
* which occurs when motion is finalized.
*/
if (
extensionAddresses?.find(
(extensionAddress) =>
extensionAddress === event?.processedValues?.user ||
extensionAddress === event?.processedValues?.agent,
)
) {
return acc;
}
return [...acc, event];
}, []) || [],
/*
* Only display motions in the list if their stake reached 10% or
* if they have been escalated
*/
motions:
unformattedActions?.motions?.reduce((acc, motion) => {
const { requiredStake, stakes, escalated } = motion;
const totalNayStake = bigNumberify(stakes[0] || 0);
const totalYayStake = bigNumberify(stakes[1] || 0);
const currentStake = totalNayStake.add(totalYayStake).toString();
const enoughStake = shouldDisplayMotion(currentStake, requiredStake);
if (escalated || enoughStake) {
return [...acc, motion];
}
return acc;
}, []) || [],
};
Object.keys(filteredUnformattedActions || {}).map((subgraphActionType) => {
formattedActions = formattedActions.concat(
(filteredUnformattedActions || {})[subgraphActionType].map(
(unformattedAction) => {
const formatedAction = {
id: unformattedAction.id,
actionType: ColonyActions.Generic,
initiator: AddressZero,
recipient: AddressZero,
amount: '0',
tokenAddress: AddressZero,
symbol: '???',
decimals: '18',
fromDomain: '1',
toDomain: '1',
transactionHash: HashZero,
createdAt: new Date(),
commentCount: 0,
status: undefined,
motionState: undefined,
motionId: undefined,
timeoutPeriods: undefined,
transactionTokenAddress: undefined,
blockNumber: 0,
totalNayStake: '0',
requiredStake: '0',
};
let hash;
let timestamp;
try {
const {
transaction: {
hash: txHash,
block: { timestamp: blockTimestamp, id: blockId },
},
} = unformattedAction;
hash = txHash;
timestamp = blockTimestamp;
formatedAction.blockNumber = parseInt(
blockId.replace('block_', ''),
10,
);
} catch (error) {
log.verbose('Could not deconstruct the subgraph action object');
log.verbose(error);
}
const transactionComments =
/*
* @NOTE Had to disable this as prettier was being too whiny
* and all suggestions it made broke the style rules
*
* This sadly happens from time to time...
*/
// disable-next-list prettier/prettier
transactionsCommentsCount?.colonyTransactionMessages?.find(
({ transactionHash }) => transactionHash === hash,
);
if (subgraphActionType === FilteredUnformattedAction.OneTxPayments) {
try {
const {
payment: {
to: recipient,
domain: { ethDomainId },
fundingPot: {
fundingPotPayouts: [
{
amount,
token: { address: tokenAddress, symbol, decimals },
},
],
},
},
} = unformattedAction;
formatedAction.actionType = ColonyActions.Payment;
formatedAction.recipient = recipient;
formatedAction.fromDomain = ethDomainId;
formatedAction.amount = amount;
formatedAction.tokenAddress = tokenAddress;
formatedAction.symbol = symbol;
formatedAction.decimals = decimals;
if (unformattedAction?.agent) {
formatedAction.initiator = unformattedAction.agent;
}
if (tokenAddress === AddressZero) {
formatedAction.transactionTokenAddress = tokenAddress;
}
} catch (error) {
log.verbose(
'Could not deconstruct the subgraph oneTx action object',
);
log.verbose(error);
}
}
if (transactionsCommentsCount && transactionComments) {
formatedAction.commentCount = transactionComments.count;
}
if (timestamp) {
formatedAction.createdAt = new Date(
/*
* @NOTE blocktime is expressed in seconds, and we need milliseconds
* to instantiate the correct Date object
*/
parseInt(`${timestamp}000`, 10),
);
}
if (subgraphActionType === FilteredUnformattedAction.Events) {
try {
const {
processedValues,
associatedColony: {
colonyAddress,
token: { address: tokenAddress, symbol, decimals },
},
name,
} = unformattedAction;
const actionEvent = Object.entries(ACTIONS_EVENTS).find((el) =>
el[1]?.includes(name.split('(')[0]),
);
const checksummedColonyAddress = createAddress(colonyAddress);
const actionType =
(actionEvent && (actionEvent[0] as ColonyActions)) ||
ColonyActions.Generic;
formatedAction.actionType = actionType;
formatedAction.tokenAddress = tokenAddress;
formatedAction.symbol = symbol;
formatedAction.decimals = decimals;
const actionTypeValues = getValuesForActionType(
processedValues,
actionType,
checksummedColonyAddress,
);
const actionTypeKeys = Object.keys(actionTypeValues);
actionTypeKeys.forEach((key) => {
formatedAction[key] = actionTypeValues[key];
});
} catch (error) {
log.verbose('Could not deconstruct the subgraph event object');
log.verbose(error);
}
}
if (subgraphActionType === FilteredUnformattedAction.Motions) {
const {
args,
agent,
type,
state,
fundamentalChainId,
timeoutPeriods,
stakes,
requiredStake,
} = unformattedAction;
if (args?.token) {
const {
args: {
token: { address: tokenAddress, symbol, decimals },
},
} = unformattedAction;
formatedAction.tokenAddress = tokenAddress;
formatedAction.symbol = symbol;
formatedAction.decimals = decimals;
}
formatedAction.initiator = agent;
formatedAction.actionType = type;
formatedAction.motionState = state;
formatedAction.motionId = fundamentalChainId;
formatedAction.timeoutPeriods = timeoutPeriods;
formatedAction.totalNayStake = bigNumberify(
stakes[0] || 0,
).toString();
formatedAction.requiredStake = requiredStake;
if (args) {
const actionTypeKeys = Object.keys(args);
actionTypeKeys.forEach((key) => {
formatedAction[key] = args[key];
});
}
}
formatedAction.transactionHash = hash;
return formatedAction;
},
),
);
return null;
});
const formattedGroupedActions = groupSetUserRolesActions(formattedActions);
/*
* @NOTE Filter out the initial 'Colony Edit' action, if it comes from the
* network contract (not the current colony).
*
* This is the first edit action that gets created, and shares the same
* transaction hash with the 'Domain Added' action (basically all actions
* that get created intially, when creating a new colony, will share the
* same tx hash)
*
* Since we can't link to two separate actions on the same hash, we filter
* out one of them, as since the metadata change is less important (and it's
* not actually a change, but a "set") we filter it out
*/
const filteredActions = formattedGroupedActions.filter(
({ initiator, actionType }: FormattedAction) => {
/*
* @NOTE This is wrapped inside a try/catch block since if the user logs out,
* for a brief moment the colony manager won't exist
*
* If that's at the same time as this filter runs, it will error out, so we
* prevent that by just returning an empty list
*
* How I **hate** race conditions
*/
try {
const colonyManager = TEMP_getContext(ContextModule.ColonyManager);
if (
colonyManager?.networkClient &&
actionType === ColonyActions.ColonyEdit
) {
return (
initiator !== colonyManager?.networkClient.address.toLowerCase()
);
}
return true;
} catch (error) {
return false;
}
},
);
/*
* Assign the NeedsAction status to whichever action needs it
*
* I wish I could merge this extra map with the other processing steps
* but for one it's kinda complex and would make the code read harder
* and second, we need to wait until we've processed everything else in order
* to determine which actions need a status change.
*
* The good part is, that this will trigger **only** if we have actions that
* need actions, otherwise, it will skip the extra map
*/
if (actionsThatNeedAttention?.length) {
return filteredActions.map((action) => {
const { transactionHash: currentActionTransactionHash } = action;
const potentialNeedsAction = actionsThatNeedAttention.find(
({ transactionHash }) =>
transactionHash === currentActionTransactionHash,
);
if (potentialNeedsAction) {
return {
...action,
status: potentialNeedsAction.needsAction
? ItemStatus.NeedAction
: undefined,
};
}
return action;
});
}
return filteredActions;
};
export const getEventsListData = (
unformattedEvents?: SubgraphEventsSubscription,
): FormattedEvent[] | undefined =>
unformattedEvents?.events?.reduce((processedEvents, event) => {
if (!event) {
return processedEvents;
}
try {
const {
id,
associatedColony: { colonyAddress },
transaction: {
hash,
block: { timestamp },
},
name,
args,
} = event;
const {
agent,
creator,
staker,
escalator,
domainId,
newDomainId,
recipient,
fundingPotId,
metadata,
token,
paymentId,
amount,
payoutRemainder,
decimals = '18',
role,
setTo,
user,
extensionId,
version,
oldVersion,
newVersion,
slot,
toValue,
motionId,
vote,
} = JSON.parse(args || '{}');
const checksummedColonyAddress = createAddress(colonyAddress);
const getRecipient = () => {
if (recipient) {
return createAddress(recipient);
}
if (user) {
return user;
}
return checksummedColonyAddress;
};
const getAgent = () => {
const userAddress = agent || user || creator || staker || escalator;
if (userAddress) {
return createAddress(userAddress);
}
return checksummedColonyAddress;
};
return [
...processedEvents,
{
id,
agent: getAgent(),
eventName: formatEventName(name),
transactionHash: hash,
colonyAddress: checksummedColonyAddress,
createdAt: new Date(parseInt(`${timestamp}000`, 10)),
displayValues: args,
domainId: domainId || null,
newDomainId: newDomainId || null,
recipient: getRecipient(),
fundingPot: fundingPotId,
metadata,
tokenAddress: token ? createAddress(token) : null,
paymentId,
decimals: parseInt(decimals, 10),
amount: amount || payoutRemainder || '0',
role,
setTo: setTo === 'true',
extensionHash: extensionId,
extensionVersion: version,
oldVersion: oldVersion || '0',
newVersion: newVersion || '0',
storageSlot: slot ? toHex(parseInt(slot, 10)) : '0',
storageSlotValue: toValue || AddressZero,
motionId,
vote,
},
];
} catch (error) {
log.verbose('Could not deconstruct the subgraph event object');
log.verbose(error);
return processedEvents;
}
}, []); | the_stack |
import { stylePropsText, stylePropsTransform, validPseudoKeys, validStyles } from '@tamagui/helpers'
// @ts-ignore
import { useInsertionEffect } from 'react'
import { ViewStyle } from 'react-native'
import { getConfig } from '../conf'
import { isClient, isWeb, useIsomorphicLayoutEffect } from '../constants/platform'
import { mediaQueryConfig, mediaState } from '../hooks/useMedia'
import {
MediaKeys,
MediaQueryKey,
PseudoStyles,
PsuedoPropKeys,
SplitStyleState,
StackProps,
StaticConfigParsed,
TamaguiInternalConfig,
ThemeObject,
} from '../types'
import { createMediaStyle } from './createMediaStyle'
import { fixNativeShadow } from './fixNativeShadow'
import { getStylesAtomic, psuedoCNInverse } from './getStylesAtomic'
import {
insertStyleRule,
insertedTransforms,
updateInserted,
updateInsertedCache,
} from './insertStyleRule'
import { mergeTransform } from './mergeTransform'
export type SplitStyles = ReturnType<typeof getSplitStyles>
export type ClassNamesObject = Record<string, string>
export type SplitStyleResult = ReturnType<typeof getSplitStyles>
const skipProps = {
animation: true,
animateOnly: true,
debug: true,
componentName: true,
...(!isWeb && {
tag: true,
whiteSpace: true,
wordWrap: true,
textOverflow: true,
textDecorationDistance: true,
userSelect: true,
selectable: true,
cursor: true,
contain: true,
pointerEvents: true,
boxSizing: true,
boxShadow: true,
}),
}
type TransformNamespaceKey = 'transform' | PsuedoPropKeys | MediaQueryKey
let conf: TamaguiInternalConfig
type StyleSplitter = (
props: { [key: string]: any },
staticConfig: StaticConfigParsed,
theme: ThemeObject,
state: SplitStyleState & {
keepVariantsAsProps?: boolean
},
defaultClassNames?: any
) => {
pseudos: PseudoStyles
medias: Record<MediaKeys, ViewStyle>
style: ViewStyle
classNames: ClassNamesObject
rulesToInsert: [string, string][]
viewProps: StackProps
}
// loop props backwards
// track used keys:
// const keys = new Set<string>()
// keep classnames and styles separate:
// const styles = {}
// const classNames = {}
export const getSplitStyles: StyleSplitter = (
props,
staticConfig,
theme,
state,
defaultClassNames
) => {
conf = conf || getConfig()
const validStyleProps = staticConfig.isText ? stylePropsText : validStyles
const viewProps: StackProps = {}
const pseudos: PseudoStyles = {}
const medias: Record<MediaKeys, ViewStyle> = {}
const usedKeys = new Set<string>()
let style: ViewStyle = {}
let classNames: ClassNamesObject = {}
// we need to gather these specific to each media query / pseudo
// value is [hash, val], so ["-jnjad-asdnjk", "scaleX(1) rotate(10deg)"]
let transforms: Record<TransformNamespaceKey, [string, string]> = {}
const rulesToInsert: [string, string][] = []
function addStyle(prop: string, rule: string) {
rulesToInsert.push([prop, rule])
updateInsertedCache(prop, rule)
}
function mergeClassName(key: string, val: string, isMediaOrPseudo = false) {
// empty classnames passed by compiler sometimes
if (!val) return
if (val.startsWith('_transform-')) {
// const isMediaOrPseudo = key !== 'transform'
// const isMedia = isMediaOrPseudo && key[11] === '_'
// const isPsuedo = (isMediaOrPseudo && key[11] === '0') || key.endsWith('Style')
const namespace: TransformNamespaceKey = isMediaOrPseudo ? key : 'transform'
let transform = insertedTransforms[val]
if (isClient) {
if (!transform) {
// HMR or loaded a new chunk
updateInserted()
transform = insertedTransforms[val]
}
if (!transform) {
if (isWeb && val[0] !== '_') {
// runtime insert
transform = val
} else {
// shouldn't reach
}
}
if (process.env.NODE_ENV === 'development' && props['debug'] === 'verbose') {
// prettier-ignore
console.log(' » getSplitStyles mergeClassName transform', { key, val, namespace, transform, insertedTransforms })
}
}
transforms[namespace] = transforms[namespace] || ['', '']
const identifier = val.replace('_transform', '')
transforms[namespace][0] += identifier
// ssr doesn't need to do anything just make the right classname
if (transform) {
transforms[namespace][1] += transform
}
} else {
classNames[key] = val
}
}
const propKeys = Object.keys(props)
for (let i = propKeys.length - 1; i >= 0; i--) {
const keyInit = propKeys[i]
if (usedKeys.has(keyInit)) continue
if (skipProps[keyInit]) continue
if (!isWeb && keyInit.startsWith('data-')) continue
const valInit = props[keyInit]
if (keyInit === 'style' || keyInit.startsWith('_style')) {
if (!valInit) continue
for (const key in valInit) {
if (usedKeys.has(key)) continue
if (valInit && typeof valInit === 'object') {
// newer react native versions return a full object instead of ID
for (const skey in valInit) {
if (usedKeys.has(skey)) continue
usedKeys.add(skey)
style[skey] = valInit[skey]
}
} else {
usedKeys.add(key)
style[key] = valInit
}
}
continue
}
if (keyInit === 'className') {
let nonTamaguis = ''
if (!valInit) {
continue
}
for (const cn of valInit.split(' ')) {
if (cn[0] === '_') {
// tamagui, merge it expanded on key, eventually this will go away with better compiler
const [shorthand, mediaOrPsuedo] = cn.slice(1).split('-')
const isMedia = mediaOrPsuedo[0] === '_'
const isPseudo = mediaOrPsuedo[0] === '0'
const isMediaOrPseudo = isMedia || isPseudo
let fullKey = conf.shorthands[shorthand]
if (isMedia) {
// is media
let mediaShortKey = mediaOrPsuedo.slice(1)
mediaShortKey = mediaShortKey.slice(0, mediaShortKey.indexOf('_'))
fullKey += `-${mediaShortKey}`
} else if (isPseudo) {
// is psuedo
const pseudoShortKey = mediaOrPsuedo.slice(1)
fullKey += `-${psuedoCNInverse[pseudoShortKey]}`
}
usedKeys.add(fullKey)
mergeClassName(fullKey, cn, isMediaOrPseudo)
} else {
nonTamaguis += ' ' + cn
}
}
if (nonTamaguis) {
mergeClassName(keyInit, nonTamaguis)
}
continue
}
if (validStyleProps[keyInit] && valInit && valInit[0] === '_') {
usedKeys.add(keyInit)
mergeClassName(keyInit, valInit)
continue
}
if (
state.keepVariantsAsProps &&
staticConfig.defaultVariants &&
keyInit in staticConfig.defaultVariants
) {
viewProps[keyInit] = valInit
}
let isMedia = keyInit[0] === '$'
let isPseudo = validPseudoKeys[keyInit]
if (
!isMedia &&
!isPseudo &&
!staticConfig.variants?.[keyInit] &&
!validStyleProps[keyInit] &&
!conf.shorthands[keyInit]
) {
usedKeys.add(keyInit)
viewProps[keyInit] = valInit
continue
}
const expanded =
isMedia || isPseudo
? [[keyInit, valInit]]
: staticConfig.propMapper(keyInit, valInit, theme, props, state)
let isMediaOrPseudo = isMedia || isPseudo
if (process.env.NODE_ENV === 'development' && props['debug'] === 'verbose') {
console.log(' » getSplitStyles', keyInit, expanded)
}
if (!expanded) {
continue
}
for (const [key, val] of expanded) {
if (val === undefined) continue
if (key !== 'target' && val && val[0] === '_') {
usedKeys.add(key)
mergeClassName(key, val, isMediaOrPseudo)
continue
}
isMedia = key[0] === '$'
isPseudo = validPseudoKeys[key]
isMediaOrPseudo = isMedia || isPseudo
if (!isMediaOrPseudo) {
if (usedKeys.has(key)) continue
}
if (
(staticConfig.deoptProps && staticConfig.deoptProps.has(key)) ||
(staticConfig.inlineProps && staticConfig.inlineProps.has(key))
) {
viewProps[key] = val
}
// pseudo
if (isPseudo) {
if (!val) continue
if (key === 'enterStyle' && state.mounted) {
// once mounted we can ignore enterStyle
continue
}
pseudos[key] = pseudos[key] || {}
pseudos[key] = getSubStyle(val, staticConfig, theme, props, state, true)
if (isWeb && !state.noClassNames) {
const pseudoStyles = getStylesAtomic({ [key]: pseudos[key] })
for (const style of pseudoStyles) {
const fullKey = `${style.property}-${key}`
if (!usedKeys.has(fullKey)) {
usedKeys.add(fullKey)
addStyle(style.identifier, style.rules[0])
mergeClassName(fullKey, style.identifier, isMediaOrPseudo)
}
}
}
continue
}
// media
if (isMedia) {
const mediaKey = key
const mediaKeyShort = mediaKey.slice(1)
if (!mediaQueryConfig[mediaKeyShort]) {
// this isn't a media key, pass through
viewProps[key] = val
continue
}
// dont check if media is active, we just apply *all* media styles
// we combine the media props on top regular props, could proxy this
// TODO test proxy here instead of merge
// THIS USED TO PROXY BACK TO REGULAR PROPS BUT THAT IS THE WRONG BEHAVIOR
// we avoid passing in default props for media queries because that would confuse things like SizableText.size:
const mediaStyle = getSubStyle(val, staticConfig, theme, props, state)
const shouldDoClasses = isWeb && !state.noClassNames
if (process.env.NODE_ENV === 'development' && props['debug'] === 'verbose') {
// prettier-ignore
console.log(' » getSplitStyles mediaStyle', { mediaKey, mediaStyle, props, shouldDoClasses })
}
if (shouldDoClasses) {
const mediaStyles = getStylesAtomic(mediaStyle)
for (const style of mediaStyles) {
const out = createMediaStyle(style, mediaKeyShort, mediaQueryConfig)
// TODO handle psuedo + media, not too hard just need to set up example case
const fullKey = `${style.property}-${mediaKeyShort}`
if (!usedKeys.has(fullKey)) {
usedKeys.add(fullKey)
addStyle(out.identifier, out.styleRule)
mergeClassName(fullKey, out.identifier, true)
}
}
} else {
if (mediaState[mediaKey]) {
if (process.env.NODE_ENV === 'development' && props['debug']) {
console.log('apply media style', mediaKey, mediaState)
}
Object.assign(shouldDoClasses ? medias : style, mediaStyle)
}
}
continue
}
if (!isWeb && key === 'pointerEvents') {
usedKeys.add(key)
viewProps[key] = val
continue
}
if (validStyleProps[key]) {
usedKeys.add(key)
if (val && val[0] === '_') {
classNames[key] = val
} else {
if (key in stylePropsTransform) {
if (process.env.NODE_ENV === 'development' && props['debug']) {
console.log('mergeTransform', key, val)
}
mergeTransform(style, key, val, true)
} else {
style[key] = val
}
}
continue
}
// pass to view props
if (!staticConfig.variants || !(key in staticConfig.variants)) {
if (!skipProps[key]) {
// push()
viewProps[key] = val
usedKeys.add(key)
}
}
}
}
// add in defaults if not set:
if (defaultClassNames) {
classNames = {
...defaultClassNames,
...classNames,
}
}
if (isWeb && !state.noClassNames) {
const atomic = getStylesAtomic(style)
for (const atomicStyle of atomic) {
const key = atomicStyle.property
if (!state.dynamicStylesInline) {
addStyle(atomicStyle.identifier, atomicStyle.rules[0])
mergeClassName(key, atomicStyle.identifier)
} else {
style[key] = atomicStyle.value
}
}
}
if (transforms) {
for (const namespace in transforms) {
const [hash, val] = transforms[namespace]
const identifier = `_transform${hash}`
if (isClient) {
if (!insertedTransforms[identifier]) {
const rule = `.${identifier} { transform: ${val}; }`
addStyle(identifier, rule)
}
}
classNames[namespace] = identifier
}
}
if (process.env.NODE_ENV === 'development' && props['debug'] === 'verbose') {
if (typeof document !== 'undefined') {
// prettier-ignore
console.log(' » getSplitStyles out', { style, pseudos, medias, classNames, viewProps, state })
}
}
return {
viewProps,
style,
medias,
pseudos,
classNames,
rulesToInsert,
}
}
export const insertSplitStyles: StyleSplitter = (...args) => {
const res = getSplitStyles(...args)
for (const [prop, rule] of res.rulesToInsert) {
insertStyleRule(prop, rule)
}
return res
}
const effect = isWeb ? useInsertionEffect || useIsomorphicLayoutEffect : useIsomorphicLayoutEffect
export const useSplitStyles: StyleSplitter = (...args) => {
const res = getSplitStyles(...args)
effect(() => {
for (const [prop, rule] of res.rulesToInsert) {
insertStyleRule(prop, rule)
}
})
return res
}
export const getSubStyle = (
styleIn: Object,
staticConfig: StaticConfigParsed,
theme: ThemeObject,
props: any,
state: SplitStyleState,
avoidDefaultProps?: boolean
): ViewStyle => {
const styleOut: ViewStyle = {}
for (const key in styleIn) {
const val = styleIn[key]
const expanded = staticConfig.propMapper(key, val, theme, props, state, avoidDefaultProps)
if (!expanded) continue
for (const [skey, sval] of expanded) {
if (skey in stylePropsTransform) {
mergeTransform(styleOut, skey, sval)
} else {
styleOut[skey] = sval
}
}
}
return styleOut
}
export function normalizeStyleObject(style: any) {
if (!isWeb) {
fixNativeShadow(style)
}
} | the_stack |
import {AttributePath} from "./AttributePath";
import {AttributeValue} from "./AttributeValue";
import {ExpressionAttributes} from "./ExpressionAttributes";
import {FunctionExpression} from "./FunctionExpression";
export type ComparisonOperand = AttributePath|AttributeValue|FunctionExpression|any;
export interface BinaryComparisonPredicate {
/**
* The value against which the comparison subject will be compared.
*/
object: ComparisonOperand;
}
/**
* A comparison predicate asserting that the subject and object are equal.
*/
export interface EqualityExpressionPredicate extends BinaryComparisonPredicate {
type: 'Equals';
}
/**
* Create an expression predicate asserting that the subject is equal to the
* predicate.
*/
export function equals(
operand: ComparisonOperand
): EqualityExpressionPredicate {
return {
type: 'Equals',
object: operand,
};
}
/**
* A comparison predicate asserting that the subject and object are not equal.
*/
export interface InequalityExpressionPredicate extends BinaryComparisonPredicate {
type: 'NotEquals';
}
export function notEquals(
operand: ComparisonOperand
): InequalityExpressionPredicate {
return {
type: 'NotEquals',
object: operand,
}
}
/**
* A comparison predicate asserting that the subject is less than the object.
*/
export interface LessThanExpressionPredicate extends BinaryComparisonPredicate {
type: 'LessThan';
}
export function lessThan(
operand: ComparisonOperand
): LessThanExpressionPredicate {
return {
type: 'LessThan',
object: operand,
}
}
/**
* A comparison predicate asserting that the subject is less than or equal to
* the object.
*/
export interface LessThanOrEqualToExpressionPredicate extends BinaryComparisonPredicate {
type: 'LessThanOrEqualTo';
}
export function lessThanOrEqualTo(
operand: ComparisonOperand
): LessThanOrEqualToExpressionPredicate {
return {
type: 'LessThanOrEqualTo',
object: operand,
}
}
/**
* A comparison predicate asserting that the subject is greater than the object.
*/
export interface GreaterThanExpressionPredicate extends BinaryComparisonPredicate {
type: 'GreaterThan';
}
export function greaterThan(
operand: ComparisonOperand
): GreaterThanExpressionPredicate {
return {
type: 'GreaterThan',
object: operand,
}
}
/**
* A comparison predicate asserting that the subject is greater than or equal
* to the object.
*/
export interface GreaterThanOrEqualToExpressionPredicate extends BinaryComparisonPredicate {
type: 'GreaterThanOrEqualTo';
}
export function greaterThanOrEqualTo(
operand: ComparisonOperand
): GreaterThanOrEqualToExpressionPredicate {
return {
type: 'GreaterThanOrEqualTo',
object: operand,
}
}
/**
* A comparison predicate asserting that the subject is between two bounds.
*/
export interface BetweenExpressionPredicate {
type: 'Between';
lowerBound: ComparisonOperand;
upperBound: ComparisonOperand;
}
export function between(
lowerBound: ComparisonOperand,
upperBound: ComparisonOperand
): BetweenExpressionPredicate {
return {
type: 'Between',
lowerBound,
upperBound,
}
}
/**
* A comparison predicate asserting that the subject is equal to any member of
* the provided list of values.
*/
export interface MembershipExpressionPredicate {
type: 'Membership';
values: Array<ComparisonOperand>;
}
export function inList(
...operands: Array<ComparisonOperand>
): MembershipExpressionPredicate {
return {
type: 'Membership',
values: operands,
}
}
/**
* An object structure used as the base of all function expression predicates.
*/
export interface BaseFunctionExpressionPredicate {
type: 'Function';
name: string;
}
/**
* A comparison predicate asserting that the subject is contained in a given
* record.
*/
export interface AttributeExistsPredicate extends
BaseFunctionExpressionPredicate
{
name: 'attribute_exists';
}
export function attributeExists(): AttributeExistsPredicate {
return {
type: 'Function',
name: 'attribute_exists',
};
}
/**
* A comparison predicate asserting that the subject is **not** contained in a
* given record.
*/
export interface AttributeNotExistsPredicate extends
BaseFunctionExpressionPredicate
{
name: 'attribute_not_exists';
}
export function attributeNotExists(): AttributeNotExistsPredicate {
return {
type: 'Function',
name: 'attribute_not_exists',
};
}
export type AttributeType = 'S'|'SS'|'N'|'NS'|'B'|'BS'|'BOOL'|'NULL'|'L'|'M';
/**
* A comparison predicate asserting that the subject is of the specified type.
*/
export interface AttributeTypePredicate extends
BaseFunctionExpressionPredicate
{
name: 'attribute_type';
expected: AttributeType;
}
export function attributeType(expected: AttributeType): AttributeTypePredicate {
return {
type: 'Function',
name: 'attribute_type',
expected,
};
}
/**
* A comparison predicate asserting that the value of the subject in a given
* record begins with the specified string.
*/
export interface BeginsWithPredicate extends
BaseFunctionExpressionPredicate
{
name: 'begins_with';
expected: string;
}
export function beginsWith(expected: string): BeginsWithPredicate {
return {
type: 'Function',
name: 'begins_with',
expected,
};
}
/**
* A comparison predicate asserting that the value of the subject in a given
* record contains the specified string.
*/
export interface ContainsPredicate extends
BaseFunctionExpressionPredicate
{
name: 'contains';
expected: string;
}
export function contains(expected: string): ContainsPredicate {
return {
type: 'Function',
name: 'contains',
expected,
};
}
export type FunctionExpressionPredicate =
AttributeExistsPredicate |
AttributeNotExistsPredicate |
AttributeTypePredicate |
BeginsWithPredicate |
ContainsPredicate;
export type ConditionExpressionPredicate =
EqualityExpressionPredicate |
InequalityExpressionPredicate |
LessThanExpressionPredicate |
LessThanOrEqualToExpressionPredicate |
GreaterThanExpressionPredicate |
GreaterThanExpressionPredicate |
GreaterThanOrEqualToExpressionPredicate |
BetweenExpressionPredicate |
MembershipExpressionPredicate |
FunctionExpressionPredicate;
/**
* Evaluate whether the provided value is a condition expression predicate.
*/
export function isConditionExpressionPredicate(
arg: any
): arg is ConditionExpressionPredicate {
if (arg && typeof arg === 'object') {
switch (arg.type) {
case 'Equals':
case 'NotEquals':
case 'LessThan':
case 'LessThanOrEqualTo':
case 'GreaterThan':
case 'GreaterThanOrEqualTo':
return arg.object !== undefined;
case 'Between':
return arg.lowerBound !== undefined
&& arg.upperBound !== undefined;
case 'Membership':
return Array.isArray(arg.values);
case 'Function':
switch (arg.name) {
case 'attribute_exists':
case 'attribute_not_exists':
return true;
case 'attribute_type':
case 'begins_with':
case 'contains':
return typeof arg.expected === 'string';
}
}
}
return false;
}
export interface ConditionExpressionSubject {
/**
* The path to the item attribute containing the subject of the comparison.
*/
subject: AttributePath|string;
}
export function isConditionExpressionSubject(
arg: any
): arg is ConditionExpressionSubject {
return Boolean(arg)
&& typeof arg === 'object'
&& (typeof arg.subject === 'string' || AttributePath.isAttributePath(arg.subject));
}
export type SimpleConditionExpression = ConditionExpressionSubject &
ConditionExpressionPredicate;
export type ConditionExpression =
SimpleConditionExpression |
AndExpression |
OrExpression |
NotExpression |
FunctionExpression;
/**
* A comparison expression asserting that all conditions in the provided list
* are true.
*/
export interface AndExpression {
type: 'And';
conditions: Array<ConditionExpression>;
}
/**
* A comparison expression asserting that one or more conditions in the provided
* list are true.
*/
export interface OrExpression {
type: 'Or';
conditions: Array<ConditionExpression>;
}
/**
* A comparison expression asserting that the provided condition is not true.
*/
export interface NotExpression {
type: 'Not';
condition: ConditionExpression;
}
/**
* Evaluates whether the provided value is a condition expression.
*/
export function isConditionExpression(arg: any): arg is ConditionExpression {
if (FunctionExpression.isFunctionExpression(arg)) {
return true;
}
if (Boolean(arg) && typeof arg === 'object') {
switch (arg.type) {
case 'Not':
return isConditionExpression(arg.condition);
case 'And':
case 'Or':
if (Array.isArray(arg.conditions)) {
for (const condition of arg.conditions) {
if (!isConditionExpression(condition)) {
return false;
}
}
return true;
}
return false;
default:
return isConditionExpressionSubject(arg)
&& isConditionExpressionPredicate(arg);
}
}
return false;
}
/**
* Convert the provided condition expression object to a string, escaping any
* values and attributes to expression-safe placeholders whose expansion value
* will be managed by the provided ExpressionAttributes object.
*/
export function serializeConditionExpression(
condition: ConditionExpression,
attributes: ExpressionAttributes
): string {
if (FunctionExpression.isFunctionExpression(condition)) {
return condition.serialize(attributes);
}
switch (condition.type) {
case 'Equals':
return serializeBinaryComparison(condition, attributes, '=');
case 'NotEquals':
return serializeBinaryComparison(condition, attributes, '<>');
case 'LessThan':
return serializeBinaryComparison(condition, attributes, '<');
case 'LessThanOrEqualTo':
return serializeBinaryComparison(condition, attributes, '<=');
case 'GreaterThan':
return serializeBinaryComparison(condition, attributes, '>');
case 'GreaterThanOrEqualTo':
return serializeBinaryComparison(condition, attributes, '>=');
case 'Between':
return `${
attributes.addName(condition.subject)
} BETWEEN ${
serializeOperand(condition.lowerBound, attributes)
} AND ${
serializeOperand(condition.upperBound, attributes)
}`;
case 'Membership':
return `${
attributes.addName(condition.subject)
} IN (${
condition.values.map(val => serializeOperand(val, attributes))
.join(', ')
})`;
case 'Function':
const subject = AttributePath.isAttributePath(condition.subject)
? condition.subject
: new AttributePath(condition.subject);
switch (condition.name) {
case 'attribute_exists':
case 'attribute_not_exists':
return (new FunctionExpression(condition.name, subject))
.serialize(attributes);
case 'attribute_type':
case 'begins_with':
case 'contains':
return (new FunctionExpression(
condition.name,
subject,
condition.expected
))
.serialize(attributes);
}
case 'Not':
return `NOT (${
serializeConditionExpression(condition.condition, attributes)
})`;
case 'And':
case 'Or':
if (condition.conditions.length === 1) {
return serializeConditionExpression(
condition.conditions[0],
attributes
);
}
return condition.conditions
.map(cond => `(${serializeConditionExpression(cond, attributes)})`)
.join(` ${condition.type.toUpperCase()} `);
}
}
function serializeBinaryComparison(
cond: BinaryComparisonPredicate & ConditionExpressionSubject,
attributes: ExpressionAttributes,
comparator: string
): string {
return `${
attributes.addName(cond.subject)
} ${comparator} ${
serializeOperand(cond.object, attributes)
}`;
}
function serializeOperand(
operand: ComparisonOperand,
attributes: ExpressionAttributes
): string {
if (FunctionExpression.isFunctionExpression(operand)) {
return operand.serialize(attributes);
}
return AttributePath.isAttributePath(operand)
? attributes.addName(operand)
: attributes.addValue(operand);
} | the_stack |
export const enum CharCode {
Null = 0,
/**
* The `\b` character.
*/
Backspace = 8,
/**
* The `\t` character.
*/
Tab = 9,
/**
* The `\n` character.
*/
LineFeed = 10,
/**
* The `\r` character.
*/
CarriageReturn = 13,
Space = 32,
/**
* The `!` character.
*/
ExclamationMark = 33,
/**
* The `"` character.
*/
DoubleQuote = 34,
/**
* The `#` character.
*/
Hash = 35,
/**
* The `$` character.
*/
DollarSign = 36,
/**
* The `%` character.
*/
PercentSign = 37,
/**
* The `&` character.
*/
Ampersand = 38,
/**
* The `'` character.
*/
SingleQuote = 39,
/**
* The `(` character.
*/
OpenParen = 40,
/**
* The `)` character.
*/
CloseParen = 41,
/**
* The `*` character.
*/
Asterisk = 42,
/**
* The `+` character.
*/
Plus = 43,
/**
* The `,` character.
*/
Comma = 44,
/**
* The `-` character.
*/
Dash = 45,
/**
* The `.` character.
*/
Period = 46,
/**
* The `/` character.
*/
Slash = 47,
Digit0 = 48,
Digit1 = 49,
Digit2 = 50,
Digit3 = 51,
Digit4 = 52,
Digit5 = 53,
Digit6 = 54,
Digit7 = 55,
Digit8 = 56,
Digit9 = 57,
/**
* The `:` character.
*/
Colon = 58,
/**
* The `;` character.
*/
Semicolon = 59,
/**
* The `<` character.
*/
LessThan = 60,
/**
* The `=` character.
*/
Equals = 61,
/**
* The `>` character.
*/
GreaterThan = 62,
/**
* The `?` character.
*/
QuestionMark = 63,
/**
* The `@` character.
*/
AtSign = 64,
A = 65,
B = 66,
C = 67,
D = 68,
E = 69,
F = 70,
G = 71,
H = 72,
I = 73,
J = 74,
K = 75,
L = 76,
M = 77,
N = 78,
O = 79,
P = 80,
Q = 81,
R = 82,
S = 83,
T = 84,
U = 85,
V = 86,
W = 87,
X = 88,
Y = 89,
Z = 90,
/**
* The `[` character.
*/
OpenSquareBracket = 91,
/**
* The `\` character.
*/
Backslash = 92,
/**
* The `]` character.
*/
CloseSquareBracket = 93,
/**
* The `^` character.
*/
Caret = 94,
/**
* The `_` character.
*/
Underline = 95,
/**
* The ``(`)`` character.
*/
BackTick = 96,
a = 97,
b = 98,
c = 99,
d = 100,
e = 101,
f = 102,
g = 103,
h = 104,
i = 105,
j = 106,
k = 107,
l = 108,
m = 109,
n = 110,
o = 111,
p = 112,
q = 113,
r = 114,
s = 115,
t = 116,
u = 117,
v = 118,
w = 119,
x = 120,
y = 121,
z = 122,
/**
* The `{` character.
*/
OpenCurlyBrace = 123,
/**
* The `|` character.
*/
Pipe = 124,
/**
* The `}` character.
*/
CloseCurlyBrace = 125,
/**
* The `~` character.
*/
Tilde = 126,
U_Combining_Grave_Accent = 0x0300, // U+0300 Combining Grave Accent
U_Combining_Acute_Accent = 0x0301, // U+0301 Combining Acute Accent
U_Combining_Circumflex_Accent = 0x0302, // U+0302 Combining Circumflex Accent
U_Combining_Tilde = 0x0303, // U+0303 Combining Tilde
U_Combining_Macron = 0x0304, // U+0304 Combining Macron
U_Combining_Overline = 0x0305, // U+0305 Combining Overline
U_Combining_Breve = 0x0306, // U+0306 Combining Breve
U_Combining_Dot_Above = 0x0307, // U+0307 Combining Dot Above
U_Combining_Diaeresis = 0x0308, // U+0308 Combining Diaeresis
U_Combining_Hook_Above = 0x0309, // U+0309 Combining Hook Above
U_Combining_Ring_Above = 0x030A, // U+030A Combining Ring Above
U_Combining_Double_Acute_Accent = 0x030B, // U+030B Combining Double Acute Accent
U_Combining_Caron = 0x030C, // U+030C Combining Caron
U_Combining_Vertical_Line_Above = 0x030D, // U+030D Combining Vertical Line Above
U_Combining_Double_Vertical_Line_Above = 0x030E, // U+030E Combining Double Vertical Line Above
U_Combining_Double_Grave_Accent = 0x030F, // U+030F Combining Double Grave Accent
U_Combining_Candrabindu = 0x0310, // U+0310 Combining Candrabindu
U_Combining_Inverted_Breve = 0x0311, // U+0311 Combining Inverted Breve
U_Combining_Turned_Comma_Above = 0x0312, // U+0312 Combining Turned Comma Above
U_Combining_Comma_Above = 0x0313, // U+0313 Combining Comma Above
U_Combining_Reversed_Comma_Above = 0x0314, // U+0314 Combining Reversed Comma Above
U_Combining_Comma_Above_Right = 0x0315, // U+0315 Combining Comma Above Right
U_Combining_Grave_Accent_Below = 0x0316, // U+0316 Combining Grave Accent Below
U_Combining_Acute_Accent_Below = 0x0317, // U+0317 Combining Acute Accent Below
U_Combining_Left_Tack_Below = 0x0318, // U+0318 Combining Left Tack Below
U_Combining_Right_Tack_Below = 0x0319, // U+0319 Combining Right Tack Below
U_Combining_Left_Angle_Above = 0x031A, // U+031A Combining Left Angle Above
U_Combining_Horn = 0x031B, // U+031B Combining Horn
U_Combining_Left_Half_Ring_Below = 0x031C, // U+031C Combining Left Half Ring Below
U_Combining_Up_Tack_Below = 0x031D, // U+031D Combining Up Tack Below
U_Combining_Down_Tack_Below = 0x031E, // U+031E Combining Down Tack Below
U_Combining_Plus_Sign_Below = 0x031F, // U+031F Combining Plus Sign Below
U_Combining_Minus_Sign_Below = 0x0320, // U+0320 Combining Minus Sign Below
U_Combining_Palatalized_Hook_Below = 0x0321, // U+0321 Combining Palatalized Hook Below
U_Combining_Retroflex_Hook_Below = 0x0322, // U+0322 Combining Retroflex Hook Below
U_Combining_Dot_Below = 0x0323, // U+0323 Combining Dot Below
U_Combining_Diaeresis_Below = 0x0324, // U+0324 Combining Diaeresis Below
U_Combining_Ring_Below = 0x0325, // U+0325 Combining Ring Below
U_Combining_Comma_Below = 0x0326, // U+0326 Combining Comma Below
U_Combining_Cedilla = 0x0327, // U+0327 Combining Cedilla
U_Combining_Ogonek = 0x0328, // U+0328 Combining Ogonek
U_Combining_Vertical_Line_Below = 0x0329, // U+0329 Combining Vertical Line Below
U_Combining_Bridge_Below = 0x032A, // U+032A Combining Bridge Below
U_Combining_Inverted_Double_Arch_Below = 0x032B, // U+032B Combining Inverted Double Arch Below
U_Combining_Caron_Below = 0x032C, // U+032C Combining Caron Below
U_Combining_Circumflex_Accent_Below = 0x032D, // U+032D Combining Circumflex Accent Below
U_Combining_Breve_Below = 0x032E, // U+032E Combining Breve Below
U_Combining_Inverted_Breve_Below = 0x032F, // U+032F Combining Inverted Breve Below
U_Combining_Tilde_Below = 0x0330, // U+0330 Combining Tilde Below
U_Combining_Macron_Below = 0x0331, // U+0331 Combining Macron Below
U_Combining_Low_Line = 0x0332, // U+0332 Combining Low Line
U_Combining_Double_Low_Line = 0x0333, // U+0333 Combining Double Low Line
U_Combining_Tilde_Overlay = 0x0334, // U+0334 Combining Tilde Overlay
U_Combining_Short_Stroke_Overlay = 0x0335, // U+0335 Combining Short Stroke Overlay
U_Combining_Long_Stroke_Overlay = 0x0336, // U+0336 Combining Long Stroke Overlay
U_Combining_Short_Solidus_Overlay = 0x0337, // U+0337 Combining Short Solidus Overlay
U_Combining_Long_Solidus_Overlay = 0x0338, // U+0338 Combining Long Solidus Overlay
U_Combining_Right_Half_Ring_Below = 0x0339, // U+0339 Combining Right Half Ring Below
U_Combining_Inverted_Bridge_Below = 0x033A, // U+033A Combining Inverted Bridge Below
U_Combining_Square_Below = 0x033B, // U+033B Combining Square Below
U_Combining_Seagull_Below = 0x033C, // U+033C Combining Seagull Below
U_Combining_X_Above = 0x033D, // U+033D Combining X Above
U_Combining_Vertical_Tilde = 0x033E, // U+033E Combining Vertical Tilde
U_Combining_Double_Overline = 0x033F, // U+033F Combining Double Overline
U_Combining_Grave_Tone_Mark = 0x0340, // U+0340 Combining Grave Tone Mark
U_Combining_Acute_Tone_Mark = 0x0341, // U+0341 Combining Acute Tone Mark
U_Combining_Greek_Perispomeni = 0x0342, // U+0342 Combining Greek Perispomeni
U_Combining_Greek_Koronis = 0x0343, // U+0343 Combining Greek Koronis
U_Combining_Greek_Dialytika_Tonos = 0x0344, // U+0344 Combining Greek Dialytika Tonos
U_Combining_Greek_Ypogegrammeni = 0x0345, // U+0345 Combining Greek Ypogegrammeni
U_Combining_Bridge_Above = 0x0346, // U+0346 Combining Bridge Above
U_Combining_Equals_Sign_Below = 0x0347, // U+0347 Combining Equals Sign Below
U_Combining_Double_Vertical_Line_Below = 0x0348, // U+0348 Combining Double Vertical Line Below
U_Combining_Left_Angle_Below = 0x0349, // U+0349 Combining Left Angle Below
U_Combining_Not_Tilde_Above = 0x034A, // U+034A Combining Not Tilde Above
U_Combining_Homothetic_Above = 0x034B, // U+034B Combining Homothetic Above
U_Combining_Almost_Equal_To_Above = 0x034C, // U+034C Combining Almost Equal To Above
U_Combining_Left_Right_Arrow_Below = 0x034D, // U+034D Combining Left Right Arrow Below
U_Combining_Upwards_Arrow_Below = 0x034E, // U+034E Combining Upwards Arrow Below
U_Combining_Grapheme_Joiner = 0x034F, // U+034F Combining Grapheme Joiner
U_Combining_Right_Arrowhead_Above = 0x0350, // U+0350 Combining Right Arrowhead Above
U_Combining_Left_Half_Ring_Above = 0x0351, // U+0351 Combining Left Half Ring Above
U_Combining_Fermata = 0x0352, // U+0352 Combining Fermata
U_Combining_X_Below = 0x0353, // U+0353 Combining X Below
U_Combining_Left_Arrowhead_Below = 0x0354, // U+0354 Combining Left Arrowhead Below
U_Combining_Right_Arrowhead_Below = 0x0355, // U+0355 Combining Right Arrowhead Below
U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below = 0x0356, // U+0356 Combining Right Arrowhead And Up Arrowhead Below
U_Combining_Right_Half_Ring_Above = 0x0357, // U+0357 Combining Right Half Ring Above
U_Combining_Dot_Above_Right = 0x0358, // U+0358 Combining Dot Above Right
U_Combining_Asterisk_Below = 0x0359, // U+0359 Combining Asterisk Below
U_Combining_Double_Ring_Below = 0x035A, // U+035A Combining Double Ring Below
U_Combining_Zigzag_Above = 0x035B, // U+035B Combining Zigzag Above
U_Combining_Double_Breve_Below = 0x035C, // U+035C Combining Double Breve Below
U_Combining_Double_Breve = 0x035D, // U+035D Combining Double Breve
U_Combining_Double_Macron = 0x035E, // U+035E Combining Double Macron
U_Combining_Double_Macron_Below = 0x035F, // U+035F Combining Double Macron Below
U_Combining_Double_Tilde = 0x0360, // U+0360 Combining Double Tilde
U_Combining_Double_Inverted_Breve = 0x0361, // U+0361 Combining Double Inverted Breve
U_Combining_Double_Rightwards_Arrow_Below = 0x0362, // U+0362 Combining Double Rightwards Arrow Below
U_Combining_Latin_Small_Letter_A = 0x0363, // U+0363 Combining Latin Small Letter A
U_Combining_Latin_Small_Letter_E = 0x0364, // U+0364 Combining Latin Small Letter E
U_Combining_Latin_Small_Letter_I = 0x0365, // U+0365 Combining Latin Small Letter I
U_Combining_Latin_Small_Letter_O = 0x0366, // U+0366 Combining Latin Small Letter O
U_Combining_Latin_Small_Letter_U = 0x0367, // U+0367 Combining Latin Small Letter U
U_Combining_Latin_Small_Letter_C = 0x0368, // U+0368 Combining Latin Small Letter C
U_Combining_Latin_Small_Letter_D = 0x0369, // U+0369 Combining Latin Small Letter D
U_Combining_Latin_Small_Letter_H = 0x036A, // U+036A Combining Latin Small Letter H
U_Combining_Latin_Small_Letter_M = 0x036B, // U+036B Combining Latin Small Letter M
U_Combining_Latin_Small_Letter_R = 0x036C, // U+036C Combining Latin Small Letter R
U_Combining_Latin_Small_Letter_T = 0x036D, // U+036D Combining Latin Small Letter T
U_Combining_Latin_Small_Letter_V = 0x036E, // U+036E Combining Latin Small Letter V
U_Combining_Latin_Small_Letter_X = 0x036F, // U+036F Combining Latin Small Letter X
/**
* Unicode Character 'LINE SEPARATOR' (U+2028)
* http://www.fileformat.info/info/unicode/char/2028/index.htm
*/
LINE_SEPARATOR = 0x2028,
/**
* Unicode Character 'PARAGRAPH SEPARATOR' (U+2029)
* http://www.fileformat.info/info/unicode/char/2029/index.htm
*/
PARAGRAPH_SEPARATOR = 0x2029,
/**
* Unicode Character 'NEXT LINE' (U+0085)
* http://www.fileformat.info/info/unicode/char/0085/index.htm
*/
NEXT_LINE = 0x0085,
// http://www.fileformat.info/info/unicode/category/Sk/list.htm
U_CIRCUMFLEX = 0x005E, // U+005E CIRCUMFLEX
U_GRAVE_ACCENT = 0x0060, // U+0060 GRAVE ACCENT
U_DIAERESIS = 0x00A8, // U+00A8 DIAERESIS
U_MACRON = 0x00AF, // U+00AF MACRON
U_ACUTE_ACCENT = 0x00B4, // U+00B4 ACUTE ACCENT
U_CEDILLA = 0x00B8, // U+00B8 CEDILLA
U_MODIFIER_LETTER_LEFT_ARROWHEAD = 0x02C2, // U+02C2 MODIFIER LETTER LEFT ARROWHEAD
U_MODIFIER_LETTER_RIGHT_ARROWHEAD = 0x02C3, // U+02C3 MODIFIER LETTER RIGHT ARROWHEAD
U_MODIFIER_LETTER_UP_ARROWHEAD = 0x02C4, // U+02C4 MODIFIER LETTER UP ARROWHEAD
U_MODIFIER_LETTER_DOWN_ARROWHEAD = 0x02C5, // U+02C5 MODIFIER LETTER DOWN ARROWHEAD
U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING = 0x02D2, // U+02D2 MODIFIER LETTER CENTRED RIGHT HALF RING
U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING = 0x02D3, // U+02D3 MODIFIER LETTER CENTRED LEFT HALF RING
U_MODIFIER_LETTER_UP_TACK = 0x02D4, // U+02D4 MODIFIER LETTER UP TACK
U_MODIFIER_LETTER_DOWN_TACK = 0x02D5, // U+02D5 MODIFIER LETTER DOWN TACK
U_MODIFIER_LETTER_PLUS_SIGN = 0x02D6, // U+02D6 MODIFIER LETTER PLUS SIGN
U_MODIFIER_LETTER_MINUS_SIGN = 0x02D7, // U+02D7 MODIFIER LETTER MINUS SIGN
U_BREVE = 0x02D8, // U+02D8 BREVE
U_DOT_ABOVE = 0x02D9, // U+02D9 DOT ABOVE
U_RING_ABOVE = 0x02DA, // U+02DA RING ABOVE
U_OGONEK = 0x02DB, // U+02DB OGONEK
U_SMALL_TILDE = 0x02DC, // U+02DC SMALL TILDE
U_DOUBLE_ACUTE_ACCENT = 0x02DD, // U+02DD DOUBLE ACUTE ACCENT
U_MODIFIER_LETTER_RHOTIC_HOOK = 0x02DE, // U+02DE MODIFIER LETTER RHOTIC HOOK
U_MODIFIER_LETTER_CROSS_ACCENT = 0x02DF, // U+02DF MODIFIER LETTER CROSS ACCENT
U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR = 0x02E5, // U+02E5 MODIFIER LETTER EXTRA-HIGH TONE BAR
U_MODIFIER_LETTER_HIGH_TONE_BAR = 0x02E6, // U+02E6 MODIFIER LETTER HIGH TONE BAR
U_MODIFIER_LETTER_MID_TONE_BAR = 0x02E7, // U+02E7 MODIFIER LETTER MID TONE BAR
U_MODIFIER_LETTER_LOW_TONE_BAR = 0x02E8, // U+02E8 MODIFIER LETTER LOW TONE BAR
U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR = 0x02E9, // U+02E9 MODIFIER LETTER EXTRA-LOW TONE BAR
U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK = 0x02EA, // U+02EA MODIFIER LETTER YIN DEPARTING TONE MARK
U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK = 0x02EB, // U+02EB MODIFIER LETTER YANG DEPARTING TONE MARK
U_MODIFIER_LETTER_UNASPIRATED = 0x02ED, // U+02ED MODIFIER LETTER UNASPIRATED
U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD = 0x02EF, // U+02EF MODIFIER LETTER LOW DOWN ARROWHEAD
U_MODIFIER_LETTER_LOW_UP_ARROWHEAD = 0x02F0, // U+02F0 MODIFIER LETTER LOW UP ARROWHEAD
U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD = 0x02F1, // U+02F1 MODIFIER LETTER LOW LEFT ARROWHEAD
U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD = 0x02F2, // U+02F2 MODIFIER LETTER LOW RIGHT ARROWHEAD
U_MODIFIER_LETTER_LOW_RING = 0x02F3, // U+02F3 MODIFIER LETTER LOW RING
U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT = 0x02F4, // U+02F4 MODIFIER LETTER MIDDLE GRAVE ACCENT
U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT = 0x02F5, // U+02F5 MODIFIER LETTER MIDDLE DOUBLE GRAVE ACCENT
U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT = 0x02F6, // U+02F6 MODIFIER LETTER MIDDLE DOUBLE ACUTE ACCENT
U_MODIFIER_LETTER_LOW_TILDE = 0x02F7, // U+02F7 MODIFIER LETTER LOW TILDE
U_MODIFIER_LETTER_RAISED_COLON = 0x02F8, // U+02F8 MODIFIER LETTER RAISED COLON
U_MODIFIER_LETTER_BEGIN_HIGH_TONE = 0x02F9, // U+02F9 MODIFIER LETTER BEGIN HIGH TONE
U_MODIFIER_LETTER_END_HIGH_TONE = 0x02FA, // U+02FA MODIFIER LETTER END HIGH TONE
U_MODIFIER_LETTER_BEGIN_LOW_TONE = 0x02FB, // U+02FB MODIFIER LETTER BEGIN LOW TONE
U_MODIFIER_LETTER_END_LOW_TONE = 0x02FC, // U+02FC MODIFIER LETTER END LOW TONE
U_MODIFIER_LETTER_SHELF = 0x02FD, // U+02FD MODIFIER LETTER SHELF
U_MODIFIER_LETTER_OPEN_SHELF = 0x02FE, // U+02FE MODIFIER LETTER OPEN SHELF
U_MODIFIER_LETTER_LOW_LEFT_ARROW = 0x02FF, // U+02FF MODIFIER LETTER LOW LEFT ARROW
U_GREEK_LOWER_NUMERAL_SIGN = 0x0375, // U+0375 GREEK LOWER NUMERAL SIGN
U_GREEK_TONOS = 0x0384, // U+0384 GREEK TONOS
U_GREEK_DIALYTIKA_TONOS = 0x0385, // U+0385 GREEK DIALYTIKA TONOS
U_GREEK_KORONIS = 0x1FBD, // U+1FBD GREEK KORONIS
U_GREEK_PSILI = 0x1FBF, // U+1FBF GREEK PSILI
U_GREEK_PERISPOMENI = 0x1FC0, // U+1FC0 GREEK PERISPOMENI
U_GREEK_DIALYTIKA_AND_PERISPOMENI = 0x1FC1, // U+1FC1 GREEK DIALYTIKA AND PERISPOMENI
U_GREEK_PSILI_AND_VARIA = 0x1FCD, // U+1FCD GREEK PSILI AND VARIA
U_GREEK_PSILI_AND_OXIA = 0x1FCE, // U+1FCE GREEK PSILI AND OXIA
U_GREEK_PSILI_AND_PERISPOMENI = 0x1FCF, // U+1FCF GREEK PSILI AND PERISPOMENI
U_GREEK_DASIA_AND_VARIA = 0x1FDD, // U+1FDD GREEK DASIA AND VARIA
U_GREEK_DASIA_AND_OXIA = 0x1FDE, // U+1FDE GREEK DASIA AND OXIA
U_GREEK_DASIA_AND_PERISPOMENI = 0x1FDF, // U+1FDF GREEK DASIA AND PERISPOMENI
U_GREEK_DIALYTIKA_AND_VARIA = 0x1FED, // U+1FED GREEK DIALYTIKA AND VARIA
U_GREEK_DIALYTIKA_AND_OXIA = 0x1FEE, // U+1FEE GREEK DIALYTIKA AND OXIA
U_GREEK_VARIA = 0x1FEF, // U+1FEF GREEK VARIA
U_GREEK_OXIA = 0x1FFD, // U+1FFD GREEK OXIA
U_GREEK_DASIA = 0x1FFE, // U+1FFE GREEK DASIA
U_IDEOGRAPHIC_FULL_STOP = 0x3002, // U+3002 IDEOGRAPHIC FULL STOP
U_LEFT_CORNER_BRACKET = 0x300C, // U+300C LEFT CORNER BRACKET
U_RIGHT_CORNER_BRACKET = 0x300D, // U+300D RIGHT CORNER BRACKET
U_LEFT_BLACK_LENTICULAR_BRACKET = 0x3010, // U+3010 LEFT BLACK LENTICULAR BRACKET
U_RIGHT_BLACK_LENTICULAR_BRACKET = 0x3011, // U+3011 RIGHT BLACK LENTICULAR BRACKET
U_OVERLINE = 0x203E, // Unicode Character 'OVERLINE'
/**
* UTF-8 BOM
* Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF)
* http://www.fileformat.info/info/unicode/char/feff/index.htm
*/
UTF8_BOM = 65279,
U_FULLWIDTH_SEMICOLON = 0xFF1B, // U+FF1B FULLWIDTH SEMICOLON
U_FULLWIDTH_COMMA = 0xFF0C, // U+FF0C FULLWIDTH COMMA
}
function roundFloat(number: number, decimalPoints: number): number {
const decimal = Math.pow(10, decimalPoints);
return Math.round(number * decimal) / decimal;
}
export class RGBA {
_rgbaBrand: void = undefined;
/**
* Red: integer in [0-255]
*/
readonly r: number;
/**
* Green: integer in [0-255]
*/
readonly g: number;
/**
* Blue: integer in [0-255]
*/
readonly b: number;
/**
* Alpha: float in [0-1]
*/
readonly a: number;
constructor(r: number, g: number, b: number, a: number = 1) {
this.r = Math.min(255, Math.max(0, r)) | 0;
this.g = Math.min(255, Math.max(0, g)) | 0;
this.b = Math.min(255, Math.max(0, b)) | 0;
this.a = roundFloat(Math.max(Math.min(1, a), 0), 3);
}
static equals(a: RGBA, b: RGBA): boolean {
return a.r === b.r && a.g === b.g && a.b === b.b && a.a === b.a;
}
}
export class HSLA {
_hslaBrand: void = undefined;
/**
* Hue: integer in [0, 360]
*/
readonly h: number;
/**
* Saturation: float in [0, 1]
*/
readonly s: number;
/**
* Luminosity: float in [0, 1]
*/
readonly l: number;
/**
* Alpha: float in [0, 1]
*/
readonly a: number;
constructor(h: number, s: number, l: number, a: number) {
this.h = Math.max(Math.min(360, h), 0) | 0;
this.s = roundFloat(Math.max(Math.min(1, s), 0), 3);
this.l = roundFloat(Math.max(Math.min(1, l), 0), 3);
this.a = roundFloat(Math.max(Math.min(1, a), 0), 3);
}
static equals(a: HSLA, b: HSLA): boolean {
return a.h === b.h && a.s === b.s && a.l === b.l && a.a === b.a;
}
/**
* Converts an RGB color value to HSL. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes r, g, and b are contained in the set [0, 255] and
* returns h in the set [0, 360], s, and l in the set [0, 1].
*/
static fromRGBA(rgba: RGBA): HSLA {
const r = rgba.r / 255;
const g = rgba.g / 255;
const b = rgba.b / 255;
const a = rgba.a;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
let h = 0;
let s = 0;
const l = (min + max) / 2;
const chroma = max - min;
if (chroma > 0) {
s = Math.min((l <= 0.5 ? chroma / (2 * l) : chroma / (2 - (2 * l))), 1);
switch (max) {
case r: h = (g - b) / chroma + (g < b ? 6 : 0); break;
case g: h = (b - r) / chroma + 2; break;
case b: h = (r - g) / chroma + 4; break;
}
h *= 60;
h = Math.round(h);
}
return new HSLA(h, s, l, a);
}
private static _hue2rgb(p: number, q: number, t: number): number {
if (t < 0) {
t += 1;
}
if (t > 1) {
t -= 1;
}
if (t < 1 / 6) {
return p + (q - p) * 6 * t;
}
if (t < 1 / 2) {
return q;
}
if (t < 2 / 3) {
return p + (q - p) * (2 / 3 - t) * 6;
}
return p;
}
/**
* Converts an HSL color value to RGB. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes h in the set [0, 360] s, and l are contained in the set [0, 1] and
* returns r, g, and b in the set [0, 255].
*/
static toRGBA(hsla: HSLA): RGBA {
const h = hsla.h / 360;
const { s, l, a } = hsla;
let r: number, g: number, b: number;
if (s === 0) {
r = g = b = l; // achromatic
} else {
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
r = HSLA._hue2rgb(p, q, h + 1 / 3);
g = HSLA._hue2rgb(p, q, h);
b = HSLA._hue2rgb(p, q, h - 1 / 3);
}
return new RGBA(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), a);
}
}
export class HSVA {
_hsvaBrand: void = undefined;
/**
* Hue: integer in [0, 360]
*/
readonly h: number;
/**
* Saturation: float in [0, 1]
*/
readonly s: number;
/**
* Value: float in [0, 1]
*/
readonly v: number;
/**
* Alpha: float in [0, 1]
*/
readonly a: number;
constructor(h: number, s: number, v: number, a: number) {
this.h = Math.max(Math.min(360, h), 0) | 0;
this.s = roundFloat(Math.max(Math.min(1, s), 0), 3);
this.v = roundFloat(Math.max(Math.min(1, v), 0), 3);
this.a = roundFloat(Math.max(Math.min(1, a), 0), 3);
}
static equals(a: HSVA, b: HSVA): boolean {
return a.h === b.h && a.s === b.s && a.v === b.v && a.a === b.a;
}
// from http://www.rapidtables.com/convert/color/rgb-to-hsv.htm
static fromRGBA(rgba: RGBA): HSVA {
const r = rgba.r / 255;
const g = rgba.g / 255;
const b = rgba.b / 255;
const cmax = Math.max(r, g, b);
const cmin = Math.min(r, g, b);
const delta = cmax - cmin;
const s = cmax === 0 ? 0 : (delta / cmax);
let m: number;
if (delta === 0) {
m = 0;
} else if (cmax === r) {
m = ((((g - b) / delta) % 6) + 6) % 6;
} else if (cmax === g) {
m = ((b - r) / delta) + 2;
} else {
m = ((r - g) / delta) + 4;
}
return new HSVA(Math.round(m * 60), s, cmax, rgba.a);
}
// from http://www.rapidtables.com/convert/color/hsv-to-rgb.htm
static toRGBA(hsva: HSVA): RGBA {
const { h, s, v, a } = hsva;
const c = v * s;
const x = c * (1 - Math.abs((h / 60) % 2 - 1));
const m = v - c;
let [r, g, b] = [0, 0, 0];
if (h < 60) {
r = c;
g = x;
} else if (h < 120) {
r = x;
g = c;
} else if (h < 180) {
g = c;
b = x;
} else if (h < 240) {
g = x;
b = c;
} else if (h < 300) {
r = x;
b = c;
} else if (h <= 360) {
r = c;
b = x;
}
r = Math.round((r + m) * 255);
g = Math.round((g + m) * 255);
b = Math.round((b + m) * 255);
return new RGBA(r, g, b, a);
}
}
export class Color {
static fromHex(hex: string): Color {
return Color.Format.CSS.parseHex(hex) || Color.red;
}
readonly rgba: RGBA;
private _hsla?: HSLA;
get hsla(): HSLA {
if (this._hsla) {
return this._hsla;
} else {
return HSLA.fromRGBA(this.rgba);
}
}
private _hsva?: HSVA;
get hsva(): HSVA {
if (this._hsva) {
return this._hsva;
}
return HSVA.fromRGBA(this.rgba);
}
constructor(arg: RGBA | HSLA | HSVA) {
if (!arg) {
throw new Error('Color needs a value');
} else if (arg instanceof RGBA) {
this.rgba = arg;
} else if (arg instanceof HSLA) {
this._hsla = arg;
this.rgba = HSLA.toRGBA(arg);
} else if (arg instanceof HSVA) {
this._hsva = arg;
this.rgba = HSVA.toRGBA(arg);
} else {
throw new Error('Invalid color ctor argument');
}
}
equals(other: Color | null): boolean {
return !!other && RGBA.equals(this.rgba, other.rgba) && HSLA.equals(this.hsla, other.hsla) && HSVA.equals(this.hsva, other.hsva);
}
/**
* http://www.w3.org/TR/WCAG20/#relativeluminancedef
* Returns the number in the set [0, 1]. O => Darkest Black. 1 => Lightest white.
*/
getRelativeLuminance(): number {
const R = Color._relativeLuminanceForComponent(this.rgba.r);
const G = Color._relativeLuminanceForComponent(this.rgba.g);
const B = Color._relativeLuminanceForComponent(this.rgba.b);
const luminance = 0.2126 * R + 0.7152 * G + 0.0722 * B;
return roundFloat(luminance, 4);
}
private static _relativeLuminanceForComponent(color: number): number {
const c = color / 255;
return (c <= 0.03928) ? c / 12.92 : Math.pow(((c + 0.055) / 1.055), 2.4);
}
/**
* http://www.w3.org/TR/WCAG20/#contrast-ratiodef
* Returns the contrast ration number in the set [1, 21].
*/
getContrastRatio(another: Color): number {
const lum1 = this.getRelativeLuminance();
const lum2 = another.getRelativeLuminance();
return lum1 > lum2 ? (lum1 + 0.05) / (lum2 + 0.05) : (lum2 + 0.05) / (lum1 + 0.05);
}
/**
* http://24ways.org/2010/calculating-color-contrast
* Return 'true' if darker color otherwise 'false'
*/
isDarker(): boolean {
const yiq = (this.rgba.r * 299 + this.rgba.g * 587 + this.rgba.b * 114) / 1000;
return yiq < 128;
}
/**
* http://24ways.org/2010/calculating-color-contrast
* Return 'true' if lighter color otherwise 'false'
*/
isLighter(): boolean {
const yiq = (this.rgba.r * 299 + this.rgba.g * 587 + this.rgba.b * 114) / 1000;
return yiq >= 128;
}
isLighterThan(another: Color): boolean {
const lum1 = this.getRelativeLuminance();
const lum2 = another.getRelativeLuminance();
return lum1 > lum2;
}
isDarkerThan(another: Color): boolean {
const lum1 = this.getRelativeLuminance();
const lum2 = another.getRelativeLuminance();
return lum1 < lum2;
}
lighten(factor: number): Color {
return new Color(new HSLA(this.hsla.h, this.hsla.s, this.hsla.l + this.hsla.l * factor, this.hsla.a));
}
darken(factor: number): Color {
return new Color(new HSLA(this.hsla.h, this.hsla.s, this.hsla.l - this.hsla.l * factor, this.hsla.a));
}
transparent(factor: number): Color {
const { r, g, b, a } = this.rgba;
return new Color(new RGBA(r, g, b, a * factor));
}
isTransparent(): boolean {
return this.rgba.a === 0;
}
isOpaque(): boolean {
return this.rgba.a === 1;
}
opposite(): Color {
return new Color(new RGBA(255 - this.rgba.r, 255 - this.rgba.g, 255 - this.rgba.b, this.rgba.a));
}
blend(c: Color): Color {
const rgba = c.rgba;
// Convert to 0..1 opacity
const thisA = this.rgba.a;
const colorA = rgba.a;
const a = thisA + colorA * (1 - thisA);
if (a < 1e-6) {
return Color.transparent;
}
const r = this.rgba.r * thisA / a + rgba.r * colorA * (1 - thisA) / a;
const g = this.rgba.g * thisA / a + rgba.g * colorA * (1 - thisA) / a;
const b = this.rgba.b * thisA / a + rgba.b * colorA * (1 - thisA) / a;
return new Color(new RGBA(r, g, b, a));
}
makeOpaque(opaqueBackground: Color): Color {
if (this.isOpaque() || opaqueBackground.rgba.a !== 1) {
// only allow to blend onto a non-opaque color onto a opaque color
return this;
}
const { r, g, b, a } = this.rgba;
// https://stackoverflow.com/questions/12228548/finding-equivalent-color-with-opacity
return new Color(new RGBA(
opaqueBackground.rgba.r - a * (opaqueBackground.rgba.r - r),
opaqueBackground.rgba.g - a * (opaqueBackground.rgba.g - g),
opaqueBackground.rgba.b - a * (opaqueBackground.rgba.b - b),
1
));
}
flatten(...backgrounds: Color[]): Color {
const background = backgrounds.reduceRight((accumulator, color) => {
return Color._flatten(color, accumulator);
});
return Color._flatten(this, background);
}
private static _flatten(foreground: Color, background: Color) {
const backgroundAlpha = 1 - foreground.rgba.a;
return new Color(new RGBA(
backgroundAlpha * background.rgba.r + foreground.rgba.a * foreground.rgba.r,
backgroundAlpha * background.rgba.g + foreground.rgba.a * foreground.rgba.g,
backgroundAlpha * background.rgba.b + foreground.rgba.a * foreground.rgba.b
));
}
private _toString?: string;
toString(): string {
if (!this._toString) {
this._toString = Color.Format.CSS.format(this);
}
return this._toString;
}
static getLighterColor(of: Color, relative: Color, factor?: number): Color {
if (of.isLighterThan(relative)) {
return of;
}
factor = factor ? factor : 0.5;
const lum1 = of.getRelativeLuminance();
const lum2 = relative.getRelativeLuminance();
factor = factor * (lum2 - lum1) / lum2;
return of.lighten(factor);
}
static getDarkerColor(of: Color, relative: Color, factor?: number): Color {
if (of.isDarkerThan(relative)) {
return of;
}
factor = factor ? factor : 0.5;
const lum1 = of.getRelativeLuminance();
const lum2 = relative.getRelativeLuminance();
factor = factor * (lum1 - lum2) / lum1;
return of.darken(factor);
}
static readonly white = new Color(new RGBA(255, 255, 255, 1));
static readonly black = new Color(new RGBA(0, 0, 0, 1));
static readonly red = new Color(new RGBA(255, 0, 0, 1));
static readonly blue = new Color(new RGBA(0, 0, 255, 1));
static readonly green = new Color(new RGBA(0, 255, 0, 1));
static readonly cyan = new Color(new RGBA(0, 255, 255, 1));
static readonly lightgrey = new Color(new RGBA(211, 211, 211, 1));
static readonly transparent = new Color(new RGBA(0, 0, 0, 0));
}
export namespace Color {
export namespace Format {
export namespace CSS {
export function formatRGB(color: Color): string {
if (color.rgba.a === 1) {
return `rgb(${color.rgba.r}, ${color.rgba.g}, ${color.rgba.b})`;
}
return Color.Format.CSS.formatRGBA(color);
}
export function formatRGBA(color: Color): string {
return `rgba(${color.rgba.r}, ${color.rgba.g}, ${color.rgba.b}, ${+(color.rgba.a).toFixed(2)})`;
}
export function formatHSL(color: Color): string {
if (color.hsla.a === 1) {
return `hsl(${color.hsla.h}, ${(color.hsla.s * 100).toFixed(2)}%, ${(color.hsla.l * 100).toFixed(2)}%)`;
}
return Color.Format.CSS.formatHSLA(color);
}
export function formatHSLA(color: Color): string {
return `hsla(${color.hsla.h}, ${(color.hsla.s * 100).toFixed(2)}%, ${(color.hsla.l * 100).toFixed(2)}%, ${color.hsla.a.toFixed(2)})`;
}
function _toTwoDigitHex(n: number): string {
const r = n.toString(16);
return r.length !== 2 ? '0' + r : r;
}
/**
* Formats the color as #RRGGBB
*/
export function formatHex(color: Color): string {
return `#${_toTwoDigitHex(color.rgba.r)}${_toTwoDigitHex(color.rgba.g)}${_toTwoDigitHex(color.rgba.b)}`;
}
/**
* Formats the color as #RRGGBBAA
* If 'compact' is set, colors without transparancy will be printed as #RRGGBB
*/
export function formatHexA(color: Color, compact = false): string {
if (compact && color.rgba.a === 1) {
return Color.Format.CSS.formatHex(color);
}
return `#${_toTwoDigitHex(color.rgba.r)}${_toTwoDigitHex(color.rgba.g)}${_toTwoDigitHex(color.rgba.b)}${_toTwoDigitHex(Math.round(color.rgba.a * 255))}`;
}
/**
* The default format will use HEX if opaque and RGBA otherwise.
*/
export function format(color: Color): string {
if (color.isOpaque()) {
return Color.Format.CSS.formatHex(color);
}
return Color.Format.CSS.formatRGBA(color);
}
/**
* Converts an Hex color value to a Color.
* returns r, g, and b are contained in the set [0, 255]
* @param hex string (#RGB, #RGBA, #RRGGBB or #RRGGBBAA).
*/
export function parseHex(hex: string): Color | null {
const length = hex.length;
if (length === 0) {
// Invalid color
return null;
}
if (hex.charCodeAt(0) !== CharCode.Hash) {
// Does not begin with a #
return null;
}
if (length === 7) {
// #RRGGBB format
const r = 16 * _parseHexDigit(hex.charCodeAt(1)) + _parseHexDigit(hex.charCodeAt(2));
const g = 16 * _parseHexDigit(hex.charCodeAt(3)) + _parseHexDigit(hex.charCodeAt(4));
const b = 16 * _parseHexDigit(hex.charCodeAt(5)) + _parseHexDigit(hex.charCodeAt(6));
return new Color(new RGBA(r, g, b, 1));
}
if (length === 9) {
// #RRGGBBAA format
const r = 16 * _parseHexDigit(hex.charCodeAt(1)) + _parseHexDigit(hex.charCodeAt(2));
const g = 16 * _parseHexDigit(hex.charCodeAt(3)) + _parseHexDigit(hex.charCodeAt(4));
const b = 16 * _parseHexDigit(hex.charCodeAt(5)) + _parseHexDigit(hex.charCodeAt(6));
const a = 16 * _parseHexDigit(hex.charCodeAt(7)) + _parseHexDigit(hex.charCodeAt(8));
return new Color(new RGBA(r, g, b, a / 255));
}
if (length === 4) {
// #RGB format
const r = _parseHexDigit(hex.charCodeAt(1));
const g = _parseHexDigit(hex.charCodeAt(2));
const b = _parseHexDigit(hex.charCodeAt(3));
return new Color(new RGBA(16 * r + r, 16 * g + g, 16 * b + b));
}
if (length === 5) {
// #RGBA format
const r = _parseHexDigit(hex.charCodeAt(1));
const g = _parseHexDigit(hex.charCodeAt(2));
const b = _parseHexDigit(hex.charCodeAt(3));
const a = _parseHexDigit(hex.charCodeAt(4));
return new Color(new RGBA(16 * r + r, 16 * g + g, 16 * b + b, (16 * a + a) / 255));
}
// Invalid color
return null;
}
function _parseHexDigit(charCode: CharCode): number {
switch (charCode) {
case CharCode.Digit0: return 0;
case CharCode.Digit1: return 1;
case CharCode.Digit2: return 2;
case CharCode.Digit3: return 3;
case CharCode.Digit4: return 4;
case CharCode.Digit5: return 5;
case CharCode.Digit6: return 6;
case CharCode.Digit7: return 7;
case CharCode.Digit8: return 8;
case CharCode.Digit9: return 9;
case CharCode.a: return 10;
case CharCode.A: return 10;
case CharCode.b: return 11;
case CharCode.B: return 11;
case CharCode.c: return 12;
case CharCode.C: return 12;
case CharCode.d: return 13;
case CharCode.D: return 13;
case CharCode.e: return 14;
case CharCode.E: return 14;
case CharCode.f: return 15;
case CharCode.F: return 15;
}
return 0;
}
}
}
} | the_stack |
import { BaseConfiguration, BaseProxy, Configuration, DefaultConfiguration, DefaultSecurity, Security } from "../base";
import { Proxy, Service } from "../decorators";
import { Forbidden, InternalServerError, NotFound } from "../errors";
import { Logger } from "../logger";
import { BindingMetadata, ContainerMetadata, EventMetadata, HttpMetadata, Metadata, ProxyMetadata, RemoteMetadata, ServiceMetadata } from "../metadata";
import { Context, EventRequest, EventResult, HttpRequest, HttpResponse, RemoteRequest } from "../types";
import { HttpUtils, Utils } from "../utils";
import { Container, ContainerState, EventHandler, HttpHandler, ObjectType, RemoteHandler } from "./common";
export class ContainerInstance implements Container {
private application: string;
private name: string;
private log: Logger;
private config: Configuration;
private security: Security;
private istate: ContainerState;
private imetadata: ContainerMetadata;
private resources: Record<string, any>;
private services: Record<string, Service>;
private proxies: Record<string, Proxy>;
private remoteHandlers: Record<string, RemoteHandler>;
private httpHandlers: Record<string, HttpHandler>;
private eventHandlers: Record<string, EventHandler[]>;
constructor(application: string, name: string, index?: string) {
this.application = application;
this.name = name || ContainerInstance.name;
if (index !== undefined) this.name += ":" + index;
this.log = Logger.get(this.application, this.name);
this.istate = ContainerState.Pending;
this.resources = {};
this.services = {};
this.proxies = {};
this.remoteHandlers = {};
this.httpHandlers = {};
this.eventHandlers = {};
this.imetadata = {
permissions: {},
httpMetadata: {},
remoteMetadata: {},
eventMetadata: {}
};
}
public get state() {
return this.istate;
}
public get metadata() {
return this.imetadata;
}
public get<T>(type: ObjectType<T> | string): T {
if (type === Configuration) return this.config as any;
if (type === Security) return this.config as any;
if (typeof type === "string") return this.services[type] || this.proxies[type] || this.resources[type];
if (ServiceMetadata.has(type)) return this.services[ServiceMetadata.service(type)] as any;
if (ProxyMetadata.has(type)) return this.proxies[ProxyMetadata.service(type)] as any;
return null;
}
public register(resource: Object, name?: string): this;
public register(service: Service): this;
public register(proxy: Proxy): this;
public register(type: Function, ...args: any[]): this;
public register(target: Object | Service | Proxy | Function, ...args: any[]): this {
if (this.istate !== ContainerState.Pending) throw new InternalServerError("Invalid container state");
let name = undefined;
// Call constructor
// https://stackoverflow.com/questions/1606797/use-of-apply-with-new-operator-is-this-possible
if (target instanceof Function) {
target = new (Function.prototype.bind.apply(target, arguments));
} else {
name = args && args[0];
}
let id = name;
if (name) {
id = name = "" + name;
} else if (ServiceMetadata.has(target)) {
name = ServiceMetadata.service(target);
id = name;
} else if (ProxyMetadata.has(target)) {
name = ProxyMetadata.service(target);
id = ProxyMetadata.id(target, this.application);
} else {
id = name = target.constructor.name;
}
if (this.services[id] || this.proxies[id] || this.resources[id]) throw new InternalServerError(`Duplicate registration [${id}]`);
if (name === Configuration) {
if (!ServiceMetadata.has(target)) throw new InternalServerError(`Configuration must be a service`);
this.config = target as Configuration;
if (target instanceof BaseConfiguration) {
target.init(this.application);
}
}
if (name === Security) {
if (!ServiceMetadata.has(target)) throw new InternalServerError(`Security must be a service`);
this.security = target as any;
}
if (ServiceMetadata.has(target)) {
this.services[id] = target;
this.log.info("Service: %s", id);
} else if (ProxyMetadata.has(target)) {
this.proxies[id] = target;
this.log.info("Proxy: %s", id);
} else {
this.resources[id] = target;
this.log.info("Resource: %s", id);
}
return this;
}
public publish(service: Function, ...args: any[]): this;
public publish(service: Service): this;
public publish(service: Service | Function, ...args: any[]): this {
if (this.istate !== ContainerState.Pending) throw new InternalServerError("Invalid container state");
// Call constructor
if (service instanceof Function) {
service = new (Function.prototype.bind.apply(service, arguments)) as Service;
}
if (!ServiceMetadata.has(service)) throw new InternalServerError("Service decoration missing");
this.register(service);
let serviceName = ServiceMetadata.service(service);
this.log.info("Publish: %s", serviceName);
let permissionMetadata = ServiceMetadata.permissions(service);
let permissions = Object.keys(permissionMetadata);
permissions.forEach(method => {
let meta = permissionMetadata[method];
let key = meta.service + "." + method;
this.imetadata.permissions[key] = meta;
});
let remoteMetadata = ServiceMetadata.remoteMetadata(service);
let remotes = Object.keys(remoteMetadata);
remotes.forEach(name => {
let meta = remoteMetadata[name];
let key = meta.service + "." + name;
if (this.imetadata.remoteMetadata[key]) throw new InternalServerError(`Duplicate service method [${key}]`);
this.imetadata.remoteMetadata[key] = meta;
this.remoteHandlers[key] = this.remoteHandler(service as Service, meta);
});
let httpMetadata = ServiceMetadata.httpMetadata(service);
let bindMetadata = ServiceMetadata.bindingMetadata(service);
let routes = Object.keys(httpMetadata);
routes.forEach(route => {
let meta = httpMetadata[route];
if (this.imetadata.httpMetadata[route]) throw new InternalServerError(`Duplicate REST route [${route}]`);
this.imetadata.httpMetadata[route] = meta;
let bindings = bindMetadata[meta.method];
this.httpHandlers[route] = this.httpHandler(service as Service, meta, bindings);
});
let eventMetadata = ServiceMetadata.eventMetadata(service);
let events = Object.keys(eventMetadata);
events.forEach(event => {
let metas = eventMetadata[event];
this.imetadata.eventMetadata[event] = this.imetadata.eventMetadata[event] || [];
this.imetadata.eventMetadata[event] = this.imetadata.eventMetadata[event].concat(metas);
let handlers = metas.map(m => this.eventHandler(service as Service, m));
this.eventHandlers[event] = this.eventHandlers[event] || [];
this.eventHandlers[event] = this.eventHandlers[event].concat(handlers);
});
return this;
}
private remoteHandler(service: Service, metadata: RemoteMetadata): RemoteHandler {
let fun: RemoteHandler = async (ctx: Context, req: RemoteRequest): Promise<any> => {
let log: Logger = service.log || this.log;
let startTime = log.time();
try {
let method: Function = service[metadata.method];
let result = await method.apply(service, req.args);
return result;
} catch (e) {
throw e;
} finally {
log.timeEnd(startTime, `${metadata.method}`);
}
};
return fun;
}
private httpHandler(service: Service, metadata: HttpMetadata, bindings: BindingMetadata): HttpHandler {
let fun: HttpHandler = async (ctx: Context, req: HttpRequest): Promise<HttpResponse> => {
let log: Logger = service.log || this.log;
let startTime = log.time();
try {
let method: Function = service[metadata.method];
let result: any;
if (metadata.adapter) {
result = await metadata.adapter(
method.bind(service),
ctx,
req,
req.pathParameters || {},
req.queryStringParameters || {});
} else if (bindings && bindings.argBindings) {
let args: any = [];
for (let binding of bindings.argBindings) {
args[binding.index] = binding.binder(ctx, req);
}
result = await method.apply(service, args);
} else {
result = await method.apply(service);
}
let contentType = bindings && bindings.contentType || "application/json";
return { statusCode: metadata.code, body: result, contentType };
} catch (e) {
throw e;
} finally {
log.timeEnd(startTime, `${metadata.method}`);
}
};
return fun;
}
private eventHandler(service: Service, metadata: EventMetadata): EventHandler {
let handler: EventHandler = async (ctx: Context, req: EventRequest): Promise<any> => {
let log: Logger = service.log || this.log;
let startTime = log.time();
try {
let result: Promise<any>;
let method: Function = service[metadata.method];
if (metadata.adapter) {
result = await metadata.adapter(method.bind(service), ctx, req);
} else {
result = await method.call(service, ctx, req);
}
return result;
} catch (e) {
throw e;
} finally {
log.timeEnd(startTime, `${metadata.method}`);
}
};
return handler;
}
public prepare(): this {
if (this.istate !== ContainerState.Pending) throw new InternalServerError("Invalid container state");
if (!this.config) {
this.register(new DefaultConfiguration());
this.log.warn("Using default configuration service!");
}
if (!this.security) {
this.register(new DefaultSecurity());
this.log.warn("Using default security service!");
}
for (let sid in this.services) {
let service = this.services[sid];
this.inject(service);
}
for (let pid in this.proxies) {
let proxy = this.proxies[pid];
if (proxy instanceof BaseProxy) {
proxy.initialize(this.config, this.security);
}
this.inject(proxy);
}
this.istate = ContainerState.Ready;
return this;
}
private inject(service: Service) {
let dependencies = Metadata.dependencies(service);
for (let pid in dependencies) {
let dep = dependencies[pid];
let localId = dep.resource;
let proxyId = (dep.application || this.application) + ":" + localId;
let resolved = this.proxies[proxyId] || this.services[localId] || this.resources[localId];
let depId = (dep.application ? dep.application + ":" : "") + localId;
if (!resolved)
throw new InternalServerError(`Unresolved dependency [${depId}] on [${service.constructor.name}.${pid}]`);
this.log.info(`Resolved dependency [${depId}] on [${service.constructor.name}.${pid}]`);
service[pid] = resolved;
}
}
// --------------------------------------------------
public async remoteRequest(req: RemoteRequest): Promise<any> {
if (this.istate !== ContainerState.Ready) throw new InternalServerError("Invalid container state");
this.istate = ContainerState.Reserved;
try {
this.log.debug("Remote Request: %j", req);
if (req.application !== this.application) {
throw this.log.error(new NotFound(`Application not found [${req.application}]`));
}
let service = this.services[req.service];
if (!service) throw this.log.error(new NotFound(`Service not found [${req.service}]`));
let permissionId = req.service + "." + req.method;
let permission = permissionId && this.imetadata.permissions[permissionId];
if (permission == null) throw this.log.error(new Forbidden(`Undefined permission for method [${permissionId}]`));
let handler: RemoteHandler = this.remoteHandlers[permissionId];
if (!handler) throw this.log.error(new NotFound(`Method not found [${permissionId}]`));
this.istate = ContainerState.Busy;
let ctx = await this.security.remoteAuth(req, permission);
// let ctx = await this.security.localAuth();
try {
await this.activate(ctx);
let result = await handler(ctx, req);
return result;
} catch (e) {
throw this.log.error(e);
} finally {
await this.release(ctx);
}
} finally {
this.istate = ContainerState.Ready;
}
}
public async eventRequest(req: EventRequest): Promise<EventResult> {
if (this.istate !== ContainerState.Ready) throw new InternalServerError("Invalid container state");
this.istate = ContainerState.Reserved;
try {
req.type = "event";
this.log.debug("Event Request: %j", req);
let key = `${req.source} ${req.resource}`;
let alias = this.config.resources && this.config.resources[req.resource];
let metas = this.imetadata.eventMetadata[key];
let handlers = this.eventHandlers && this.eventHandlers[key];
if (!handlers && alias) {
let key2 = `${req.source} ${alias}`;
metas = this.imetadata.eventMetadata[key2];
handlers = this.eventHandlers && this.eventHandlers[key2];
}
if (!handlers) throw this.log.error(new NotFound(`Event handler not found [${key}] [${req.object}]`));
let result: EventResult = {
status: null,
source: req.source,
action: req.action,
resource: req.resource,
object: req.object,
returns: []
};
this.istate = ContainerState.Busy;
for (let i = 0; i < handlers.length; i++) {
let handler = handlers[i];
let target = metas[i];
if (!Utils.wildcardMatch(target.actionFilter, req.action) || !Utils.wildcardMatch(target.objectFilter, req.object)) continue;
req.application = this.application;
req.service = target.service;
req.method = target.method;
let permissionId = req.service + "." + req.method;
let permission = permissionId && this.imetadata.permissions[permissionId];
if (permission == null) throw this.log.error(new Forbidden(`Undefined permission for method [${permissionId}]`));
let ctx = await this.security.eventAuth(req, permission);
try {
await this.activate(ctx);
for (let record of req.records) {
req.record = record;
let data = await handler(ctx, req);
result.status = result.status || "OK";
result.returns.push({
service: target.service,
method: target.method,
error: null,
data
});
}
} catch (e) {
this.log.error(e);
result.status = "FAILED";
result.returns.push({
service: target.service,
method: target.method,
error: InternalServerError.wrap(e),
data: null
});
} finally {
await this.release(ctx);
}
}
result.status = result.status || "NOP";
return result;
} finally {
this.istate = ContainerState.Ready;
}
}
public async httpRequest(req: HttpRequest): Promise<HttpResponse> {
if (this.istate !== ContainerState.Ready) throw new InternalServerError("Invalid container state");
this.istate = ContainerState.Reserved;
try {
req.type = "http";
this.log.debug("HTTP Event: %j", req);
req.contentType = HttpUtils.contentType(req.headers, req.body);
let key = `${req.httpMethod} ${req.resource}`;
if (req.contentType.domainModel) key += `:${req.contentType.domainModel}`;
let handler = this.httpHandlers && this.httpHandlers[key];
if (!handler) throw this.log.error(new NotFound(`Route not found [${key}]`));
let target = this.imetadata.httpMetadata[key];
req.application = this.application;
req.service = target.service;
req.method = target.method;
let permissionId = req.service + "." + req.method;
let permission = permissionId && this.imetadata.permissions[permissionId];
if (permission == null) throw this.log.error(new Forbidden(`Undefined permission for method [${permissionId}]`));
this.istate = ContainerState.Busy;
let ctx = await this.security.httpAuth(req, permission);
try {
await this.activate(ctx);
HttpUtils.body(req);
this.log.debug("HTTP Context: %j", ctx);
this.log.debug("HTTP Request: %j", req);
let res = await handler(ctx, req);
if (res.contentType === HttpResponse) res = res.body;
if (ctx && ctx.auth.renewed && ctx.auth.token) {
res.headers = res.headers || {};
res.headers["Token"] = ctx.auth.token;
}
this.log.debug("Response: %j", res);
return res;
} catch (e) {
this.log.error(e);
throw InternalServerError.wrap(e);
} finally {
await this.release(ctx);
}
} finally {
this.istate = ContainerState.Ready;
}
}
public async activate(ctx: Context): Promise<Context> {
for (let sid in this.services) {
let service = this.services[sid];
try {
if (service.activate) await service.activate(ctx);
} catch (e) {
this.log.error("Failed to activate service: [%s]", sid);
this.log.error(e);
throw e;
// TODO: Error state for container
}
}
return ctx;
}
public async release(ctx: Context): Promise<void> {
for (let sid in this.services) {
let service = this.services[sid];
try {
if (service.release) await service.release(ctx);
} catch (e) {
this.log.error("Failed to release service: [%s]", sid);
this.log.error(e);
// TODO: Error state for container
}
}
}
} | the_stack |
import { ipcRenderer, remote, shell } from "electron";
import { join } from "path";
import { pathExists } from "fs-extra";
import { IPCRequests, IPCResponses } from "../../shared/ipc";
import { IStringDictionary, Nullable, Undefinable } from "../../shared/types";
import * as React from "react";
import * as ReactDOM from "react-dom";
import { Toaster, Position, ProgressBar, Intent, Classes, IToastProps, IconName, MaybeElement } from "@blueprintjs/core";
import { Layout, Model, TabNode, Rect, Actions } from "flexlayout-react";
import {
Engine, Scene, Observable, ISize, Node, BaseTexture, Material, Vector3, CannonJSPlugin,
SubMesh, Animation, AbstractMesh, IParticleSystem, Sound, KeyboardInfo, KeyboardEventTypes,
Color4, SceneLoader, Skeleton,
} from "babylonjs";
import { Overlay } from "./gui/overlay";
import { ActivityIndicator } from "./gui/acitivity-indicator";
import { Confirm } from "./gui/confirm";
import { Tools } from "./tools/tools";
import { IPCTools } from "./tools/ipc";
import { IObjectModified, IEditorPreferences, EditorPlayMode } from "./tools/types";
import { undoRedo } from "./tools/undo-redo";
import { AbstractEditorPlugin } from "./tools/plugin";
import { EditorUpdater } from "./tools/update/updater";
import { TouchBarHelper } from "./tools/touch-bar";
import { IFile } from "./project/files";
import { WorkSpace } from "./project/workspace";
import { Project } from "./project/project";
import { ProjectImporter } from "./project/project-importer";
import { ProjectExporter } from "./project/project-exporter";
import { WelcomeDialog } from "./project/welcome/welcome";
import { SceneSettings } from "./scene/settings";
import { GizmoType } from "./scene/gizmo";
import { SceneUtils } from "./scene/utils";
import { SandboxMain } from "../sandbox/main";
import { IPlugin, IPluginConfiguration } from "./plugins/plugin";
import { IPluginToolbar } from "./plugins/toolbar";
import "./painting/material-mixer/material";
// Loaders
import { FBXLoader } from "./loaders/fbx/loader";
// Components
import { Inspector } from "./components/inspector";
import { Graph } from "./components/graph";
import { Assets } from "./components/assets";
import { Preview } from "./components/preview";
import { MainToolbar } from "./components/main-toolbar";
import { ToolsToolbar } from "./components/tools-toolbar";
import { Console } from "./components/console";
// Augmentations
import "./gui/augmentations/index";
// Inspectors
import "./inspectors/scene/scene-inspector";
import "./inspectors/scene/rendering-inspector";
import "./inspectors/scene/animation-groups-inspector";
import "./inspectors/node-inspector";
import "./inspectors/node/mesh-inspector";
import "./inspectors/node/transform-node-inspector";
import "./inspectors/node/sub-mesh-proxy-inspector";
import "./inspectors/node/sub-mesh-inspector";
import "./inspectors/node/ground-inspector";
import "./inspectors/lights/light-inspector";
import "./inspectors/lights/directional-light-inspector";
import "./inspectors/lights/spot-light-inspector";
import "./inspectors/lights/point-light-inspector";
import "./inspectors/lights/hemispheric-light-inspector";
import "./inspectors/lights/shadows-inspector";
import "./inspectors/cameras/camera-inspector";
import "./inspectors/cameras/free-camera-inspector";
import "./inspectors/cameras/arc-rotate-camera-inspector";
import "./inspectors/materials/standard-inspector";
import "./inspectors/materials/pbr-inspector";
import "./inspectors/materials/sky-inspector";
import "./inspectors/materials/node-inspector";
import "./inspectors/materials/cell-inspector";
import "./inspectors/materials/fire-inspector";
import "./inspectors/materials/lava-inspector";
import "./inspectors/materials/water-inspector";
import "./inspectors/materials/tri-planar-inspector";
import "./inspectors/textures/texture-inspector";
import "./inspectors/particle-systems/particle-system-inspector";
import "./inspectors/particle-systems/particle-system-gradients-inspector";
import "./inspectors/sound/sound-inspector";
// Assets
import { MeshesAssets } from "./assets/meshes";
import { MaterialAssets } from "./assets/materials";
import { TextureAssets } from "./assets/textures";
import { SoundAssets } from "./assets/sounds";
import { ScriptAssets } from "./assets/scripts";
import { GraphAssets } from "./assets/graphs";
import { PrefabAssets } from "./assets/prefabs";
// Extensions
import { WebpackProgressExtension } from "./extensions/webpack-progress";
// Json
import layoutConfiguration from "./layout.json";
export interface ILayoutTabNodeConfiguration {
/**
* Defines the name of the layout tab node.
*/
componentName: "preview" | "inspector" | "console" | "assets" | "graph" | string;
/**
* Defines the name of the tab component.
*/
name: string;
/**
* Defines the id of the layout tab node.
*/
id: string;
/**
* Defines the id of the tab node in the layout.
*/
rect: Rect;
}
export class Editor {
/**
* Reference to the Babylon.JS engine used to render the preview scene.
*/
public engine: Nullable<Engine> = null;
/**
* Reference to the Babylon.JS scene rendered by the preview component.
*/
public scene: Nullable<Scene> = null;
/**
* Reference to the layout used to create the editor's sections.
*/
public layout: Layout;
/**
* Reference to the inspector tool used to edit objects in the scene.
*/
public inspector: Inspector;
/**
* Reference to the graph tool used to show and edit hierarchy in the scene..
*/
public graph: Graph;
/**
* Reference to the assets tool used to show and edit assets of the project (meshes, prefabs, etc.)..
*/
public assets: Assets;
/**
* Reference to the preview element used to draw the project's scene.
*/
public preview: Preview;
/**
* Reference to the main toolbar.
*/
public mainToolbar: MainToolbar;
/**
* Reference to the tools toolbar.
*/
public toolsToolbar: ToolsToolbar;
/**
* Reference to the console.
*/
public console: Console;
/**
* Defines the dictionary of all avaiable loaded plugins in the editor.
*/
public plugins: IStringDictionary<AbstractEditorPlugin<any>> = {};
/**
* Reference to the scene utils.
*/
public sceneUtils: SceneUtils;
/**
* Notifies observers once the editor has been initialized.
*/
public editorInitializedObservable: Observable<void> = new Observable<void>();
/**
* Notifies observers on the editor is resized (window, layout, etc.).
*/
public resizeObservable: Observable<void> = new Observable<void>();
/**
* Notifies observers on the editor modified an object (typically inspectors).
*/
public objectModifiedObservable: Observable<IObjectModified<any>> = new Observable<IObjectModified<any>>();
/**
* Notifies observers on the editor modfies an object (typically inspectors).
*/
public objectModigyingObservable: Observable<IObjectModified<any>> = new Observable<IObjectModified<any>>();
/**
* Notifies observers that a node has been selected in the editor (preview or graph).
*/
public selectedNodeObservable: Observable<Node> = new Observable<Node>();
/**
* Notifies observers that a submesh has been selected in the editor (preview or graph).
*/
public selectedSubMeshObservable: Observable<SubMesh> = new Observable<SubMesh>();
/**
* Notifies observers that a particle system has been selected in the editor (preview or graph).
*/
public selectedParticleSystemObservable: Observable<IParticleSystem> = new Observable<IParticleSystem>();
/**
* Notifies observers that a texture has been selected in the editor (assets).
*/
public selectedTextureObservable: Observable<BaseTexture> = new Observable<BaseTexture>();
/**
* Notifies observers that a material has been selected in the editor (assets).
*/
public selectedMaterialObservable: Observable<Material> = new Observable<Material>();
/**
* Notifies observers that the scene has been selected in the editor (graph).
*/
public selectedSceneObservable: Observable<Scene> = new Observable<Scene>();
/**
* Notifies observers that a sound has been selected in the editor (graph, preview).
*/
public selectedSoundObservable: Observable<Sound> = new Observable<Sound>();
/**
* Notifies observers that a skeleton has been selected in the editor (graph).
*/
public selectedSkeletonObservable: Observable<Skeleton> = new Observable<Skeleton>();
/**
* Notifies observers that a node has been added in the editor.
*/
public addedNodeObservable: Observable<Node> = new Observable<Node>();
/**
* Notifies observers that a particle system has been added in the editor.
*/
public addedParticleSystemObservable: Observable<IParticleSystem> = new Observable<IParticleSystem>();
/**
* Notifies observers that a sound has been added in the editor.
*/
public addedSoundObservable: Observable<Sound> = new Observable<Sound>();
/**
* Notifies observers that a node has been removed in the editor (graph, preview, etc.).
*/
public removedNodeObservable: Observable<Node> = new Observable<Node>();
/**
* Notifies observers that a particle system has been removed in the editor (graph, preview, etc.).
*/
public removedParticleSystemObservable: Observable<IParticleSystem> = new Observable<IParticleSystem>();
/**
* Notifies observers that a sound has been removed in the editor (graph, preview, etc.).
*/
public removedSoundObservable: Observable<Sound> = new Observable<Sound>();
/**
* Notifies observers that a keyboard event has been fired.
*/
public keyboardEventObservable: Observable<KeyboardInfo> = new Observable<KeyboardInfo>();
/**
* Notifies observers that the project will be saved.
*/
public beforeSaveProjectObservable: Observable<string> = new Observable<string>();
/**
* Notifies observers that the project has been saved.
*/
public afterSaveProjectObservable: Observable<string> = new Observable<string>();
/**
* Notifies observers that the scene will be generated.
*/
public beforeGenerateSceneObservable: Observable<string> = new Observable<string>();
/**
* Notifies observers that the scene has been generated.
*/
public afterGenerateSceneObservable: Observable<string> = new Observable<string>();
/**
* Defines the current editor version.
* @hidden
*/
public _packageJson: any = {};
/**
* @hidden
*/
public _byPassBeforeUnload: boolean;
/**
* @hidden
*/
public _toaster: Nullable<Toaster> = null;
/**
* Defines the dictionary of all configurations for all tab nodes. This configuration is updated each time a node
* event is triggered, like "resize".
* @hidden
*/
public readonly _layoutTabNodesConfigurations: Record<string, ILayoutTabNodeConfiguration> = {};
private _components: IStringDictionary<React.ReactNode> = {};
private _taskFeedbacks: IStringDictionary<{
message: string;
amount: number;
timeout: number;
}> = {};
private _activityIndicator: Nullable<ActivityIndicator> = null;
private _refHandlers = {
getToaster: (ref: Toaster) => (this._toaster = ref),
getActivityIndicator: (ref: ActivityIndicator) => (this._activityIndicator = ref),
};
private _isInitialized: boolean = false;
private _isProjectReady: boolean = false;
private _closing: boolean = false;
private _pluginWindows: number[] = [];
private _preferences: Nullable<IEditorPreferences> = null;
/**
* Defines the current version of the layout.
*/
public static readonly LayoutVersion = "4.0.0";
/**
* Defines the dictionary of all loaded plugins in the editor.
*/
public static LoadedPlugins: IStringDictionary<{ name: string; fullPath?: boolean; }> = {};
/**
* Defines the dictionary of all loaded external plugins in the editor.
*/
public static LoadedExternalPlugins: IStringDictionary<IPlugin> = {};
/**
* Constructor.
*/
public constructor() {
// Register assets
MeshesAssets.Register();
MaterialAssets.Register();
TextureAssets.Register();
SoundAssets.Register();
ScriptAssets.Register();
GraphAssets.Register();
PrefabAssets.Register();
// Register loaders
SceneLoader.RegisterPlugin(new FBXLoader());
// Create toolbar
ReactDOM.render(<MainToolbar editor={this} />, document.getElementById("BABYLON-EDITOR-MAIN-TOOLBAR"));
ReactDOM.render(<ToolsToolbar editor={this} />, document.getElementById("BABYLON-EDITOR-TOOLS-TOOLBAR"));
// Toaster
ReactDOM.render(<Toaster canEscapeKeyClear={true} position={Position.BOTTOM_LEFT} ref={this._refHandlers.getToaster}></Toaster>, document.getElementById("BABYLON-EDITOR-TOASTS"));
// Activity Indicator
ReactDOM.render(
<ActivityIndicator size={25} ref={this._refHandlers.getActivityIndicator} onClick={() => this._revealAllTasks()}></ActivityIndicator>,
document.getElementById("BABYLON-EDITOR-ACTIVITY-INDICATOR"),
);
// Empty touchbar
TouchBarHelper.SetTouchBarElements([]);
// Init!
this.init();
}
/**
* Called on the component did mount.
*/
public async init(): Promise<void> {
document.getElementById("BABYLON-START-IMAGE")?.remove();
Overlay.Show("Loading Editor...", true);
// Get version
this._packageJson = JSON.parse(await Tools.LoadFile("../package.json", false));
document.title = `Babylon.JS Editor v${this._packageJson.version}`;
// Register default components
this._components["preview"] = <Preview editor={this} />;
this._components["inspector"] = <Inspector editor={this} />;
this._components["assets"] = <Assets editor={this} />;
this._components["graph"] = <Graph editor={this} />;
this._components["console"] = <Console editor={this} />;
// Retrieve preview layout state for plugins.
try {
const loadedPluginsItem = localStorage.getItem("babylonjs-editor-loaded-plugins");
if (loadedPluginsItem) {
Editor.LoadedPlugins = JSON.parse(loadedPluginsItem);
for (const key in Editor.LoadedPlugins) {
const name = Editor.LoadedPlugins[key].name;
const plugin = Editor.LoadedPlugins[key].fullPath ? require(name) : require(`../tools/${name}`);
this._components[name] = <plugin.default editor={this} id={plugin.title} />;
}
}
} catch (e) {
this._resetEditor();
}
// Mount layout
const layoutVersion = localStorage.getItem('babylonjs-editor-layout-version');
const layoutStateItem = (layoutVersion === Editor.LayoutVersion) ? localStorage.getItem('babylonjs-editor-layout-state') : null;
const layoutState = layoutStateItem ? JSON.parse(layoutStateItem) : layoutConfiguration;
const layoutModel = Model.fromJson(layoutState);
ReactDOM.render((
<Layout ref={(r) => this.layout = r!} model={layoutModel} factory={(n) => this._layoutFactory(n)} />
), document.getElementById("BABYLON-EDITOR"), () => {
setTimeout(() => this._init(), 0);
});
}
/**
* Called each time a FlexLayout.TabNode is mounted by React.
*/
private _layoutFactory(node: TabNode): React.ReactNode {
const componentName = node.getComponent();
if (!componentName) {
this.console.logError("Can't mount layout node without component name.");
return <div>Error, see console...</div>;
}
const component = this._components[componentName];
if (!component) {
this.console.logError(`No react component available for "${componentName}".`);
return <div>Error, see console...</div>;
}
this._layoutTabNodesConfigurations[componentName] ??= {
componentName,
id: node.getId(),
name: node.getName(),
rect: node.getRect(),
};
node.setEventListener("resize", (ev: { rect: Rect }) => {
const configuration = this._layoutTabNodesConfigurations[componentName];
configuration.rect = ev.rect;
setTimeout(() => this.resize(), 0);
});
if (Editor.LoadedPlugins[componentName]) {
node.setEventListener("close", () => {
setTimeout(() => this.closePlugin(componentName), 0);
});
node.setEventListener("visibility", (p) => {
const plugin = this.plugins[node.getName()];
if (p.visible) {
plugin?.onShow();
} else {
plugin?.onHide();
}
});
}
return component;
}
/**
* Resizes the editor.
*/
public resize(): void {
this.engine!.resize();
this.inspector.resize();
this.assets.resize();
this.console.resize();
this.engine?.resize();
for (const p in this.plugins) {
const panel = this.getPanelSize(p);
this.plugins[p].resize(panel.width, panel.height);
}
this.resizeObservable.notifyObservers();
}
/**
* Returns wether or not the editor has been initialized.
*/
public get isInitialized(): boolean {
return this._isInitialized;
}
/**
* Returns wether or not the project is fully ready.
*/
public get isProjectReady(): boolean {
return this._isProjectReady;
}
/**
* Returns the current size of the panel identified by the given id.
* @param panelId the id of the panel to retrieve its size.
*/
public getPanelSize(panelId: string): ISize {
let configuration: Nullable<ILayoutTabNodeConfiguration> = null; // = this._layoutTabNodesConfigurations[panelId];
for (const key in this._layoutTabNodesConfigurations) {
if (key === panelId || this._layoutTabNodesConfigurations[key].name === panelId) {
configuration = this._layoutTabNodesConfigurations[key];
}
}
if (!configuration) {
return { width: 0, height: 0 };
}
return { width: configuration.rect.width, height: configuration.rect.height };
}
/**
* Adds a new task feedback (typically when saving the project).
* @param amount the amount of progress for the task in interval [0; 100].
* @param message the message to show.
*/
public addTaskFeedback(amount: number, message: string, timeout: number = 10000): string {
const key = this._toaster?.show(this._renderTaskFeedback(amount, message, timeout));
if (!key) { throw "Can't create a new task feedback" }
this._activityIndicator?.setState({ enabled: true });
this._taskFeedbacks[key] = { amount, message, timeout };
return key;
}
/**
* Updates the task feedback identified by the given key.
* @param key the key that identifies the task feedback.
* @param amount the new amount of the progress bar.
* @param message the new message to show.
*/
public updateTaskFeedback(key: string, amount: number, message?: string): void {
const task = this._taskFeedbacks[key];
if (task === undefined) { throw "Can't update an unexisting feedback."; }
task.message = message ?? task.message;
this._toaster?.show(this._renderTaskFeedback(amount ?? task.amount, task.message, task.timeout), key);
}
/**
* Closes the toast identified by the given id.
* @param key the key of the existing toast.
* @param timeout the time in Ms to wait before dismiss.
*/
public closeTaskFeedback(key: string, timeout: number = 0): void {
setTimeout(() => {
this._toaster?.dismiss(key);
delete this._taskFeedbacks[key];
if (!Object.keys(this._taskFeedbacks).length) {
this._activityIndicator?.setState({ enabled: false });
}
}, timeout);
}
/**
* Notifies the user the given message.
* @param message defines the message to notify.
* @param timeout defines the time in ms before hidding the notification.
* @param icon odefines the ptional icon to show in the toast.
* @param intent defines the visual intent color.
*/
public notifyMessage(message: string, timeout: number = 1000, icon: IconName | MaybeElement = "notifications", intent: Intent = "none"): void {
this._toaster?.show({
message,
timeout,
className: Classes.DARK,
icon,
intent,
}, message);
}
/**
* Adds a new plugin to the layout.
* @param name the name of the plugin to laod.
* @param openParameters defines the optional reference to the opening parameters.
*/
public addBuiltInPlugin(name: string, openParameters: any = {}): void {
const plugin = require(`../tools/${name}`);
this._addPlugin(plugin, name, false, openParameters);
}
/**
* Adds the given plugin to the editor's layout.
* @param path defines the path of the plugin.
* @param openParameters defines the optional reference to the opening parameters.
*/
public addPluginFromPath(path: string, openParameters: any = {}): void {
const plugin = require(path);
this._addPlugin(plugin, path, true, openParameters);
}
/**
* Closes the plugin identified by the given name.
* @param pluginName the name of the plugin to close.
*/
public closePlugin(pluginName: string): void {
let effectiveKey = pluginName;
for (const key in this._layoutTabNodesConfigurations) {
if (this._layoutTabNodesConfigurations[key].name === pluginName) {
effectiveKey = this._layoutTabNodesConfigurations[key].componentName;
break;
}
}
this.layout.props.model.doAction(Actions.deleteTab(effectiveKey));
const configuration = this._layoutTabNodesConfigurations[pluginName];
if (configuration && this.plugins[configuration.name]) {
delete this.plugins[configuration.name];
}
delete this._components[effectiveKey];
delete Editor.LoadedPlugins[effectiveKey];
this.resize();
}
/**
* Adds a new plugin handled by its own window.
* @param name the name of the plugin to load.
* @param windowId the id of the window that is possibly already opened.
* @param args optional arguments to pass the plugn's .init function.
*/
public async addWindowedPlugin(name: string, windowId?: Undefinable<number>, ...args: any[]): Promise<Nullable<number>> {
// Check if the provided window id exists. If exists, just restore.
if (windowId) {
const index = this._pluginWindows.indexOf(windowId);
if (index !== -1) {
IPCTools.Send(IPCRequests.FocusWindow, windowId);
return null;
}
}
const width = 1280;
const height = 800;
const popupId = await IPCTools.CallWithPromise<number>(IPCRequests.OpenWindowOnDemand, {
options: {
title: name,
width,
height,
x: window.screenX + Math.max(window.outerWidth - width, 0) / 2,
y: window.screenY + Math.max(window.outerHeight - height, 0) / 2,
resizable: true,
autoHideMenuBar: true,
webPreferences: {
nodeIntegration: true,
zoomFactor: parseFloat(this.getPreferences()?.zoom ?? "1"),
},
},
url: "./plugin.html",
autofocus: true,
});
this._pluginWindows.push(popupId);
ipcRenderer.once(IPCRequests.SendWindowMessage, (_, data) => {
if (data.id === "pluginName" && data.popupId === popupId) {
IPCTools.SendWindowMessage(popupId, "pluginName", { name, args });
}
});
return popupId;
}
/**
* Adds a new preview.
*/
public addPreview(): void {
const preview = require("../tools/preview");
const plugin = {
title: "Preview 1",
default: preview.default,
};
this._addPlugin(plugin, "preview", false);
}
/**
* Runs the project.
* @param integratedBrowser defines wether or not the integrated browser should be used to run the project.
* @param https defines wether or not an HTTPS server should be used to serve the project.
*/
public async runProject(mode: EditorPlayMode, https: boolean): Promise<void> {
await ProjectExporter.ExportFinalScene(this);
const task = this.addTaskFeedback(0, "Running Server");
const workspace = WorkSpace.Workspace!;
const httpsConfig = https ? workspace.https : undefined;
const serverResult = await IPCTools.CallWithPromise<{ ips?: string[]; error?: string }>(IPCRequests.StartGameServer, WorkSpace.DirPath!, workspace.serverPort, httpsConfig);
this.updateTaskFeedback(task, 100);
this.closeTaskFeedback(task, 500);
if (serverResult?.error) {
return this.notifyMessage(`Failed to run server: ${serverResult.error}`, 3000, null, "danger");
}
const protocol = https ? "https" : "http";
this.console.logSection("Running Game Server");
if (serverResult.ips) {
const log = this.console.logInfo("");
if (log) {
log.innerHTML = `
Server is running:
<ul>${serverResult.ips.map((ip) => `<li>${protocol}://${ip}:${workspace.serverPort}</li>`).join("")}</ul>
`;
log.style.color = "green";
}
}
this.console.logInfo("Server is running.");
switch (mode) {
case EditorPlayMode.EditorPanelBrowser:
this.addBuiltInPlugin("run");
break;
case EditorPlayMode.IntegratedBrowser:
this.addWindowedPlugin("run", undefined, workspace);
break;
case EditorPlayMode.ExternalBrowser:
shell.openExternal(`${protocol}://localhost:${workspace.serverPort}`);
break;
}
}
/**
* Reveals the panel identified by the given Id.
* @param panelId the id of the panel to reveal.
*/
public revealPanel(panelId: string): void {
this.layout.props.model.doAction(Actions.selectTab(panelId));
}
/**
* Returns the current settings of the editor.
*/
public getPreferences(): IEditorPreferences {
return this._preferences ?? Tools.GetEditorPreferences();
}
/**
* Sets wether or not the editor's scene should be rendered.
* @param render defines wether or not the render loop should render the editor's scene.
*/
public runRenderLoop(render: boolean): void {
if (!render) {
this.engine?.stopRenderLoop();
this.engine?.clear(new Color4(0, 0, 0, 1), true, true, true);
} else {
this.engine?.runRenderLoop(() => {
this.scene!.render();
SceneSettings.UpdateArcRotateCameraPanning();
});
}
}
/**
* Adds the given plugin into the layout.
*/
private _addPlugin(plugin: any, name: string, fullPath: boolean, openParameters: any = {}): void {
if (this._components[name]) {
this.layout.props.model.doAction(Actions.selectTab(name));
return;
}
// Register plugin
Editor.LoadedPlugins[name] = { name, fullPath };
// Add component
this._components[name] = <plugin.default editor={this} id={plugin.title} openParameters={openParameters} />;
this.layout.addTabToActiveTabSet({ type: "tab", name: plugin.title, component: name, id: name });
}
/**
* Inits the launch of the editor's project.
*/
private async _init(): Promise<void> {
// Create Babylon.JS stuffs
this.engine = new Engine(document.getElementById("renderCanvas") as HTMLCanvasElement, true, {
antialias: true,
audioEngine: true,
disableWebGL2Support: false,
powerPreference: "high-performance",
failIfMajorPerformanceCaveat: false,
useHighPrecisionFloats: true,
preserveDrawingBuffer: true,
stencil: true,
}, true);
this.scene = new Scene(this.engine);
this.runRenderLoop(true);
// Camera
this.scene.activeCamera = SceneSettings.Camera ?? SceneSettings.GetArcRotateCamera(this);
// Post-processes
SceneSettings.GetSSAORenderingPipeline(this);
SceneSettings.GetDefaultRenderingPipeline(this);
// Physics
this.scene.enablePhysics(Vector3.Zero(), new CannonJSPlugin());
// Animations
Animation.AllowMatricesInterpolation = true;
// Utils
this.sceneUtils = new SceneUtils(this);
this._bindEvents();
this.resize();
// Hide overlay
Overlay.Hide();
// Reveal console
this.revealPanel("console");
// Init sandbox
await SandboxMain.Init();
// Refresh preferences
this._applyPreferences();
// Check workspace
const workspacePath = await WorkSpace.GetOpeningWorkspace();
if (workspacePath) {
await WorkSpace.ReadWorkSpaceFile(workspacePath);
await WorkSpace.RefreshAvailableProjects();
}
// Get opening project
const projectPath = workspacePath ? WorkSpace.GetProjectPath() : await Project.GetOpeningProject();
if (projectPath) {
await ProjectImporter.ImportProject(this, projectPath);
// Assets
this.assets.getComponent(TextureAssets)?.refreshCompressedTexturesFiles();
} else {
this.graph.refresh();
WelcomeDialog.Show(this, false);
}
// Console
this.console.overrideLogger();
// Refresh
this.mainToolbar.setState({ hasWorkspace: workspacePath !== null });
this.toolsToolbar.setState({ hasWorkspace: WorkSpace.HasWorkspace() });
// Now initialized!
this._isInitialized = true;
const workspace = WorkSpace.Workspace;
if (workspace) {
// Plugins
for (const p in workspace.pluginsPreferences ?? {}) {
const plugin = Editor.LoadedExternalPlugins[p];
if (!plugin?.setWorkspacePreferences) { continue; }
const preferences = workspace.pluginsPreferences![p];
try {
plugin.setWorkspacePreferences(preferences);
} catch (e) {
console.error(e);
}
}
}
// Notify!
this.editorInitializedObservable.notifyObservers();
this.selectedSceneObservable.notifyObservers(this.scene!);
// If has workspace, od workspace stuffs.
if (workspace) {
// Set editor touch bar
this._setTouchBar();
// Extensions
WebpackProgressExtension.Initialize(this);
// First load?
if (!(await pathExists(join(WorkSpace.DirPath!, "scenes", WorkSpace.GetProjectName())))) {
await ProjectExporter.ExportFinalScene(this);
}
const hasNodeModules = await pathExists(join(WorkSpace.DirPath!, "node_modules"));
const hasPackageJson = await pathExists(join(WorkSpace.DirPath!, "package.json"));
if (!hasNodeModules && hasPackageJson) {
await WorkSpace.InstallAndBuild(this);
}
// Watch typescript project.
await WorkSpace.WatchTypeScript(this);
// Watch project?
if (workspace.watchProject) {
await WorkSpace.WatchProject(this);
}
}
this._isProjectReady = true;
// Check for updates
EditorUpdater.CheckForUpdates(this, false);
}
/**
* Renders a task with the given amount (progress bar) and message.
*/
private _renderTaskFeedback(amount: number, message: string, timeout: number): IToastProps {
return {
icon: "cloud-upload",
timeout,
className: Classes.DARK,
message: (
<>
<p><strong>{message}</strong></p>
<ProgressBar
intent={amount < 100 ? Intent.PRIMARY : Intent.SUCCESS}
value={amount / 100}
/>
</>
),
}
}
/**
* Called on the user wants to reveal all the tasks for information.
*/
private _revealAllTasks(): void {
if (!Object.keys(this._taskFeedbacks).length) { return; }
for (const key in this._taskFeedbacks) {
const task = this._taskFeedbacks[key];
this.updateTaskFeedback(key, task.amount, task.message);
}
}
/**
* Binds the events of the overall editor main events;
*/
private _bindEvents(): void {
// IPC
ipcRenderer.on(IPCRequests.SendWindowMessage, async (_, message) => {
switch (message.id) {
// A window has been closed
case "close-window":
const index = this._pluginWindows.indexOf(message.windowId);
if (index !== -1) { this._pluginWindows.splice(index, 1); }
break;
// An editor function should be executed
case "execute-editor-function":
const caller = Tools.GetEffectiveProperty(this, message.data.functionName);
const fn = Tools.GetProperty<(...args: any[]) => any>(this, message.data.functionName);
try {
const result = await fn.call(caller, ...message.data.args);
IPCTools.SendWindowMessage(message.data.popupId, "execute-editor-function", result);
} catch (e) {
IPCTools.SendWindowMessage(message.data.popupId, "execute-editor-function");
}
break;
}
});
// Editor events coordinator
this.selectedNodeObservable.add((o, ev) => {
this.inspector.setSelectedObject(o);
this.preview.gizmo.setAttachedNode(o);
if (ev.target !== this.graph) { this.graph.setSelected(o, ev.userInfo?.ctrlDown); }
});
this.selectedSubMeshObservable.add((o, ev) => {
this.inspector.setSelectedObject(o);
this.preview.gizmo.setAttachedNode(o.getMesh());
if (ev.target !== this.graph) { this.graph.setSelected(o.getMesh()); }
});
this.selectedParticleSystemObservable.add((o, ev) => {
this.inspector.setSelectedObject(o);
if (o.emitter instanceof AbstractMesh) {
this.preview.gizmo.setAttachedNode(o.emitter);
}
if (ev.target !== this.graph) { this.graph.setSelected(o); }
});
this.selectedSoundObservable.add((o, ev) => {
this.inspector.setSelectedObject(o);
if (o["_connectedTransformNode"]) {
this.preview.gizmo.setAttachedNode(o);
}
if (ev.target !== this.graph) { this.graph.setSelected(o); }
});
this.selectedSceneObservable.add((s) => this.inspector.setSelectedObject(s));
this.selectedTextureObservable.add((t) => this.inspector.setSelectedObject(t));
this.selectedMaterialObservable.add((m) => this.inspector.setSelectedObject(m));
this.selectedSkeletonObservable.add((s) => this.inspector.setSelectedObject(s));
this.objectModigyingObservable.add(() => {
// Nothing to to now...
});
this.removedNodeObservable.add(() => {
this.preview.picker.reset();
});
this.removedParticleSystemObservable.add(() => {
this.preview.picker.reset();
});
this.removedSoundObservable.add(() => {
this.preview.picker.reset();
});
this.addedNodeObservable.add(() => {
// Nothing to do now...
});
// Resize
window.addEventListener("resize", () => {
this.resize();
});
// Close window
ipcRenderer.on("quit", async () => {
if (!WorkSpace.HasWorkspace()) {
return ipcRenderer.send("quit", true);
}
const shouldQuit = await Confirm.Show("Quit Editor?", "Are you sure to quit the editor? All unsaved work will be lost.");
if (shouldQuit) { this._byPassBeforeUnload = true; }
ipcRenderer.send("quit", shouldQuit);
});
// Save
ipcRenderer.on("save", () => ProjectExporter.Save(this));
// ipcRenderer.on("save-as", () => ProjectExporter.SaveAs(this));
// Undo / Redo
ipcRenderer.on("undo", () => !(document.activeElement instanceof HTMLInputElement) && undoRedo.undo());
ipcRenderer.on("redo", () => !(document.activeElement instanceof HTMLInputElement) && undoRedo.redo());
// Copy / Paste
document.addEventListener("copy", () => {
if (this.preview.canvasFocused) { return this.preview.copySelectedNode(); }
});
document.addEventListener("paste", () => {
if (this.preview.canvasFocused) { return this.preview.pasteCopiedNode(); }
});
// Search
ipcRenderer.on("search", () => this.preview.showSearchBar());
// Project
ipcRenderer.on("build-project", () => WorkSpace.BuildProject(this));
ipcRenderer.on("build-and-run-project", async () => {
await WorkSpace.BuildProject(this);
this.runProject(EditorPlayMode.IntegratedBrowser, false);
});
ipcRenderer.on("run-project", () => this.runProject(EditorPlayMode.IntegratedBrowser, false));
ipcRenderer.on("generate-project", () => ProjectExporter.ExportFinalScene(this));
ipcRenderer.on("play-project", () => this.toolsToolbar.handlePlay());
// Drag'n'drop
document.addEventListener("dragover", (ev) => ev.preventDefault());
document.addEventListener("drop", (ev) => {
if (!ev.dataTransfer || !ev.dataTransfer.files.length) { return; }
const files: IFile[] = [];
const sources = ev.dataTransfer.files;
for (let i = 0; i < sources.length; i++) {
const file = sources.item(i);
if (file) { files.push({ path: file.path, name: file.name } as IFile); }
}
if (files.length) { this.assets.addDroppedFiles(ev, files); }
});
// Shortcuts
window.addEventListener("keyup", (ev) => {
this.keyboardEventObservable.notifyObservers(new KeyboardInfo(KeyboardEventTypes.KEYUP, ev));
if (this.preview.canvasFocused) {
if (ev.key === "t") { return this.preview.setGizmoType(GizmoType.Position); }
if (ev.key === "r") { return this.preview.setGizmoType(GizmoType.Rotation); }
if (ev.key === "w") { return this.preview.setGizmoType(GizmoType.Scaling); }
if (ev.key === "f") { return this.preview.focusSelectedNode(true); }
if (ev.key === "F") { return this.preview.focusSelectedNode(false); }
if (ev.key === "i") { return this.preview.toggleIsolatedMode(); }
if (ev.keyCode === 46) { return this.preview.removeSelectedNode(); }
if (ev.keyCode === 27) {
if (this.preview.state.isIsolatedMode) { return this.preview.toggleIsolatedMode(); }
}
}
if (!ev.ctrlKey && SceneSettings.Camera?.metadata.detached) {
SceneSettings.Camera.metadata.detached = false;
for (const i in SceneSettings.Camera.inputs.attached) {
const input = SceneSettings.Camera.inputs.attached[i];
SceneSettings.Camera.inputs.attachInput(input);
}
}
});
window.addEventListener("keydown", (ev) => {
this.keyboardEventObservable.notifyObservers(new KeyboardInfo(KeyboardEventTypes.KEYDOWN, ev));
if (ev.ctrlKey && SceneSettings.Camera) {
for (const i in SceneSettings.Camera.inputs.attached) {
const input = SceneSettings.Camera.inputs.attached[i];
input.detachControl();
}
SceneSettings.Camera.metadata = SceneSettings.Camera.metadata ?? {};
SceneSettings.Camera.metadata.detached = true;
}
});
// State
window.addEventListener("beforeunload", async (e) => {
if (this._byPassBeforeUnload) { return; }
if (WorkSpace.HasWorkspace() && !this._closing) {
e.returnValue = false;
this._closing = await Confirm.Show("Close project?", "Are you sure to close the project? All unsaved work will be lost.");
if (this._closing) { window.location.reload(); }
return;
}
// Windows
this._pluginWindows.forEach((id) => IPCTools.Send(IPCRequests.CloseWindow, id));
// Processes
if (WorkSpace.HasWorkspace()) { WorkSpace.KillAllProcesses(); }
});
}
/**
* Sets the editor touch bar for Mac OS systems.
*/
private _setTouchBar(): void {
// Touch bar
TouchBarHelper.SetTouchBarElements([
{
label: "Build...",
click: "build-project",
},
{
label: "Generate...",
click: "generate-project",
},
{
separator: true,
},
{
label: "Run...",
click: "run-project",
icon: "assets/extras/play.png",
},
]);
}
/**
* Saves the editor configuration.
* @hidden
*/
public _saveEditorConfig(): void {
const config = this.layout.props.model.toJson();
localStorage.setItem("babylonjs-editor-layout-state", JSON.stringify(config));
localStorage.setItem("babylonjs-editor-layout-version", Editor.LayoutVersion);
localStorage.setItem("babylonjs-editor-loaded-plugins", JSON.stringify(Editor.LoadedPlugins));
}
/**
* Resets the editor.
* @hidden
*/
public _resetEditor(): void {
localStorage.removeItem("babylonjs-editor-layout-state");
localStorage.removeItem("babylonjs-editor-layout-version");
localStorage.removeItem("babylonjs-editor-loaded-plugins");
window.location.reload();
}
/**
* Called by the workspace settings windows.
* @hidden
*/
public async _refreshWorkSpace(): Promise<void> {
await WorkSpace.ReadWorkSpaceFile(WorkSpace.Path!);
const workspace = WorkSpace.Workspace;
if (!workspace) { return; }
if (workspace.watchProject && !WorkSpace.IsWatchingProject) {
await WorkSpace.WatchProject(this);
} else if (!workspace.watchProject && WorkSpace.IsWatchingProject) {
WorkSpace.StopWatchingProject();
}
this.toolsToolbar?.forceUpdate();
}
/**
* @hidden
*/
public async _applyPreferences(): Promise<void> {
this._preferences = null;
this._preferences = this.getPreferences();
remote.getCurrentWebContents()?.setZoomFactor(parseFloat(this._preferences.zoom ?? "1"));
this.engine?.setHardwareScalingLevel(this._preferences.scalingLevel ?? 1);
// Gizmo steps
if (this._preferences.positionGizmoSnapping) {
this.preview?.setState({ availableGizmoSteps: this._preferences.positionGizmoSnapping });
}
// Picker
if (this.preview?.picker) {
this.preview.picker.drawOverlayOnOverElement = !this._preferences.noOverlayOnDrawElement;
}
// Plugins
const plugins = this._preferences.plugins ?? [];
const pluginToolbars: IPluginToolbar[] = [];
for (const p in Editor.LoadedExternalPlugins) {
const pluginReference = Editor.LoadedExternalPlugins[p];
const exists = plugins.find((p2) => p2.name === p);
if (exists) { continue; }
if (pluginReference.onDispose) { pluginReference.onDispose(); }
delete Editor.LoadedExternalPlugins[p];
}
for (const p of plugins) {
if (Editor.LoadedExternalPlugins[p.name]) {
if (!p.enabled) {
const pluginReference = Editor.LoadedExternalPlugins[p.name];
if (pluginReference.onDispose) { pluginReference.onDispose(); }
delete Editor.LoadedExternalPlugins[p.name];
} else {
pluginToolbars.push.apply(pluginToolbars, Editor.LoadedExternalPlugins[p.name].toolbar);
}
continue;
}
if (!p.enabled) { continue; }
try {
const exports = require(p.path);
const plugin = exports.registerEditorPlugin(this, {
pluginAbsolutePath: p.path,
} as IPluginConfiguration) as IPlugin;
Editor.LoadedExternalPlugins[p.name] = plugin;
// Toolbar
if (plugin.toolbar) {
pluginToolbars.push.apply(pluginToolbars, plugin.toolbar);
}
// Inspectors
if (plugin.inspectors) {
plugin.inspectors.forEach((i) => Inspector.RegisterObjectInspector(i));
}
} catch (e) {
console.error(e);
}
}
this.mainToolbar?.setState({ plugins: pluginToolbars });
this.resize();
// Devtools
await new Promise<void>((resolve) => {
ipcRenderer.once(IPCResponses.EnableDevTools, () => resolve());
ipcRenderer.send(IPCRequests.EnableDevTools, this._preferences!.developerMode);
});
// Assets
this.assets.getComponent(TextureAssets)?.refreshCompressedTexturesFiles();
}
} | the_stack |
import { HexBuffer } from '../HexBuffer';
import { W3Buffer } from '../W3Buffer';
import { WarResult, JsonResult } from '../CommonInterfaces'
interface Map {
name: string;
author: string;
description: string;
recommendedPlayers: string;
playableArea: PlayableMapArea;
flags: MapFlags;
mainTileType: string;
}
interface GameVersion {
major: number;
minor: number;
patch: number;
build: number;
}
interface Camera {
bounds: number[];
complements: number[];
}
interface MapFlags {
hideMinimapInPreview: boolean; // 0x0001: 1=hide minimap in preview screens
modifyAllyPriorities: boolean; // 0x0002: 1=modify ally priorities
isMeleeMap: boolean; // 0x0004: 1=melee map
// 0x0008: 1=playable map size was large and has never been reduced to medium (?)
maskedPartiallyVisible: boolean; // 0x0010: 1=masked area are partially visible
fixedPlayerSetting: boolean; // 0x0020: 1=fixed player setting for custom forces
useCustomForces: boolean; // 0x0040: 1=use custom forces
useCustomTechtree: boolean; // 0x0080: 1=use custom techtree
useCustomAbilities: boolean; // 0x0100: 1=use custom abilities
useCustomUpgrades: boolean; // 0x0200: 1=use custom upgrades
// 0x0400: 1=map properties menu opened at least once since map creation (?)
waterWavesOnCliffShores: boolean; // 0x0800: 1=show water waves on cliff shores
waterWavesOnRollingShores: boolean; // 0x1000: 1=show water waves on rolling shores
// 0x2000: 1=unknown
// 0x4000: 1=unknown
useItemClassificationSystem: boolean; // 0x8000: 1=use item classification system
enableWaterTinting: boolean; // 0x10000
useAccurateProbabilityForCalculations: boolean; // 0x20000
useCustomAbilitySkins: boolean; // 0x40000
}
interface LoadingScreen {
background: number;
path: string;
text: string;
title: string;
subtitle: string;
}
enum FogType {
Linear = 0,
Exponential1 = 1,
Exponential2 = 2
}
interface Fog {
type: FogType;
startHeight: number;
endHeight: number;
density: number;
color: number[]; // R G B A
}
interface PlayableMapArea {
width: number;
height: number;
}
interface Prologue {
path: string;
text: string;
title: string;
subtitle: string;
}
interface Info {
saves: number;
gameVersion: GameVersion;
editorVersion: number;
scriptLanguage: ScriptLanguage;
supportedModes: SupportedModes;
map: Map;
camera: Camera;
prologue: Prologue;
loadingScreen: LoadingScreen;
fog: Fog;
globalWeather: string;
customSoundEnvironment: string;
customLightEnv: string;
water: number[]; // R G B A
players: Player[];
forces: Force[];
}
interface PlayerStartingPosition {
x: number;
y: number;
fixed: boolean;
}
interface Player {
playerNum: number;
type: number; // 1=Human, 2=Computer, 3=Neutral, 4=Rescuable
race: number; // 1=Human, 2=Orc, 3=Undead, 4=Night Elf
name: string;
startingPos: PlayerStartingPosition;
}
interface ForceFlags {
allied: boolean; // 0x00000001: allied (force 1)
alliedVictory: boolean; // 0x00000002: allied victory
// 0x00000004: share vision (the documentation has this incorrect)
shareVision: boolean; // 0x00000008: share vision
shareUnitControl: boolean; // 0x00000010: share unit control
shareAdvUnitControl: boolean; // 0x00000020: share advanced unit control
}
interface Force {
flags: ForceFlags;
players: number; // UNSUPPORTED: (bit "x"=1 --> player "x" is in this force)
name: string;
}
enum ScriptLanguage {
JASS = 0,
Lua = 1
}
enum SupportedModes {
SD = 1,
HD = 2,
Both = 3
}
export abstract class InfoTranslator {
public static jsonToWar(infoJson: Info): WarResult {
const outBufferToWar = new HexBuffer();
outBufferToWar.addInt(31); // file version, 0x1F
outBufferToWar.addInt(infoJson.saves || 0);
outBufferToWar.addInt(infoJson.editorVersion || 0);
outBufferToWar.addInt(infoJson.gameVersion.major);
outBufferToWar.addInt(infoJson.gameVersion.minor);
outBufferToWar.addInt(infoJson.gameVersion.patch);
outBufferToWar.addInt(infoJson.gameVersion.build);
// Map information
outBufferToWar.addString(infoJson.map.name);
outBufferToWar.addString(infoJson.map.author);
outBufferToWar.addString(infoJson.map.description);
outBufferToWar.addString(infoJson.map.recommendedPlayers);
// Camera bounds (8 floats total)
for (let cbIndex = 0; cbIndex < 8; cbIndex++) {
outBufferToWar.addFloat(infoJson.camera.bounds[cbIndex]);
}
// Camera complements (4 floats total)
for (let ccIndex = 0; ccIndex < 4; ccIndex++) {
outBufferToWar.addInt(infoJson.camera.complements[ccIndex]);
}
// Playable area
outBufferToWar.addInt(infoJson.map.playableArea.width);
outBufferToWar.addInt(infoJson.map.playableArea.height);
/*
* Flags
*/
let flags = 0;
if (infoJson.map.flags) { // can leave out the entire flags object, all flags will default to false
if (infoJson.map.flags.hideMinimapInPreview) flags |= 0x0001; // hide minimap in preview screens
if (infoJson.map.flags.modifyAllyPriorities) flags |= 0x0002; // modify ally priorities
if (infoJson.map.flags.isMeleeMap) flags |= 0x0004; // melee map
// 0x0008 - unknown; // playable map size was large and never reduced to medium (?)
if (infoJson.map.flags.maskedPartiallyVisible) flags |= 0x0010; // masked area are partially visible
if (infoJson.map.flags.fixedPlayerSetting) flags |= 0x0020; // fixed player setting for custom forces
if (infoJson.map.flags.useCustomForces) flags |= 0x0040; // use custom forces
if (infoJson.map.flags.useCustomTechtree) flags |= 0x0080; // use custom techtree
if (infoJson.map.flags.useCustomAbilities) flags |= 0x0100; // use custom abilities
if (infoJson.map.flags.useCustomUpgrades) flags |= 0x0200; // use custom upgrades
// 0x0400 - unknown; // map properties menu opened at least once since map creation (?)
if (infoJson.map.flags.waterWavesOnCliffShores) flags |= 0x0800; // show water waves on cliff shores
if (infoJson.map.flags.waterWavesOnRollingShores) flags |= 0x1000; // show water waves on rolling shores
// 0x2000: 1=unknown
// 0x4000: 1=unknown
if (infoJson.map.flags.useItemClassificationSystem) flags |= 0x8000
if (infoJson.map.flags.enableWaterTinting) flags |= 0x10000
if (infoJson.map.flags.useAccurateProbabilityForCalculations) flags |= 0x20000
if (infoJson.map.flags.useCustomAbilitySkins) flags |= 0x40000
}
// Unknown, but these seem to always be on, at least for default maps
flags |= 0x8000;
flags |= 0x4000;
flags |= 0x0400;
outBufferToWar.addInt(flags); // Add flags
// Map main ground type
outBufferToWar.addChar(infoJson.map.mainTileType);
// Loading screen
outBufferToWar.addInt(infoJson.loadingScreen.background);
outBufferToWar.addString(infoJson.loadingScreen.path);
outBufferToWar.addString(infoJson.loadingScreen.text);
outBufferToWar.addString(infoJson.loadingScreen.title);
outBufferToWar.addString(infoJson.loadingScreen.subtitle);
// Use game data set (Unsupported)
outBufferToWar.addInt(0);
// Prologue
outBufferToWar.addString(infoJson.prologue.path);
outBufferToWar.addString(infoJson.prologue.text);
outBufferToWar.addString(infoJson.prologue.title);
outBufferToWar.addString(infoJson.prologue.subtitle);
// Fog
outBufferToWar.addInt(infoJson.fog.type);
outBufferToWar.addFloat(infoJson.fog.startHeight);
outBufferToWar.addFloat(infoJson.fog.endHeight);
outBufferToWar.addFloat(infoJson.fog.density);
outBufferToWar.addByte(infoJson.fog.color[0]);
outBufferToWar.addByte(infoJson.fog.color[1]);
outBufferToWar.addByte(infoJson.fog.color[2]);
outBufferToWar.addByte(255); // Fog alpha - unsupported
// Misc.
// If globalWeather is not defined or is set to 'none', use 0 sentinel value, else add char[4]
if (!infoJson.globalWeather || infoJson.globalWeather.toLowerCase() === 'none') {
outBufferToWar.addInt(0);
} else {
outBufferToWar.addChars(infoJson.globalWeather); // char[4] - lookup table
}
outBufferToWar.addString(infoJson.customSoundEnvironment || '');
outBufferToWar.addChar(infoJson.customLightEnv || 'L');
// Custom water tinting
outBufferToWar.addByte(infoJson.water[0]);
outBufferToWar.addByte(infoJson.water[1]);
outBufferToWar.addByte(infoJson.water[2]);
outBufferToWar.addByte(255); // Water alpha - unsupported
outBufferToWar.addInt(infoJson.scriptLanguage);
outBufferToWar.addInt(infoJson.supportedModes);
outBufferToWar.addInt(0); // unknown
// Players
outBufferToWar.addInt(infoJson.players.length);
infoJson.players.forEach((player) => {
outBufferToWar.addInt(player.playerNum);
outBufferToWar.addInt(player.type);
outBufferToWar.addInt(player.race);
outBufferToWar.addInt(player.startingPos.fixed ? 1 : 0);
outBufferToWar.addString(player.name);
outBufferToWar.addFloat(player.startingPos.x);
outBufferToWar.addFloat(player.startingPos.y);
outBufferToWar.addInt(0); // ally low prio flags - unsupported
outBufferToWar.addInt(0); // ally high prio flags - unsupported
outBufferToWar.addInt(0); // enemy low prio flags - unsupported
outBufferToWar.addInt(0); // enemy high prio flags - unsupported
});
// Forces
outBufferToWar.addInt(infoJson.forces.length);
infoJson.forces.forEach((force) => {
// Calculate flags
let forceFlags = 0;
if (force.flags.allied) forceFlags |= 0x0001;
if (force.flags.alliedVictory) forceFlags |= 0x0002;
// Skip 0x0004
if (force.flags.shareVision) forceFlags |= 0x0008;
if (force.flags.shareUnitControl) forceFlags |= 0x0010;
if (force.flags.shareAdvUnitControl) forceFlags |= 0x0020;
outBufferToWar.addInt(forceFlags);
outBufferToWar.addInt(force.players);
outBufferToWar.addString(force.name);
});
// Upgrades - unsupported
outBufferToWar.addInt(0);
// Tech availability - unsupported
outBufferToWar.addInt(0);
// Unit table (random) - unsupported
outBufferToWar.addInt(0);
// Item table (random) - unsupported
outBufferToWar.addInt(0);
return {
errors: [],
buffer: outBufferToWar.getBuffer()
};
}
public static warToJson(buffer: Buffer): JsonResult<Info> {
const result: Info = {
map: {
name: '',
author: '',
description: '',
recommendedPlayers: '',
playableArea: {
width: 64,
height: 64
},
mainTileType: '',
flags: {
hideMinimapInPreview: false, // 0x0001: 1=hide minimap in preview screens
modifyAllyPriorities: true, // 0x0002: 1=modify ally priorities
isMeleeMap: false, // 0x0004: 1=melee map
// 0x0008: 1=playable map size was large and has never been reduced to medium (?)
maskedPartiallyVisible: false, // 0x0010: 1=masked area are partially visible
fixedPlayerSetting: false, // 0x0020: 1=fixed player setting for custom forces
useCustomForces: false, // 0x0040: 1=use custom forces
useCustomTechtree: false, // 0x0080: 1=use custom techtree
useCustomAbilities: false, // 0x0100: 1=use custom abilities
useCustomUpgrades: false, // 0x0200: 1=use custom upgrades
// 0x0400: 1=map properties menu opened at least once since map creation (?)
waterWavesOnCliffShores: false, // 0x0800: 1=show water waves on cliff shores
waterWavesOnRollingShores: false, // 0x1000: 1=show water waves on rolling shores
useItemClassificationSystem: false, // 0x8000: 1=use item classification system
enableWaterTinting: false, // 0x10000
useAccurateProbabilityForCalculations: false, // 0x20000
useCustomAbilitySkins: false // 0x40000
}
},
loadingScreen: {
background: 0,
path: '',
text: '',
title: '',
subtitle: ''
}, prologue: {
path: '',
text: '',
title: '',
subtitle: ''
}, fog: {
type: FogType.Linear,
startHeight: 0,
endHeight: 0,
density: 0,
color: [0, 0, 0, 1]
}, camera: {
bounds: [],
complements: []
}, players: [
], forces: [
],
saves: 0,
editorVersion: 0,
scriptLanguage: ScriptLanguage.JASS,
supportedModes: SupportedModes.Both,
gameVersion: {
major: 0,
minor: 0,
patch: 0,
build: 0
},
globalWeather: '',
customSoundEnvironment: '',
customLightEnv: '',
water: []
};
const outBufferToJSON = new W3Buffer(buffer);
const fileVersion = outBufferToJSON.readInt();
result.saves = outBufferToJSON.readInt(),
result.editorVersion = outBufferToJSON.readInt();
result.gameVersion = {
major: outBufferToJSON.readInt(),
minor: outBufferToJSON.readInt(),
patch: outBufferToJSON.readInt(),
build: outBufferToJSON.readInt()
};
result.map.name = outBufferToJSON.readString();
result.map.author = outBufferToJSON.readString();
result.map.description = outBufferToJSON.readString();
result.map.recommendedPlayers = outBufferToJSON.readString();
result.camera.bounds = [
outBufferToJSON.readFloat(), outBufferToJSON.readFloat(), outBufferToJSON.readFloat(), outBufferToJSON.readFloat(),
outBufferToJSON.readFloat(), outBufferToJSON.readFloat(), outBufferToJSON.readFloat(), outBufferToJSON.readFloat()
];
result.camera.complements = [
outBufferToJSON.readInt(), outBufferToJSON.readInt(), outBufferToJSON.readInt(), outBufferToJSON.readInt()
];
result.map.playableArea = {
width: outBufferToJSON.readInt(),
height: outBufferToJSON.readInt()
};
const flags = outBufferToJSON.readInt();
result.map.flags = {
hideMinimapInPreview: !!(flags & 0x0001),
modifyAllyPriorities: !!(flags & 0x0002),
isMeleeMap: !!(flags & 0x0004),
// skip 0x008
maskedPartiallyVisible: !!(flags & 0x0010),
fixedPlayerSetting: !!(flags & 0x0020),
useCustomForces: !!(flags & 0x0040),
useCustomTechtree: !!(flags & 0x0080),
useCustomAbilities: !!(flags & 0x0100),
useCustomUpgrades: !!(flags & 0x0200),
waterWavesOnCliffShores: !!(flags & 0x0800),
waterWavesOnRollingShores: !!(flags & 0x1000),
// skip 0x2000
// skip 0x4000
useItemClassificationSystem: !!(flags & 0x8000),
enableWaterTinting: !!(flags & 0x10000),
useAccurateProbabilityForCalculations: !!(flags & 0x20000),
useCustomAbilitySkins: !!(flags & 0x40000)
};
result.map.mainTileType = outBufferToJSON.readChars();
result.loadingScreen.background = outBufferToJSON.readInt();
result.loadingScreen.path = outBufferToJSON.readString();
result.loadingScreen.text = outBufferToJSON.readString();
result.loadingScreen.title = outBufferToJSON.readString();
result.loadingScreen.subtitle = outBufferToJSON.readString();
const gameDataSet = outBufferToJSON.readInt(); // 0 = standard
result.prologue = {
path: outBufferToJSON.readString(),
text: outBufferToJSON.readString(),
title: outBufferToJSON.readString(),
subtitle: outBufferToJSON.readString()
};
result.fog = {
type: outBufferToJSON.readInt(),
startHeight: outBufferToJSON.readFloat(),
endHeight: outBufferToJSON.readFloat(),
density: outBufferToJSON.readFloat(),
color: [outBufferToJSON.readByte(), outBufferToJSON.readByte(), outBufferToJSON.readByte(), outBufferToJSON.readByte()] // R G B A
};
result.globalWeather = outBufferToJSON.readChars(4);
result.customSoundEnvironment = outBufferToJSON.readString();
result.customLightEnv = outBufferToJSON.readChars();
result.water = [outBufferToJSON.readByte(), outBufferToJSON.readByte(), outBufferToJSON.readByte(), outBufferToJSON.readByte()]; // R G B A
result.scriptLanguage = outBufferToJSON.readInt();
result.supportedModes = outBufferToJSON.readInt();
outBufferToJSON.readInt(); // unknown
// Struct: players
const numPlayers = outBufferToJSON.readInt();
for (let i = 0; i < numPlayers; i++) {
const player: Player = {
name: '',
startingPos: { x: 0, y: 0, fixed: false },
playerNum: 0,
type: 0,
race: 0
};
player.playerNum = outBufferToJSON.readInt();
player.type = outBufferToJSON.readInt(); // 1=Human, 2=Computer, 3=Neutral, 4=Rescuable
player.race = outBufferToJSON.readInt(); // 1=Human, 2=Orc, 3=Undead, 4=Night Elf
const isPlayerStartPositionFixed: boolean = outBufferToJSON.readInt() === 1; // 00000001 = fixed start position
player.name = outBufferToJSON.readString();
player.startingPos = {
x: outBufferToJSON.readFloat(),
y: outBufferToJSON.readFloat(),
fixed: isPlayerStartPositionFixed
};
outBufferToJSON.readInt(); // ally low priorities flags (bit "x"=1 --> set for player "x")
outBufferToJSON.readInt(); // ally high priorities flags (bit "x"=1 --> set for player "x")
outBufferToJSON.readInt(); // enemy low priorities flags
outBufferToJSON.readInt(); // enemy high priorities flags
result.players.push(player);
}
// Struct: forces
const numForces = outBufferToJSON.readInt();
for (let i = 0; i < numForces; i++) {
const force: Force = {
flags: { allied: false, alliedVictory: true, shareVision: true, shareUnitControl: false, shareAdvUnitControl: false },
players: 0,
name: ''
};
const forceFlag = outBufferToJSON.readInt();
force.flags = {
allied: !!(forceFlag & 0b1), // 0x00000001: allied (force 1)
alliedVictory: !!(forceFlag & 0b10), // 0x00000002: allied victory
// 0x00000004: share vision (the documentation has this incorrect)
shareVision: !!(forceFlag & 0b1000), // 0x00000008: share vision
shareUnitControl: !!(forceFlag & 0b10000), // 0x00000010: share unit control
shareAdvUnitControl: !!(forceFlag & 0b100000) // 0x00000020: share advanced unit control
};
force.players = outBufferToJSON.readInt(); // UNSUPPORTED: (bit "x"=1 --> player "x" is in this force; but carried over for accurate translation
force.name = outBufferToJSON.readString();
result.forces.push(force);
}
// UNSUPPORTED: Struct: upgrade avail.
const numUpgrades = outBufferToJSON.readInt();
for (let i = 0; i < numUpgrades; i++) {
outBufferToJSON.readInt(); // Player Flags (bit "x"=1 if this change applies for player "x")
outBufferToJSON.readChars(4); // upgrade id (as in UpgradeData.slk)
outBufferToJSON.readInt(); // Level of the upgrade for which the availability is changed (this is actually the level - 1, so 1 => 0)
outBufferToJSON.readInt(); // Availability (0 = unavailable, 1 = available, 2 = researched)
}
// UNSUPPORTED: Struct: tech avail.
const numTech = outBufferToJSON.readInt();
for (let i = 0; i < numTech; i++) {
outBufferToJSON.readInt(); // Player Flags (bit "x"=1 if this change applies for player "x")
outBufferToJSON.readChars(4); // tech id (this can be an item, unit or ability)
}
// UNSUPPORTED: Struct: random unit table
const numUnitTable = outBufferToJSON.readInt();
for (let i = 0; i < numUnitTable; i++) {
outBufferToJSON.readInt(); // Group number
outBufferToJSON.readString(); // Group name
const numPositions = outBufferToJSON.readInt(); // Number "m" of positions
for (let j = 0; j < numPositions; j++) {
outBufferToJSON.readInt(); // unit table (=0), a building table (=1) or an item table (=2)
const numLinesInTable = outBufferToJSON.readInt();
for (let k = 0; k < numLinesInTable; k++) {
outBufferToJSON.readInt(); // Chance of the unit/item (percentage)
outBufferToJSON.readChars(4); // unit/item id's for this line specified
}
}
}
// UNSUPPORTED: Struct: random item table
const numItemTable = outBufferToJSON.readInt();
for (let i = 0; i < numItemTable; i++) {
outBufferToJSON.readInt(); // Table number
outBufferToJSON.readString(); // Table name
const itemSetsCurrentTable = outBufferToJSON.readInt(); // Number "m" of item sets on the current item table
for (let j = 0; j < itemSetsCurrentTable; j++) {
const itemsInItemSet = outBufferToJSON.readInt(); // Number "i" of items on the current item set
for (let k = 0; k < itemsInItemSet; k++) {
outBufferToJSON.readInt(); // Percentual chance
outBufferToJSON.readChars(4); // Item id (as in ItemData.slk)
}
}
}
return {
errors: [],
json: result
};
}
} | the_stack |
import { ConcreteRequest } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type OrderHistoryTestsQueryVariables = {
count: number;
};
export type OrderHistoryTestsQueryResponse = {
readonly me: {
readonly " $fragmentRefs": FragmentRefs<"OrderHistory_me">;
} | null;
};
export type OrderHistoryTestsQuery = {
readonly response: OrderHistoryTestsQueryResponse;
readonly variables: OrderHistoryTestsQueryVariables;
};
/*
query OrderHistoryTestsQuery(
$count: Int!
) {
me {
...OrderHistory_me_yu5n1
id
}
}
fragment OrderHistoryRow_order on CommerceOrder {
__isCommerceOrder: __typename
internalID
state
mode
buyerTotal(precision: 2)
createdAt
itemsTotal
lineItems(first: 1) {
edges {
node {
shipment {
status
trackingUrl
trackingNumber
id
}
artwork {
image {
resized(width: 55) {
url
}
}
partner {
name
id
}
title
artistNames
id
}
fulfillments(first: 1) {
edges {
node {
trackingId
id
}
}
}
id
}
}
}
}
fragment OrderHistory_me_yu5n1 on Me {
orders(first: $count, states: [APPROVED, CANCELED, FULFILLED, REFUNDED, SUBMITTED]) {
edges {
node {
__typename
code
...OrderHistoryRow_order
id
}
cursor
}
pageInfo {
endCursor
hasNextPage
}
}
}
*/
const node: ConcreteRequest = (function(){
var v0 = [
{
"defaultValue": null,
"kind": "LocalArgument",
"name": "count"
}
],
v1 = [
{
"kind": "Variable",
"name": "first",
"variableName": "count"
},
{
"kind": "Literal",
"name": "states",
"value": [
"APPROVED",
"CANCELED",
"FULFILLED",
"REFUNDED",
"SUBMITTED"
]
}
],
v2 = [
{
"kind": "Literal",
"name": "first",
"value": 1
}
],
v3 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
},
v4 = {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "ID"
},
v5 = {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "String"
},
v6 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "String"
};
return {
"fragment": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Fragment",
"metadata": null,
"name": "OrderHistoryTestsQuery",
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Me",
"kind": "LinkedField",
"name": "me",
"plural": false,
"selections": [
{
"args": [
{
"kind": "Variable",
"name": "count",
"variableName": "count"
}
],
"kind": "FragmentSpread",
"name": "OrderHistory_me"
}
],
"storageKey": null
}
],
"type": "Query",
"abstractKey": null
},
"kind": "Request",
"operation": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Operation",
"name": "OrderHistoryTestsQuery",
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Me",
"kind": "LinkedField",
"name": "me",
"plural": false,
"selections": [
{
"alias": null,
"args": (v1/*: any*/),
"concreteType": "CommerceOrderConnectionWithTotalCount",
"kind": "LinkedField",
"name": "orders",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceOrderEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "__typename",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "code",
"storageKey": null
},
{
"kind": "TypeDiscriminator",
"abstractKey": "__isCommerceOrder"
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "internalID",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "state",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "mode",
"storageKey": null
},
{
"alias": null,
"args": [
{
"kind": "Literal",
"name": "precision",
"value": 2
}
],
"kind": "ScalarField",
"name": "buyerTotal",
"storageKey": "buyerTotal(precision:2)"
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "createdAt",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "itemsTotal",
"storageKey": null
},
{
"alias": null,
"args": (v2/*: any*/),
"concreteType": "CommerceLineItemConnection",
"kind": "LinkedField",
"name": "lineItems",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceLineItemEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceLineItem",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceShipment",
"kind": "LinkedField",
"name": "shipment",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "status",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "trackingUrl",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "trackingNumber",
"storageKey": null
},
(v3/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Artwork",
"kind": "LinkedField",
"name": "artwork",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "image",
"plural": false,
"selections": [
{
"alias": null,
"args": [
{
"kind": "Literal",
"name": "width",
"value": 55
}
],
"concreteType": "ResizedImageUrl",
"kind": "LinkedField",
"name": "resized",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "url",
"storageKey": null
}
],
"storageKey": "resized(width:55)"
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Partner",
"kind": "LinkedField",
"name": "partner",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "name",
"storageKey": null
},
(v3/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "title",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "artistNames",
"storageKey": null
},
(v3/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": (v2/*: any*/),
"concreteType": "CommerceFulfillmentConnection",
"kind": "LinkedField",
"name": "fulfillments",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceFulfillmentEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceFulfillment",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "trackingId",
"storageKey": null
},
(v3/*: any*/)
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": "fulfillments(first:1)"
},
(v3/*: any*/)
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": "lineItems(first:1)"
},
(v3/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "cursor",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "CommercePageInfo",
"kind": "LinkedField",
"name": "pageInfo",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "endCursor",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "hasNextPage",
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": (v1/*: any*/),
"filters": [
"states"
],
"handle": "connection",
"key": "OrderHistory_orders",
"kind": "LinkedHandle",
"name": "orders"
},
(v3/*: any*/)
],
"storageKey": null
}
]
},
"params": {
"id": "85e412a5fba4fafdf2b2e4d7c399d57b",
"metadata": {
"relayTestingSelectionTypeInfo": {
"me": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Me"
},
"me.id": (v4/*: any*/),
"me.orders": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "CommerceOrderConnectionWithTotalCount"
},
"me.orders.edges": {
"enumValues": null,
"nullable": true,
"plural": true,
"type": "CommerceOrderEdge"
},
"me.orders.edges.cursor": (v5/*: any*/),
"me.orders.edges.node": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "CommerceOrder"
},
"me.orders.edges.node.__isCommerceOrder": (v5/*: any*/),
"me.orders.edges.node.__typename": (v5/*: any*/),
"me.orders.edges.node.buyerTotal": (v6/*: any*/),
"me.orders.edges.node.code": (v5/*: any*/),
"me.orders.edges.node.createdAt": (v5/*: any*/),
"me.orders.edges.node.id": (v4/*: any*/),
"me.orders.edges.node.internalID": (v4/*: any*/),
"me.orders.edges.node.itemsTotal": (v6/*: any*/),
"me.orders.edges.node.lineItems": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "CommerceLineItemConnection"
},
"me.orders.edges.node.lineItems.edges": {
"enumValues": null,
"nullable": true,
"plural": true,
"type": "CommerceLineItemEdge"
},
"me.orders.edges.node.lineItems.edges.node": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "CommerceLineItem"
},
"me.orders.edges.node.lineItems.edges.node.artwork": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Artwork"
},
"me.orders.edges.node.lineItems.edges.node.artwork.artistNames": (v6/*: any*/),
"me.orders.edges.node.lineItems.edges.node.artwork.id": (v4/*: any*/),
"me.orders.edges.node.lineItems.edges.node.artwork.image": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Image"
},
"me.orders.edges.node.lineItems.edges.node.artwork.image.resized": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "ResizedImageUrl"
},
"me.orders.edges.node.lineItems.edges.node.artwork.image.resized.url": (v5/*: any*/),
"me.orders.edges.node.lineItems.edges.node.artwork.partner": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Partner"
},
"me.orders.edges.node.lineItems.edges.node.artwork.partner.id": (v4/*: any*/),
"me.orders.edges.node.lineItems.edges.node.artwork.partner.name": (v6/*: any*/),
"me.orders.edges.node.lineItems.edges.node.artwork.title": (v6/*: any*/),
"me.orders.edges.node.lineItems.edges.node.fulfillments": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "CommerceFulfillmentConnection"
},
"me.orders.edges.node.lineItems.edges.node.fulfillments.edges": {
"enumValues": null,
"nullable": true,
"plural": true,
"type": "CommerceFulfillmentEdge"
},
"me.orders.edges.node.lineItems.edges.node.fulfillments.edges.node": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "CommerceFulfillment"
},
"me.orders.edges.node.lineItems.edges.node.fulfillments.edges.node.id": (v4/*: any*/),
"me.orders.edges.node.lineItems.edges.node.fulfillments.edges.node.trackingId": (v6/*: any*/),
"me.orders.edges.node.lineItems.edges.node.id": (v4/*: any*/),
"me.orders.edges.node.lineItems.edges.node.shipment": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "CommerceShipment"
},
"me.orders.edges.node.lineItems.edges.node.shipment.id": (v4/*: any*/),
"me.orders.edges.node.lineItems.edges.node.shipment.status": (v6/*: any*/),
"me.orders.edges.node.lineItems.edges.node.shipment.trackingNumber": (v6/*: any*/),
"me.orders.edges.node.lineItems.edges.node.shipment.trackingUrl": (v6/*: any*/),
"me.orders.edges.node.mode": {
"enumValues": [
"BUY",
"OFFER"
],
"nullable": true,
"plural": false,
"type": "CommerceOrderModeEnum"
},
"me.orders.edges.node.state": {
"enumValues": [
"ABANDONED",
"APPROVED",
"CANCELED",
"FULFILLED",
"PENDING",
"REFUNDED",
"SUBMITTED"
],
"nullable": false,
"plural": false,
"type": "CommerceOrderStateEnum"
},
"me.orders.pageInfo": {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "CommercePageInfo"
},
"me.orders.pageInfo.endCursor": (v6/*: any*/),
"me.orders.pageInfo.hasNextPage": {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "Boolean"
}
}
},
"name": "OrderHistoryTestsQuery",
"operationKind": "query",
"text": null
}
};
})();
(node as any).hash = 'f4d615ed85aa9b712d599622f7b12bb3';
export default node; | the_stack |
import { EventAggregator } from 'aurelia-event-aggregator';
import { UxModalTheme } from './ux-modal-theme';
import { UxModal } from './ux-modal';
import { UxModalPosition, UxModalKeybord, UxDefaultModalConfiguration } from './ux-modal-configuration';
import { inject, Controller, ViewResources } from 'aurelia-framework';
import { CompositionContext, TemplatingEngine, CompositionEngine, ViewSlot, ShadowDOM } from 'aurelia-templating';
import { invokeLifecycle } from './lifecycle';
export interface UxModalServiceOptions {
viewModel?: any;
view?: any;
host?: Element| 'body' | string;
position?: UxModalPosition;
moveToBodyTag?: boolean;
theme?: UxModalTheme;
model?: any;
overlayDismiss?: boolean;
outsideDismiss?: boolean;
lock?: boolean;
keyboard?: UxModalKeybord;
modalBreakpoint?: number;
restoreFocus?: (lastActiveElement: HTMLElement) => void;
openingCallback?: (contentWrapperElement?: HTMLElement, overlayElement?: HTMLElement) => void;
}
export interface UxModalServiceResult {
wasCancelled: boolean;
output: any;
}
export interface UxModalServiceModal {
whenClosed: () => Promise<UxModalServiceResult>
}
export interface ModalAnchorPositionOptions {
offsetX?: number;
offsetY?: number;
preferedPosition?: 'bottom' | 'top' | 'left' | 'right';
}
interface UxModalBindingContext {
currentViewModel?: {
canDeactivate?: (result: any) => any;
deactivate?: (result: any) => any;
detached?: (result: any) => any;
};
theme?: UxModalTheme;
keyboard?: UxModalKeybord;
restoreFocus?: (lastActiveElement: HTMLElement) => void;
openingCallback?: (contentWrapperElement?: HTMLElement, overlayElement?: HTMLElement) => void;
host?: HTMLElement;
dismiss?: () => void;
ok?: (event: Event) => void;
}
interface UxModalLayer {
bindingContext?: UxModalBindingContext;
modal: UxModal;
}
@inject(TemplatingEngine, CompositionEngine, ViewResources, EventAggregator, UxDefaultModalConfiguration)
export class UxModalService {
public startingZIndex: number = 200;
public modalLayers: Array<UxModalLayer> = [];
public modalIndex: number = 0;
constructor(
private templatingEngine: TemplatingEngine,
private compositionEngine: CompositionEngine,
private viewResources: ViewResources,
private eventAggregator: EventAggregator,
private defaultConfig: UxDefaultModalConfiguration) {
}
public addLayer(modal: UxModal, bindingContext: UxModalBindingContext) {
const layerCount = this.modalLayers.push({
bindingContext,
modal
});
if (layerCount === 1) {
this.setListener();
}
}
public getLayer(modal: UxModal): UxModalLayer | undefined {
const index = this.modalLayers.map(i => i.modal).indexOf(modal);
if (index !== -1) {
return this.modalLayers[index];
}
return undefined;
}
public removeLayer(modal: UxModal) {
const index = this.modalLayers.map(i => i.modal).indexOf(modal);
if (index !== -1) {
this.modalLayers.splice(index, 1);
}
if (this.modalLayers.length === 0) {
this.removeListener();
}
}
private setListener() {
document.addEventListener('keyup', this);
document.addEventListener('click', this);
}
private removeListener() {
document.removeEventListener('keyup', this);
document.removeEventListener('click', this);
}
public handleEvent(event: KeyboardEvent | MouseEvent) {
if (event instanceof KeyboardEvent) {
this.handleKeyEvent(event);
} else {
this.handleDocumentClick(event);
}
}
private handleKeyEvent(event: KeyboardEvent) {
const key = this.getActionKey(event);
if (key === undefined) {
return;
}
const activeLayer = this.getLastModal();
if (activeLayer === null) {
return;
}
const keyboard = activeLayer.keyboard;
if (key === 'Escape'
&& (keyboard === true || keyboard === key || (Array.isArray(keyboard) && keyboard.indexOf(key) > -1))) {
activeLayer.dismiss();
} else if (key === 'Enter' && (keyboard === key || (Array.isArray(keyboard) && keyboard.indexOf(key) > -1))) {
activeLayer.ok();
}
}
private handleDocumentClick(event: MouseEvent) {
// the purpose of this handler is to close all modals that are
// - not locked
// - have outsideDismiss === true
// - placed above the last locked layer
// - and if the click is outside the modal
let concernedLayers: Array<UxModalLayer> = [];
for (const layer of this.modalLayers) {
if (layer.modal.lock || !layer.modal.outsideDismiss) {
concernedLayers = [];
continue; // we ignore locks
}
concernedLayers.push(layer);
}
// now we have all the layers above the last locked in the concernedLayers array
// let's check if the click is outside of any
layerloop: for (const layer of concernedLayers) {
const modalContentElement = layer.modal.contentElement;
for (const element of (event as any).composedPath() ) {
if (element === modalContentElement) {
continue layerloop; // click is on the modal, do not hide
}
}
layer.modal.dismiss();
}
return true; // this allow normal behvior with this click for other purposes
}
private getActionKey(event: KeyboardEvent): UxModalKeybord | undefined {
if ((event.code || event.key) === 'Escape' || event.keyCode === 27) {
return 'Escape';
}
if ((event.code || event.key) === 'Enter' || event.keyCode === 13) {
return 'Enter';
}
return undefined;
}
public getLastLayer(): UxModalLayer | null {
return this.modalLayers.length > 0 ? this.modalLayers[this.modalLayers.length - 1] : null;
}
public getLastModal(): UxModal | null {
const lastLayer = this.getLastLayer();
return lastLayer !== null ? lastLayer.modal : null;
}
public get zIndex() {
return this.startingZIndex + this.modalLayers.length;
}
private createModalElement(options: UxModalServiceOptions, bindingContext: UxModalBindingContext): HTMLElement {
const element = document.createElement('ux-modal');
element.setAttribute('dismiss.trigger', 'dismiss()');
element.setAttribute('ok.trigger', 'ok($event)');
if (options.position !== undefined) {
element.setAttribute('position', options.position);
}
if (options.overlayDismiss === false) {
element.setAttribute('overlay-dismiss.bind', 'false');
}
if (options.outsideDismiss === false) {
element.setAttribute('outside-dismiss.bind', 'false');
}
if (options.lock === false) {
element.setAttribute('lock.bind', 'false');
}
if (options.keyboard !== undefined) {
bindingContext.keyboard = options.keyboard;
element.setAttribute('keyboard.bind', 'keyboard');
}
if (typeof options.restoreFocus === 'function') {
bindingContext.restoreFocus = options.restoreFocus;
element.setAttribute('restore-focus.bind', 'restoreFocus');
}
if (typeof options.openingCallback === 'function') {
bindingContext.openingCallback = options.openingCallback;
element.setAttribute('opening-callback.bind', 'openingCallback');
}
if (typeof options.modalBreakpoint === 'number') {
element.setAttribute('modal-breakpoint.bind', `${options.modalBreakpoint}`);
}
element.setAttribute('host.bind', 'false');
if (options.theme) {
bindingContext.theme = options.theme;
element.setAttribute('theme.bind', `theme`);
}
return element;
}
private createCompositionContext(
container: any, // there is a TS error if this is not any ?
host: Element,
bindingContext: UxModalBindingContext,
settings: {model?: any, view?: any, viewModel?: any},
slot?: ViewSlot
): CompositionContext {
return {
container,
bindingContext: settings.viewModel ? null : bindingContext,
viewResources: this.viewResources as any, // there is a TS error if this is not any ?
model: settings.model,
view: settings.view,
viewModel: settings.viewModel,
viewSlot: slot || new ViewSlot(host, true),
host
};
}
private ensureViewModel(compositionContext: CompositionContext): Promise<CompositionContext> {
if (compositionContext.viewModel === undefined) {
return Promise.resolve(compositionContext);
}
if (typeof compositionContext.viewModel === 'object') {
return Promise.resolve(compositionContext);
}
return this.compositionEngine.ensureViewModel(compositionContext);
}
public async open(options: UxModalServiceOptions): Promise<UxModal & UxModalServiceModal> {
// tslint:disable-next-line: prefer-object-spread
options = Object.assign({}, this.defaultConfig, options);
if (!options.viewModel && !options.view) {
throw new Error('Invalid modal Settings. You must provide "viewModel", "view" or both.');
}
// Each modal has an index to keep track of it
this.modalIndex++;
const bindingContext: UxModalBindingContext = {};
const element = this.createModalElement(options, bindingContext);
if (!options.host || options.host === 'body') {
options.host = document.body;
} else if (typeof options.host === 'string') {
options.host = document.querySelector(options.host) || document.body;
}
options.host.appendChild(element);
const childView = this.templatingEngine.enhance({ element, bindingContext });
// We need to get the slot anchor from the modal
// so that the composed VM/M will be placed in the
// right place in the DOM once the compositionEngine
// has finished its work
let slot: ViewSlot;
const controllers = (childView as any).controllers as Controller[];
const modal: UxModal = controllers[0].viewModel as UxModal;
try {
const view: any = controllers[0].view;
// ShadowDOM.defaultSlotKey refers to the name of the default
// slot if the view.
slot = new ViewSlot(view.slots[ShadowDOM.defaultSlotKey].anchor, false);
} catch (error) {
// This catch => throw here might not be necessary
// in the future once the modal service is finished
// I have ideas on how to move from here but I would need
// to fix the composition issue first.
this.cancelOpening(modal);
throw new Error('Missing slot in modal');
}
slot.attached();
let compositionContext = this.createCompositionContext(childView.container, element, bindingContext, {
viewModel: options.viewModel,
view: options.view,
model: options.model
}, slot);
compositionContext = await this.ensureViewModel(compositionContext);
try {
const canActivate = compositionContext.viewModel ? await invokeLifecycle(compositionContext.viewModel, 'canActivate', options.model) : true;
if (!canActivate) {
throw new Error('modal cannot be opened');
}
} catch (error) {
this.cancelOpening(modal);
throw error;
}
this.compositionEngine.compose(compositionContext).then((controller) => {
bindingContext.currentViewModel = (controller as Controller).viewModel;
});
const modalIndex = this.modalIndex;
const whenClosed: Promise<UxModalServiceResult> = new Promise((resolve) => {
this.eventAggregator.subscribeOnce(`modal-${modalIndex}-resolve`, (result: UxModalServiceResult) => {
resolve(result);
});
});
(modal as UxModal & UxModalServiceModal).whenClosed = () => {
return whenClosed;
};
bindingContext.dismiss = () => {
modal.element.remove();
modal.detached();
this.eventAggregator.publish(`modal-${modalIndex}-resolve`, {
wasCancelled: true,
output: null
});
};
bindingContext.ok = (event: CustomEvent) => {
modal.element.remove();
modal.detached();
this.eventAggregator.publish(`modal-${modalIndex}-resolve`, {
wasCancelled: false,
output: event.detail
});
};
return modal as UxModal & UxModalServiceModal;
}
private cancelOpening(modal: UxModal) {
modal.element.remove();
modal.detached();
}
public async callCanDeactivate(layer: UxModalLayer, result: UxModalServiceResult): Promise<boolean> {
if (layer.bindingContext && layer.bindingContext.currentViewModel) {
const vm = layer.bindingContext.currentViewModel;
if (typeof vm.canDeactivate === 'function') {
try {
const can = (await vm.canDeactivate.call(vm, result) === false) ? false : true;
return can;
} catch (error) {
return false;
}
}
}
return true;
}
public async callDetached(layer: UxModalLayer): Promise<void> {
if (layer.bindingContext && layer.bindingContext.currentViewModel) {
const vm = layer.bindingContext.currentViewModel;
if (typeof vm.detached === 'function') {
await vm.detached.call(vm);
}
}
return;
}
public async callDeactivate(layer: UxModalLayer, result: UxModalServiceResult): Promise<void> {
if (layer.bindingContext && layer.bindingContext.currentViewModel) {
const vm = layer.bindingContext.currentViewModel;
if (typeof vm.deactivate === 'function') {
await vm.deactivate.call(vm, result);
}
}
return;
}
public async cancel(modal?: UxModal) {
const layer = modal ? this.getLayer(modal) : this.getLastLayer();
if (!layer) {
return;
}
await layer.modal.dismiss();
}
public async ok(result?: any, modal?: UxModal) {
const layer = modal ? this.getLayer(modal) : this.getLastLayer();
if (!layer) {
return;
}
await layer.modal.ok(result);
}
} | the_stack |
import * as FF from 'final-form'
import * as R from 'ramda'
import * as React from 'react'
import * as RF from 'react-final-form'
import * as urql from 'urql'
import * as M from '@material-ui/core'
import * as Intercom from 'components/Intercom'
import * as AWS from 'utils/AWS'
import * as Data from 'utils/Data'
import * as NamedRoutes from 'utils/NamedRoutes'
import StyledLink from 'utils/StyledLink'
import assertNever from 'utils/assertNever'
import { mkFormError, mapInputErrors } from 'utils/formTools'
import * as tagged from 'utils/taggedV2'
import * as Types from 'utils/types'
import * as validators from 'utils/validators'
import * as workflows from 'utils/workflows'
import * as PD from './PackageDialog'
import PACKAGE_PROMOTE from './PackageDialog/gql/PackagePromote.generated'
import * as requests from './requests'
const useFormSkeletonStyles = M.makeStyles((t) => ({
meta: {
marginTop: t.spacing(3),
},
}))
interface FormSkeletonProps {
animate?: boolean
}
function FormSkeleton({ animate }: FormSkeletonProps) {
const classes = useFormSkeletonStyles()
return (
<>
<PD.TextFieldSkeleton animate={animate} />
<PD.TextFieldSkeleton animate={animate} />
<PD.MetaInputSkeleton className={classes.meta} animate={animate} />
<PD.WorkflowsInputSkeleton animate={animate} />
</>
)
}
interface DialogTitleProps {
bucket: string
}
function DialogTitle({ bucket }: DialogTitleProps) {
const { urls } = NamedRoutes.use()
return (
<M.DialogTitle>
Push package to{' '}
<StyledLink target="_blank" to={urls.bucketOverview(bucket)}>
{bucket}
</StyledLink>{' '}
bucket
</M.DialogTitle>
)
}
const useStyles = M.makeStyles((t) => ({
form: {
display: 'flex',
flexDirection: 'column',
height: '100%',
overflowY: 'auto',
},
meta: {
display: 'flex',
flexDirection: 'column',
paddingTop: t.spacing(3),
overflowY: 'auto',
},
}))
interface DialogFormProps {
bucket: string
close: () => void
hash: string
initialMeta: PD.Manifest['meta']
name: string
setSubmitting: (submitting: boolean) => void
setSuccess: (success: PackageCreationSuccess) => void
setWorkflow: (workflow: workflows.Workflow) => void
successor: workflows.Successor
workflowsConfig: workflows.WorkflowsConfig
}
function DialogForm({
bucket,
close,
hash,
initialMeta,
name: initialName,
responseError,
schema,
schemaLoading,
selectedWorkflow,
setSubmitting,
setSuccess,
setWorkflow,
successor,
validate: validateMetaInput,
workflowsConfig,
}: DialogFormProps & PD.SchemaFetcherRenderProps) {
const nameValidator = PD.useNameValidator(selectedWorkflow)
const nameExistence = PD.useNameExistence(successor.slug)
const [nameWarning, setNameWarning] = React.useState<React.ReactNode>('')
const [metaHeight, setMetaHeight] = React.useState(0)
const classes = useStyles()
const validateWorkflow = PD.useWorkflowValidator(workflowsConfig)
const [, copyPackage] = urql.useMutation(PACKAGE_PROMOTE)
interface FormData {
commitMessage: string
name: string
meta: Types.JsonRecord | undefined
workflow: workflows.Workflow
}
// eslint-disable-next-line consistent-return
const onSubmit = async ({ commitMessage, name, meta, workflow }: FormData) => {
try {
const res = await copyPackage({
params: {
bucket: successor.slug,
name,
message: commitMessage,
userMeta: requests.getMetaValue(meta, schema) ?? null,
workflow:
// eslint-disable-next-line no-nested-ternary
workflow.slug === workflows.notAvailable
? null
: workflow.slug === workflows.notSelected
? ''
: workflow.slug,
},
src: {
bucket,
name: initialName,
hash,
},
})
if (res.error) throw res.error
if (!res.data) throw new Error('No data returned by the API')
const r = res.data.packagePromote
switch (r.__typename) {
case 'PackagePushSuccess':
setSuccess({ name, hash: r.revision.hash, bucket: successor.slug })
return
case 'OperationError':
return mkFormError(r.message)
case 'InvalidInput':
return mapInputErrors(r.errors)
default:
assertNever(r)
}
} catch (e: any) {
// eslint-disable-next-line no-console
console.error('Error creating manifest:')
// eslint-disable-next-line no-console
console.error(e)
return mkFormError(
e.message ? `Unexpected error: ${e.message}` : PD.ERROR_MESSAGES.MANIFEST,
)
}
}
const onSubmitWrapped = async (...args: Parameters<typeof onSubmit>) => {
setSubmitting(true)
try {
return await onSubmit(...args)
} finally {
setSubmitting(false)
}
}
const handleNameChange = React.useCallback(
async (name) => {
const nameExists = await nameExistence.validate(name)
const warning = <PD.PackageNameWarning exists={!!nameExists} />
if (warning !== nameWarning) {
setNameWarning(warning)
}
},
[nameWarning, nameExistence],
)
const [editorElement, setEditorElement] = React.useState<HTMLDivElement | null>(null)
const resizeObserver = React.useMemo(
() =>
new window.ResizeObserver((entries) => {
const { height } = entries[0].contentRect
setMetaHeight(height)
}),
[setMetaHeight],
)
// HACK: FIXME: it triggers name validation with correct workflow
const [hideMeta, setHideMeta] = React.useState(false)
const onFormChange = React.useCallback(
async ({ modified, values }) => {
if (modified.workflow && values.workflow !== selectedWorkflow) {
setWorkflow(values.workflow)
// HACK: FIXME: it triggers name validation with correct workflow
setHideMeta(true)
setTimeout(() => {
setHideMeta(false)
}, 300)
}
handleNameChange(values.name)
},
[handleNameChange, selectedWorkflow, setWorkflow],
)
React.useEffect(() => {
if (editorElement) resizeObserver.observe(editorElement)
return () => {
if (editorElement) resizeObserver.unobserve(editorElement)
}
}, [editorElement, resizeObserver])
const dialogContentClasses = PD.useContentStyles({ metaHeight })
return (
<RF.Form
onSubmit={onSubmitWrapped}
subscription={{
error: true,
hasValidationErrors: true,
submitError: true,
submitFailed: true,
submitting: true,
}}
>
{({
error,
hasValidationErrors,
submitError,
submitFailed,
submitting,
handleSubmit,
}) => (
<>
<DialogTitle bucket={successor.slug} />
<M.DialogContent classes={dialogContentClasses}>
<form onSubmit={handleSubmit} className={classes.form}>
<RF.FormSpy
subscription={{ modified: true, values: true }}
onChange={onFormChange}
/>
<RF.FormSpy
subscription={{ modified: true, values: true }}
onChange={({ modified, values }) => {
if (modified?.workflow) {
setWorkflow(values.workflow)
}
}}
/>
<RF.Field
component={PD.WorkflowInput}
name="workflow"
workflowsConfig={workflowsConfig}
initialValue={selectedWorkflow}
validate={validateWorkflow}
validateFields={['meta', 'workflow']}
errors={{
required: 'Workflow is required for this bucket.',
}}
/>
<RF.Field
component={PD.PackageNameInput}
name="name"
workflow={selectedWorkflow || workflowsConfig}
validate={validators.composeAsync(
validators.required,
nameValidator.validate,
)}
validateFields={['name']}
errors={{
required: 'Enter a package name',
invalid: 'Invalid package name',
pattern: `Name should match ${selectedWorkflow?.packageNamePattern}`,
}}
helperText={nameWarning}
initialValue={initialName}
/>
<RF.Field
component={PD.CommitMessageInput}
name="commitMessage"
validate={validators.required as FF.FieldValidator<any>}
validateFields={['commitMessage']}
errors={{
required: 'Enter a commit message',
}}
/>
{schemaLoading || hideMeta ? (
<PD.MetaInputSkeleton className={classes.meta} ref={setEditorElement} />
) : (
<RF.Field
className={classes.meta}
component={PD.MetaInput}
name="meta"
bucket={successor.slug}
schema={schema}
schemaError={responseError}
validate={validateMetaInput}
validateFields={['meta']}
isEqual={R.equals}
ref={setEditorElement}
initialValue={initialMeta}
/>
)}
<input type="submit" style={{ display: 'none' }} />
</form>
</M.DialogContent>
<M.DialogActions>
{submitting && (
<PD.SubmitSpinner>
{successor.copyData
? 'Copying files and writing manifest'
: 'Writing manifest'}
</PD.SubmitSpinner>
)}
{!submitting && (!!error || !!submitError) && (
<M.Box flexGrow={1} display="flex" alignItems="center" pl={2}>
<M.Icon color="error">error_outline</M.Icon>
<M.Box pl={1} />
<M.Typography variant="body2" color="error">
{error || submitError}
</M.Typography>
</M.Box>
)}
<M.Button onClick={close} disabled={submitting}>
Cancel
</M.Button>
<M.Button
onClick={handleSubmit}
variant="contained"
color="primary"
disabled={submitting || (submitFailed && hasValidationErrors)}
>
Push
</M.Button>
</M.DialogActions>
</>
)}
</RF.Form>
)
}
interface DialogErrorProps {
bucket: string
error: Error
onCancel: () => void
}
function DialogError({ bucket, error, onCancel }: DialogErrorProps) {
const { urls } = NamedRoutes.use()
return (
<PD.DialogError
error={error}
skeletonElement={<FormSkeleton animate={false} />}
title={
<>
Push package to{' '}
<StyledLink target="_blank" to={urls.bucketOverview(bucket)}>
{bucket}
</StyledLink>{' '}
bucket
</>
}
onCancel={onCancel}
/>
)
}
interface DialogLoadingProps {
bucket: string
onCancel: () => void
}
function DialogLoading({ bucket, onCancel }: DialogLoadingProps) {
const { urls } = NamedRoutes.use()
return (
<PD.DialogLoading
skeletonElement={<FormSkeleton />}
title={
<>
Push package to{' '}
<StyledLink target="_blank" to={urls.bucketOverview(bucket)}>
{bucket}
</StyledLink>{' '}
bucket
</>
}
onCancel={onCancel}
/>
)
}
interface PackageCreationSuccess {
bucket: string
name: string
hash: string
}
const DialogState = tagged.create(
'app/containers/Bucket/PackageCopyDialog:DialogState' as const,
{
Loading: () => {},
Error: (e: Error) => e,
Form: (v: { manifest: PD.Manifest; workflowsConfig: workflows.WorkflowsConfig }) => v,
Success: (v: PackageCreationSuccess) => v,
},
)
interface PackageCopyDialogProps {
open: boolean
bucket: string
successor: workflows.Successor | null
name: string
hash: string
onExited: (props: { pushed: PackageCreationSuccess | null }) => void
}
export default function PackageCopyDialog({
open,
bucket,
successor,
name,
hash,
onExited,
}: PackageCopyDialogProps) {
const s3 = AWS.S3.use()
const [success, setSuccess] = React.useState<PackageCreationSuccess | null>(null)
const [submitting, setSubmitting] = React.useState(false)
const [workflow, setWorkflow] = React.useState<workflows.Workflow>()
const manifestData = PD.useManifest({
bucket,
name,
hash,
skipEntries: true,
pause: !successor || !open,
})
const workflowsData = Data.use(
requests.workflowsConfig,
{ s3, bucket: successor ? successor.slug : '' },
{ noAutoFetch: !successor || !open },
)
const state = React.useMemo(() => {
if (success) return DialogState.Success(success)
return workflowsData.case({
Ok: (workflowsConfig: workflows.WorkflowsConfig) =>
manifestData.case({
Ok: (manifest: PD.Manifest) => DialogState.Form({ manifest, workflowsConfig }),
Err: DialogState.Error,
_: DialogState.Loading,
}),
Err: DialogState.Error,
_: DialogState.Loading,
})
}, [success, workflowsData, manifestData])
const handleExited = React.useCallback(() => {
if (submitting) return
onExited({
pushed: success,
})
setSuccess(null)
}, [submitting, success, setSuccess, onExited])
const close = React.useCallback(() => {
if (submitting) return
onExited({
pushed: success,
})
setSuccess(null)
}, [submitting, success, setSuccess, onExited])
Intercom.usePauseVisibilityWhen(open)
return (
<M.Dialog fullWidth onClose={close} onExited={handleExited} open={open} scroll="body">
{DialogState.match({
Error: (e) =>
successor && <DialogError bucket={successor.slug} onCancel={close} error={e} />,
Loading: () =>
successor && <DialogLoading bucket={successor.slug} onCancel={close} />,
Form: ({ manifest, workflowsConfig }) =>
successor && (
<PD.SchemaFetcher
initialWorkflowId={manifest.workflowId}
workflowsConfig={workflowsConfig}
workflow={workflow}
>
{(schemaProps) => (
<DialogForm
{...schemaProps}
{...{
bucket,
close,
setSubmitting,
setSuccess,
setWorkflow,
workflowsConfig,
initialMeta: manifest.meta,
hash,
name,
successor,
}}
/>
)}
</PD.SchemaFetcher>
),
Success: (props) => successor && <PD.DialogSuccess {...props} onClose={close} />,
})(state)}
</M.Dialog>
)
} | the_stack |
import {
Button,
FormControl,
FormHelperText,
FormLabel,
Input,
Popover,
PopoverArrow,
PopoverBody,
PopoverContent,
PopoverTrigger,
Portal,
Tab,
TabList,
TabPanel,
TabPanels,
Tabs,
useDisclosure,
} from "@chakra-ui/react";
import { ItemTypes } from "@/lib/ItemTypes";
import { MINIMUM_WIDGET_NAME_LENGTH } from "@/lib/constants";
import {
MinusIcon,
PlusCircleIcon,
PlusIcon,
VariableIcon,
} from "@heroicons/react/outline";
import { Widget } from "@prisma/client";
import {
activeWidgetIdSelector,
setActiveWidgetId,
} from "@/features/records/state-slice";
import { iconForWidget } from "..";
import { isArray, isEqual, snakeCase, sortBy } from "lodash";
import { toast } from "react-toastify";
import { useAddWidgetMutation, useReorderWidgetsMutation } from "../api-slice";
import { useAppDispatch, useAppSelector } from "@/hooks";
import { useDashboardResponse } from "../hooks";
import { useDataSourceContext } from "@/hooks";
import { useDrag, useDrop } from "react-dnd";
import DashedCreateBox from "@/components/DashedCreateBox";
import DragIcon from "@/components/DragIcon";
import React, { forwardRef, useEffect, useMemo, useRef, useState } from "react";
import Shimmer from "@/components/Shimmer";
import TinyLabel from "@/components/TinyLabel";
import classNames from "classnames";
import update from "immutability-helper";
const WidgetItem = ({
widget,
moveWidget,
}: {
widget: Widget;
moveWidget: any;
}) => {
const dispatch = useAppDispatch();
const activeWidgetId = useAppSelector(activeWidgetIdSelector);
const IconElement = iconForWidget(widget);
const toggleWidgetSelection = () => {
if (activeWidgetId === widget?.id) {
dispatch(setActiveWidgetId(null));
} else {
dispatch(setActiveWidgetId(widget.id));
}
};
const id = widget.name;
const [{ item, isDragging }, drag, preview] = useDrag(
() => ({
type: ItemTypes.WIDGET,
item: { id },
collect: (monitor) => ({
isDragging: monitor.isDragging(),
item: monitor.getItem(),
}),
}),
[moveWidget, id]
);
const [{ isOver }, drop] = useDrop(
() => ({
accept: ItemTypes.WIDGET,
collect: (monitor) => ({
isOver: monitor.isOver(),
}),
canDrop: () => false,
hover(item: { id: string }) {
const draggedWidgetName = item.id;
const overWidgetName = widget.name;
if (draggedWidgetName !== overWidgetName && moveWidget) {
moveWidget(draggedWidgetName, overWidgetName);
}
},
}),
[moveWidget, id]
);
return (
<div
className={classNames(
"relative flex items-center justify-between cursor-pointer group rounded",
{
"bg-blue-600 text-white": activeWidgetId === widget.id,
"hover:bg-gray-100":
activeWidgetId !== widget.id ||
(!isDragging && item?.id === widget?.name),
"!bg-gray-800 opacity-25":
isOver || (isDragging && item?.id === widget?.name),
}
)}
ref={preview}
>
<div className="flex items-center flex-1 hover:cursor-pointer">
<span ref={(node: any) => drag(drop(node))} className="h-full ml-1">
<DragIcon />{" "}
</span>
<div
className="flex-1 flex items-center justify-between"
onClick={toggleWidgetSelection}
>
<span className="flex items-center">
<IconElement className="h-4 self-start mt-1 ml-1 mr-2 lg:self-center lg:mt-0 inline-block flex-shrink-0" />{" "}
<span>{widget.name}</span>{" "}
</span>
</div>
</div>
</div>
);
};
const NameInput = forwardRef((props: any, ref: any) => {
return (
<FormControl>
<FormLabel htmlFor="name">Name</FormLabel>
<Input ref={ref} id="name" size="sm" {...props} />
<FormHelperText>What should the widget be called.</FormHelperText>
</FormControl>
);
});
NameInput.displayName = "NameInput";
// 2. Create the form
const Form = ({
firstFieldRef,
onClose,
type,
}: {
firstFieldRef: any;
onClose: () => void;
type: string;
}) => {
const dispatch = useAppDispatch();
const [name, setName] = useState("");
const [addWidget, { isLoading }] = useAddWidgetMutation();
const { dashboardId } = useDataSourceContext();
const { widgets } = useDashboardResponse(dashboardId);
const widgetExists = () =>
widgets.some((widget: Widget) => widget.name === snakeCase(name));
const createWidget = async () => {
if (name.length < MINIMUM_WIDGET_NAME_LENGTH) return;
// close popover
onClose();
const response = await addWidget({
dashboardId,
body: {
dashboardId,
name,
type,
},
}).unwrap();
if (response?.ok) {
// select the newly created widget
dispatch(setActiveWidgetId(response.data.id));
}
};
return (
<form
onSubmit={(e) => {
e.preventDefault();
if (widgetExists()) {
toast.error("A widget with that name already exists.");
return;
}
// Clear the input value
setName("");
firstFieldRef.current.value = "";
createWidget();
}}
>
<NameInput
ref={firstFieldRef}
onChange={(e: any) => setName(e.currentTarget.value)}
/>
<div className="mt-2">
<Button
type="submit"
size="sm"
colorScheme="blue"
width="100%"
isDisabled={name.length < MINIMUM_WIDGET_NAME_LENGTH}
isLoading={isLoading}
leftIcon={<PlusIcon className="text-white h-4" />}
>
Add {type}
</Button>
</div>
</form>
);
};
const DashboardEditWidgets = () => {
const dispatch = useAppDispatch();
const { onOpen, onClose, isOpen } = useDisclosure();
const { dashboardId } = useDataSourceContext();
const firstFieldRefMetric = useRef(null);
const firstFieldRefDivider = useRef(null);
const { isLoading: dashboardIsLoading, widgets } =
useDashboardResponse(dashboardId);
const [order, setOrder] = useState<string[]>([]);
useEffect(() => {
if (isArray(widgets)) {
const newOrder = sortBy(widgets, [(w) => w?.order]).map(
({ name }: Widget) => name
);
setOrder(newOrder);
}
}, [widgets]);
const orderedWidgets = useMemo(
() => sortBy(widgets, [(widget: Widget) => order.indexOf(widget.name)]),
[widgets, order]
);
const [{ didDrop }, drop] = useDrop(() => ({
accept: ItemTypes.WIDGET,
collect: (monitor) => ({
didDrop:
monitor.getItemType() === ItemTypes.WIDGET ? monitor.didDrop() : false,
}),
}));
const [reorderWidgets] = useReorderWidgetsMutation();
const moveWidget = (from: string, to: string) => {
const fromIndex = order.indexOf(from);
const toIndex = order.indexOf(to);
const newOrder = update(order, {
$splice: [
[fromIndex, 1],
[toIndex, 0, from],
],
}).filter(Boolean);
if (!isEqual(order, newOrder)) {
setOrder(newOrder);
}
};
// We have to save the order of the widgets when the order changes, and the order changes when an element is dropped.
useEffect(() => {
if (didDrop === true) {
reorderWidgets({
dashboardId,
body: { order },
}).unwrap();
}
}, [didDrop]);
useEffect(() => {
return () => {
dispatch(setActiveWidgetId(null));
};
}, []);
const ContentForPopover = () => (
<Portal>
<PopoverContent
rootProps={{
style: {
zIndex: 40,
},
}}
>
<PopoverArrow />
<PopoverBody>
<Tabs isFitted>
<TabList size="sm">
<Tab>
Metric{" "}
<VariableIcon className="h-4 self-start mt-1 ml-1 mr-2 lg:self-center lg:mt-0 inline-block flex-shrink-0" />
</Tab>
<Tab>
Divider{" "}
<MinusIcon className="h-4 self-start mt-1 ml-1 mr-2 lg:self-center lg:mt-0 inline-block flex-shrink-0" />
</Tab>
</TabList>
<TabPanels>
<TabPanel>
<Form
firstFieldRef={firstFieldRefMetric}
onClose={onClose}
type="metric"
/>
</TabPanel>
<TabPanel>
<Form
firstFieldRef={firstFieldRefDivider}
onClose={onClose}
type="divider"
/>
</TabPanel>
</TabPanels>
</Tabs>
</PopoverBody>
</PopoverContent>
</Portal>
);
return (
<div>
<div className="flex justify-between">
<div>
<TinyLabel>Widgets</TinyLabel>{" "}
{widgets.length > 0 && (
<span className="text-xs text-gray-600">(click to edit)</span>
)}
</div>
{widgets.length > 0 && (
<div className="flex items-center">
<Popover
isOpen={isOpen}
initialFocusRef={firstFieldRefMetric}
onOpen={onOpen}
onClose={onClose}
>
<PopoverTrigger>
<div className="flex justify-center items-center h-full mx-1 text-xs cursor-pointer">
<PlusCircleIcon className="h-4 inline mr-px" /> Add
</div>
</PopoverTrigger>
<ContentForPopover />
</Popover>
</div>
)}
</div>
{widgets.length === 0 && (
<Popover
isOpen={isOpen}
initialFocusRef={firstFieldRefMetric}
onOpen={onOpen}
onClose={onClose}
>
<PopoverTrigger>
<div>
<DashedCreateBox>Create widget</DashedCreateBox>
</div>
</PopoverTrigger>
<ContentForPopover />
</Popover>
)}
<div className="mt-2" ref={drop}>
{dashboardIsLoading && (
<div className="space-y-1">
<Shimmer height="15px" width="60px" />
<Shimmer height="15px" width="160px" />
<Shimmer height="15px" width="120px" />
<Shimmer height="15px" width="80px" />
<Shimmer height="15px" width="140px" />
<Shimmer height="15px" width="210px" />
<Shimmer height="15px" width="90px" />
<Shimmer height="15px" width="110px" />
</div>
)}
{!dashboardIsLoading &&
orderedWidgets &&
orderedWidgets.map((widget: Widget, idx: number) => (
<WidgetItem key={idx} widget={widget} moveWidget={moveWidget} />
))}
</div>
</div>
);
};
export default DashboardEditWidgets; | the_stack |
/**
* Attributes for dynamic constraints.
* We define one default attribute as style. Speech rule stores can add other
* attributes later.
*/
export enum Axis {
DOMAIN = 'domain',
STYLE = 'style',
LOCALE = 'locale',
TOPIC = 'topic',
MODALITY = 'modality'
}
export type AxisProperties = {[key: string]: string[]};
export type AxisOrder = Axis[];
export type AxisValues = {[key: string]: boolean};
export type AxisMap = {[key: string]: string};
namespace CstrValues {
/**
* Initialises an object for collecting all values per axis.
*/
const axisToValues: {[key: string]: AxisValues} = {
[Axis.DOMAIN]: {},
[Axis.STYLE]: {},
[Axis.LOCALE]: {},
[Axis.TOPIC]: {},
[Axis.MODALITY]: {}
};
/**
* Registers a constraint value for a given axis
* @param axis The axis.
* @param value The value for the axis.
*/
export function add(axis: Axis, value: string) {
axisToValues[axis][value] = true;
}
/**
* @return The sets of values
* for all constraint attributes.
*/
export function get(): AxisProperties {
let result: AxisProperties = {};
for (let [key, values] of Object.entries(axisToValues)) {
result[key] = Object.keys(values);
}
return result;
}
}
export class DynamicProperties {
/**
* Convenience method to create a standard dynamic constraint, that follows a
* pre-prescribed order of the axes.
* @param cstrList Dynamic property lists for the Axes.
*/
public static createProp(...cstrList: string[][]): DynamicProperties {
let axes = DynamicCstr.DEFAULT_ORDER;
let dynamicCstr: AxisProperties = {};
for (let i = 0, l = cstrList.length, k = axes.length; i < l && i < k; i++) {
dynamicCstr[axes[i]] = cstrList[i];
}
return new DynamicProperties(dynamicCstr);
}
/**
* @param properties The
* property mapping.
* @param opt_order A parse order of the keys.
*/
constructor(private properties: AxisProperties,
protected order: AxisOrder = Object.keys(properties) as Axis[]) {
}
/**
* @return The components of
* the constraint.
*/
public getProperties(): AxisProperties {
return this.properties;
}
/**
* @return The priority order of constraint attributes
* in the comparator.
*/
public getOrder(): AxisOrder {
return this.order;
}
/**
* @return The components of the constraint.
*/
public getAxes(): AxisOrder {
return this.order;
}
/**
* Returns the value of the constraint for a particular attribute key.
* @param key The attribute key.
* @return The component value of the constraint.
*/
public getProperty(key: Axis): string[] {
return this.properties[key];
}
/**
* Updates the dynamic properties from another one.
* @param props A second
* properties element.
*/
public updateProperties(props: AxisProperties) {
this.properties = props;
}
/**
* Convenience method to return the ordered list of properties.
* @return Ordered list of lists of constraint values.
*/
public allProperties(): string[][] {
let propLists: string[][] = [];
this.order.forEach(key =>
propLists.push(this.getProperty(key).slice()));
return propLists;
}
/**
* @override
*/
public toString() {
let cstrStrings: string[] = [];
this.order.forEach(key =>
cstrStrings.push(key + ': ' + this.getProperty(key).toString()));
return cstrStrings.join('\n');
}
}
export class DynamicCstr extends DynamicProperties {
/**
* Default order of constraints.
*/
public static DEFAULT_ORDER: AxisOrder =
[Axis.LOCALE, Axis.MODALITY, Axis.DOMAIN, Axis.STYLE, Axis.TOPIC];
/**
* Default values for to assign. Value is default.
*/
public static DEFAULT_VALUE: string = 'default';
/**
* Default values for axes.
*/
public static DEFAULT_VALUES: AxisMap = {
[Axis.LOCALE]: 'en',
[Axis.DOMAIN]: DynamicCstr.DEFAULT_VALUE,
[Axis.STYLE]: DynamicCstr.DEFAULT_VALUE,
[Axis.TOPIC]: DynamicCstr.DEFAULT_VALUE,
[Axis.MODALITY]: 'speech'
};
private static Values_: any;
private components: AxisMap;
/**
* @return The sets of values
* for all constraint attributes.
*/
public static getAxisValues(): AxisProperties {
return DynamicCstr.Values_.getInstance().get();
}
/**
* Convenience method to create a standard dynamic constraint, that follows a
* pre-prescribed order of the axes.
* @param cstrList Dynamic constraint values for the Axes.
*/
public static createCstr(...cstrList: string[]): DynamicCstr {
let axes = DynamicCstr.DEFAULT_ORDER;
let dynamicCstr: AxisMap = {};
for (let i = 0, l = cstrList.length, k = axes.length; i < l && i < k; i++) {
dynamicCstr[axes[i]] = cstrList[i];
}
return new DynamicCstr(dynamicCstr);
}
/**
* @return A default constraint of maximal order.
*/
public static defaultCstr(): DynamicCstr {
return DynamicCstr.createCstr.apply(
null, DynamicCstr.DEFAULT_ORDER.map(function(x) {
return DynamicCstr.DEFAULT_VALUES[x];
}));
}
/**
* Checks explicitly if a dynamic constraint order is indeed valid.
* @param order The order to check.
* @return True if the order only contains valid axis descriptions.
*/
public static validOrder(order: AxisOrder): boolean {
let axes = DynamicCstr.DEFAULT_ORDER.slice();
return order.every(x => {
let index = axes.indexOf(x);
return index !== -1 && axes.splice(index, 1);
});
}
/**
* Dynamic constraints are a means to specialize rules that can be changed
* dynamically by the user, for example by choosing different styles, etc.
* @param cstr The constraint mapping.
* @param opt_order A parse order of the keys.
*/
constructor(components_: AxisMap, order?: AxisOrder) {
let properties: AxisProperties = {};
for (let [key, value] of Object.entries(components_)) {
properties[key] = [value];
CstrValues.add(key as Axis, value);
}
super(properties, order);
this.components = components_;
}
/**
* @return The components of the
* constraint.
*/
public getComponents(): AxisMap {
return this.components;
}
/**
* Returns the value of the constraint for a particular attribute key.
* @param key The attribute key.
* @return The component value of the constraint.
*/
public getValue(key: Axis): string {
return this.components[key];
}
/**
* Convenience method to return the ordered list of constraint values.
* @return Ordered list of constraint values.
*/
public getValues(): string[] {
return this.order.map(key => this.getValue(key));
}
/**
* @override
*/
public allProperties() {
let propLists = super.allProperties();
for (let i = 0, props, key; props = propLists[i], key = this.order[i];
i++) {
let value = this.getValue(key);
if (props.indexOf(value) === -1) {
props.unshift(value);
}
}
return propLists;
}
/**
* @override
*/
public toString() {
return this.getValues().join('.');
}
/**
* Tests whether the dynamic constraint is equal to a given one.
* @param cstr Dynamic constraints.
* @return True if the preconditions apply to the node.
*/
public equal(cstr: DynamicCstr): boolean {
let keys1 = cstr.getAxes();
if (this.order.length !== keys1.length) {
return false;
}
for (let j = 0, key; key = keys1[j]; j++) {
let comp2 = this.getValue(key);
if (!comp2 || cstr.getValue(key) !== comp2) {
return false;
}
}
return true;
}
}
export class DynamicCstrParser {
/**
* A parser for dynamic constraint representations.
* @param order The order of attributes in the
* dynamic constraint string.
*/
constructor(private order: AxisOrder) {}
/**
* Parses the dynamic constraint for math rules, consisting of a domain and
* style information, given as 'domain.style'.
* @param str A string representation of the dynamic constraint.
* @return The dynamic constraint.
*/
public parse(str: string): DynamicCstr {
let order = str.split('.');
let cstr: AxisMap = {};
if (order.length > this.order.length) {
throw new Error('Invalid dynamic constraint: ' + cstr);
}
let j = 0;
for (let i = 0, key; key = this.order[i], order.length; i++, j++) {
let value = order.shift();
cstr[key] = value;
}
return new DynamicCstr(cstr, this.order.slice(0, j));
}
}
export interface Comparator {
/**
* @return The current reference constraint in the comparator.
*/
getReference(): DynamicCstr;
/**
* Sets the reference constraint in the comparator.
* @param cstr A new reference constraint.
* @param opt_props An optional properties element
* for matching.
*/
setReference(cstr: DynamicCstr, opt_props?: DynamicProperties): void;
/**
* Checks if dynamic constraints matches the reference constraint.
* @param cstr The dynamic constraint to match.
* @return True if the constraint matches a possibly relaxed version
* of the reference constraint.
*/
match(cstr: DynamicCstr): boolean;
/**
* Compares two dynamic constraints for order with respect to the reference
* constraint and the priority order of the comparator.
* @param cstr1 First dynamic constraint.
* @param cstr2 Second dynamic constraint.
* @return A negative integer, zero, or a positive integer as the first
* argument is less than, equal to, or greater than the second.
*/
compare(cstr1: DynamicCstr, cstr2: DynamicCstr): number;
}
export class DefaultComparator implements Comparator {
private order: AxisOrder;
/**
* A default comparator for dynamic constraints. Has initially a reference
* constraint with default values only.
*
* @param reference A reference constraint.
* @param fallback An optional properties element for matching. This is a
* preference order, if more than one property value are given.
*/
constructor(private reference: DynamicCstr,
private fallback: DynamicProperties =
new DynamicProperties(reference.getProperties(), reference.getOrder())) {
this.order = this.reference.getOrder();
}
/**
* @override
* @final
*/
public getReference() {
return this.reference;
}
/**
* @override
* @final
*/
public setReference(cstr: DynamicCstr, props?: DynamicProperties) {
this.reference = cstr;
this.fallback = props ||
new DynamicProperties(cstr.getProperties(), cstr.getOrder());
this.order = this.reference.getOrder();
}
/**
* @override
*/
public match(cstr: DynamicCstr) {
let keys1 = cstr.getAxes();
return keys1.length === this.reference.getAxes().length &&
keys1.every(key => {
let value = cstr.getValue(key);
return value === this.reference.getValue(key) ||
this.fallback.getProperty(key).indexOf(value) !== -1;
});
}
/**
* @override
*/
public compare(cstr1: DynamicCstr, cstr2: DynamicCstr) {
let ignore = false;
for (let i = 0, key; key = this.order[i]; i++) {
let value1 = cstr1.getValue(key);
let value2 = cstr2.getValue(key);
// As long as the constraint values are the same as the reference value,
// we continue to compare them, otherwise we ignore them, to go for the
// best matching fallback rule, wrt. priority order.
if (!ignore) {
let ref = this.reference.getValue(key);
if (ref === value1 && ref !== value2) {
return -1;
}
if (ref === value2 && ref !== value1) {
return 1;
}
if (ref === value1 && ref === value2) {
continue;
}
if (ref !== value1 && ref !== value2) {
ignore = true;
}
}
let prop = this.fallback.getProperty(key);
let index1 = prop.indexOf(value1);
let index2 = prop.indexOf(value2);
if (index1 < index2) {
return -1;
}
if (index2 < index1) {
return 1;
}
}
return 0;
}
/**
* @override
*/
public toString() {
return this.reference.toString() + '\n' + this.fallback.toString();
}
} | the_stack |
import { FastPath } from './fastPath';
import { Doc, concat, join, indent, hardline, softline, group, line } from './docBuilder';
import { willBreak, propagateBreaks } from './docUtils';
import { printComments, printDanglingComments, printDanglingStatementComments } from './comments';
import { locEnd, isNextLineEmpty, hasNewLineInRange } from './util';
import { Options, getStringQuotemark, getAlternativeStringQuotemark, Quotemark } from './options';
import * as luaparse from 'luaparse';
export type PrintFn = (path: FastPath) => Doc;
// Prints a sequence of statements with a newline separating them..
// ex:
// local a = 1
// local b = 2
function printStatementSequence(path: FastPath, options: Options, print: PrintFn): Doc {
const printed: Doc[] = [];
path.forEach((statementPath) => {
const parts = [print(statementPath)];
if (isNextLineEmpty(options.sourceText, locEnd(statementPath.getValue())) && !isLastStatement(path)) {
parts.push(hardline);
}
printed.push(concat(parts));
});
return join(hardline, printed);
}
// Same as printStatementSequence, however the statements are indented
function printIndentedStatementList(path: FastPath, options: Options, print: PrintFn, field: string): Doc {
const printedBody = path.call((bodyPath) => {
return printStatementSequence(bodyPath, options, print);
}, field);
return indent(concat([hardline, printedBody]));
}
// Prints a comment present at the end of a statement leading to a block, which would otherwise fall into the body of
// the statement. Doing so might remove contextual information in the comment.
function printDanglingStatementComment(path: FastPath) {
const comments = (path.getValue() as any).attachedComments;
if (!comments) { return ''; }
return concat([printDanglingStatementComments(path), printDanglingComments(path)]);
}
function makeStringLiteral(raw: string, quotemark: Quotemark) {
const preferredQuoteCharacter = getStringQuotemark(quotemark);
const alternativeQuoteCharacter = getAlternativeStringQuotemark(quotemark === 'single' ? 'single' : 'double');
const newString = raw.replace(/\\([\s\S])|(['"])/g, (match, escaped, quote) => {
if (escaped === alternativeQuoteCharacter) {
return escaped;
}
if (quote === preferredQuoteCharacter) {
return '\\' + quote;
}
return match;
});
return preferredQuoteCharacter + newString + preferredQuoteCharacter;
}
function printStringLiteral(path: FastPath, options: Options): Doc {
const literal = path.getValue() as luaparse.StringLiteral;
if (literal.type !== 'StringLiteral') {
throw new Error('printStringLiteral: Expected StringLiteral, got ' + literal.type);
}
// Ignore raw string literals as they have no leading/trailing quotes.
if (literal.raw.startsWith('[[') || literal.raw.startsWith('[=')) {
return literal.raw;
}
// Strip off the leading and trailing quote characters from the raw string
const raw = literal.raw.slice(1, -1);
let preferredQuotemark = options.quotemark;
const preferredQuoteCharacter = getStringQuotemark(preferredQuotemark);
// If the string literal already contains the preferred quote character, then use the alternative to improve
// potential readability issues.
if (raw.includes(preferredQuoteCharacter)) {
preferredQuotemark = preferredQuotemark === 'single' ? 'double' : 'single';
}
return makeStringLiteral(raw, preferredQuotemark);
}
function isLastStatement(path: FastPath) {
const parent = path.getParent();
const node = path.getValue();
const body = parent.body;
return body && body[body.length - 1] === node;
}
function printNodeNoParens(path: FastPath, options: Options, print: PrintFn) {
const value = path.getValue();
if (!value) {
return '';
}
const parts: Doc[] = [];
const node = value as luaparse.Node;
switch (node.type) {
case 'Chunk':
parts.push(
path.call((bodyPath) => {
return printStatementSequence(bodyPath, options, print);
}, 'body'));
parts.push(printDanglingComments(path, true));
if (node.body.length || (node as any).attachedComments) {
parts.push(hardline);
}
return concat(parts);
// Statements
case 'LabelStatement':
return concat(['::', path.call(print, 'label'), '::']);
case 'GotoStatement':
return concat(['goto ', path.call(print, 'label')]);
case 'BreakStatement':
return 'break';
case 'ReturnStatement':
parts.push('return');
if (node.arguments.length > 0) {
parts.push(' ');
parts.push(join(', ', path.map(print, 'arguments')));
}
return concat(parts);
case 'WhileStatement':
parts.push('while ');
parts.push(path.call(print, 'condition'));
parts.push(' do');
parts.push(printDanglingStatementComment(path));
if (node.body.length) {
parts.push(printIndentedStatementList(path, options, print, 'body'));
}
parts.push(concat([hardline, 'end']));
return concat(parts);
case 'DoStatement':
parts.push('do');
parts.push(printDanglingStatementComment(path));
if (node.body.length) {
parts.push(printIndentedStatementList(path, options, print, 'body'));
}
parts.push(concat([hardline, 'end']));
return concat(parts);
case 'RepeatStatement':
parts.push('repeat');
parts.push(printDanglingStatementComment(path));
if (node.body.length) {
parts.push(printIndentedStatementList(path, options, print, 'body'));
}
parts.push(concat([hardline, 'until ']));
parts.push(path.call(print, 'condition'));
return concat(parts);
case 'LocalStatement':
case 'AssignmentStatement':
{
const left = [];
if (node.type === 'LocalStatement') {
left.push('local ');
}
const shouldBreak = options.linebreakMultipleAssignments;
left.push(
indent(
join(
concat([
',',
shouldBreak ? hardline : line
]),
path.map(print, 'variables')
)
)
);
let operator = '';
const right = [];
if (node.init.length) {
operator = ' =';
if (node.init.length > 1) {
right.push(
indent(
join(
concat([',', line]), path.map(print, 'init')
)
)
);
} else {
right.push(
join(concat([',', line]), path.map(print, 'init'))
);
}
}
// HACK: This definitely needs to be improved, as I'm sure TableConstructorExpression isn't the only
// candidate that falls under this critera.
//
// Due to the nature of how groups break, if the TableConstructorExpression contains a newline (and
// thusly breaks), the break will propagate all the way up to the group on the left of the assignment.
// This results in the table's initial { character being moved to a separate line.
//
// There's probably a much better way of doing this, but it works for now.
const canBreakLine = node.init.some(n =>
n != null &&
n.type !== 'TableConstructorExpression' &&
n.type !== 'FunctionDeclaration'
);
return group(
concat([
group(concat(left)),
group(
concat([
operator,
canBreakLine ? indent(line) : ' ',
concat(right)
])
)
])
);
}
case 'CallStatement':
return path.call(print, 'expression');
case 'FunctionDeclaration':
if (node.isLocal) {
parts.push('local ');
}
parts.push('function');
if (node.identifier) {
parts.push(' ', path.call(print, 'identifier'));
}
parts.push(concat([
'(',
group(
indent(
concat([
softline,
join(concat([',', line]), path.map(print, 'parameters'))
])
)
),
')'
])
);
parts.push(printDanglingStatementComment(path));
if (node.body.length) {
parts.push(printIndentedStatementList(path, options, print, 'body'));
}
parts.push(hardline, 'end');
return concat(parts);
case 'ForNumericStatement':
parts.push('for ');
parts.push(path.call(print, 'variable'));
parts.push(' = ');
parts.push(path.call(print, 'start'));
parts.push(', ');
parts.push(path.call(print, 'end'));
if (node.step) {
parts.push(', ');
parts.push(path.call(print, 'step'));
}
parts.push(' do');
parts.push(printDanglingStatementComment(path));
if (node.body.length) {
parts.push(printIndentedStatementList(path, options, print, 'body'));
}
parts.push(concat([hardline, 'end']));
return concat(parts);
case 'ForGenericStatement':
parts.push('for ');
parts.push(join(', ', path.map(print, 'variables')));
parts.push(' in ');
parts.push(join(', ', path.map(print, 'iterators')));
parts.push(' do');
parts.push(printDanglingStatementComment(path));
if (node.body.length) {
parts.push(printIndentedStatementList(path, options, print, 'body'));
}
parts.push(concat([hardline, 'end']));
return concat(parts);
case 'IfStatement':
const printed: Doc[] = [];
path.forEach((statementPath) => {
printed.push(print(statementPath));
}, 'clauses');
parts.push(join(hardline, printed));
parts.push(concat([hardline, 'end']));
return concat(parts);
// Clauses
case 'IfClause':
parts.push(concat([
'if ',
group(
concat([
indent(concat([
softline,
path.call(print, 'condition')
])),
softline
])
),
' then'
]));
parts.push(printDanglingStatementComment(path));
if (node.body.length) {
parts.push(printIndentedStatementList(path, options, print, 'body'));
}
return concat(parts);
case 'ElseifClause':
parts.push(concat([
'elseif ',
group(
concat([
indent(concat([
softline,
path.call(print, 'condition')
])),
softline
])
),
' then'
]));
parts.push(printDanglingStatementComment(path));
if (node.body.length) {
parts.push(printIndentedStatementList(path, options, print, 'body'));
}
return concat(parts);
case 'ElseClause':
parts.push('else');
parts.push(printDanglingStatementComment(path));
if (node.body.length) {
parts.push(printIndentedStatementList(path, options, print, 'body'));
}
return concat(parts);
// Literals
case 'BooleanLiteral':
return node.raw;
case 'NilLiteral':
return 'nil';
case 'NumericLiteral':
return node.raw;
case 'StringLiteral':
return printStringLiteral(path, options);
case 'VarargLiteral':
return '...';
case 'Identifier':
return node.name;
// Expressions
case 'BinaryExpression':
case 'LogicalExpression':
const parent = path.getParent() as luaparse.Node;
const shouldGroup = parent.type !== node.type &&
node.left.type !== node.type &&
node.right.type !== node.type;
const right = concat([
node.operator,
line,
path.call(print, 'right')
]);
return group(
concat([
path.call(print, 'left'),
indent(concat([
' ', shouldGroup ? group(right) : right
]))
])
);
case 'UnaryExpression':
parts.push(node.operator);
if (node.operator === 'not') {
parts.push(' ');
}
parts.push(path.call(print, 'argument'));
return concat(parts);
case 'MemberExpression':
return concat([
path.call(print, 'base'),
node.indexer,
path.call(print, 'identifier')
]);
case 'IndexExpression':
return concat([
path.call(print, 'base'),
'[',
group(
concat([
indent(concat([softline, path.call(print, 'index')])),
softline
])
),
']'
]);
case 'CallExpression':
const printedCallExpressionArgs = path.map(print, 'arguments');
// TODO: We should implement prettier's conditionalGroup construct to try and fit the most appropriately
// fitting combination of argument layout. I.e: If all arguments but the last fit on the same line, and the
// last argument is a table, it would be beneficial to break on the table, rather than breaking the entire
// argument list.
return concat([
path.call(print, 'base'),
group(
concat([
'(',
indent(
concat([softline, join(concat([',', line]), printedCallExpressionArgs)])
),
softline,
')'
]),
printedCallExpressionArgs.some(willBreak)
)
]);
case 'TableCallExpression':
parts.push(path.call(print, 'base'));
parts.push(' ');
parts.push(path.call(print, 'arguments'));
return concat(parts);
case 'StringCallExpression':
parts.push(path.call(print, 'base'));
parts.push(' ');
parts.push(path.call(print, 'argument'));
return concat(parts);
case 'TableConstructorExpression':
if (node.fields.length === 0) {
return '{}';
}
const fields: Doc[] = [];
let separatorParts: Doc[] = [];
path.forEach(childPath => {
fields.push(concat(separatorParts));
fields.push(group(print(childPath)));
separatorParts = [',', line];
}, 'fields');
// If the user has placed their own linebreaks in the table, they probably want them to be preserved
const shouldBreak = hasNewLineInRange(options.sourceText, node.range[0], node.range[1]);
return group(
concat([
'{',
indent(
concat([softline, concat(fields)])
),
softline,
'}'
]),
shouldBreak
);
case 'TableKeyString':
return concat([
path.call(print, 'key'),
' = ',
path.call(print, 'value')
]);
case 'TableKey':
return concat([
'[', path.call(print, 'key'), ']',
' = ',
path.call(print, 'value')
]);
case 'TableValue':
return path.call(print, 'value');
}
throw new Error('Unhandled AST node: ' + node.type);
}
function printNode(path: FastPath, options: Options, print: PrintFn) {
const printed = printNodeNoParens(path, options, print);
const parts = [];
const needsParens = path.needsParens();
if (needsParens) {
parts.push('(');
}
parts.push(printed);
if (needsParens) {
parts.push(')');
}
return concat(parts);
}
export function buildDocFromAst(ast: luaparse.Chunk, options: Options) {
const printNodeWithComments = (path: FastPath): Doc => {
return printComments(path, options, p => printNode(p, options, printNodeWithComments));
};
const doc = printNodeWithComments(new FastPath(ast));
propagateBreaks(doc);
return doc;
} | the_stack |
import * as assert from "assert";
import * as fs from "fs-extra";
import * as spectron from "spectron";
import {generateAuthCredentials, generatePlatformProject} from "../../util/generator";
import {mockSBGClient} from "../../util/sbg-client-proxy";
import {boot, proxerialize, shutdown} from "../../util/util";
describe("dirty checking", async () => {
let app: spectron.Application;
const user = generateAuthCredentials("test-user", "https://api.sbgenomics.com");
const project = generatePlatformProject({id: "test-user/test-project"});
const localTool = fs.readFileSync(__dirname + "/stub/local-tool.json", "utf-8");
const localWorkflow = fs.readFileSync(__dirname + "/stub/local-workflow.json", "utf-8");
const platformTool = fs.readFileSync(__dirname + "/stub/platform-tool.json", "utf-8");
const platformWorkflow = fs.readFileSync(__dirname + "/stub/platform-workflow.json", "utf-8");
const localFile = fs.readFileSync(__dirname + "/stub/local-file.json", "utf-8");
afterEach(() => shutdown(app));
describe("prevent closing tabs", async () => {
it("modal should prevent closing dirty apps", async function () {
app = await boot(this, {
prepareTestData: [{
name: "demo-app-tool.json",
content: localTool
}],
localRepository: {
credentials: [user],
activeCredentials: user,
openTabs: [{
id: "test:/demo-app-tool.json",
type: "CommandLineTool",
label: "My Demo App",
isWritable: true
}]
},
platformRepositories: {
[user.id]: {
projects: [project],
openProjects: [project.id]
}
}
});
const client = app.client;
const visualEditor = `ct-tool-visual-editor`;
const tab = `ct-workbox .tab`;
const closingDirtyAppsModal = `ct-modal-closing-dirty-apps`;
const commonDocumentControls = `ct-common-document-controls`;
const docker = `[data-test="docker-pull-input"]`;
await client.waitForVisible(visualEditor);
await client.waitForVisible(docker);
// Tab should not be dirty
await waitUntilTabBecomeDirty(client, tab, false);
// Set docker value
await client.setValue(docker, "someText");
// Wait until tab is dirty
await waitUntilTabBecomeDirty(client, tab);
// Click to close the tab, Dirty Apps Modal should appear
await client.click(`${tab} .close-icon`);
await client.waitForVisible(closingDirtyAppsModal);
// If you click on Cancel button, tab should be still Dirty
await client.click(`${closingDirtyAppsModal} [data-test="dirty-app-modal-cancel-button"]`);
await waitUntilTabBecomeDirty(client, tab);
// When you click on Save button, tab should not be Dirty anymore
await client.click(`${commonDocumentControls} [data-test="save-button"]`);
await waitUntilTabBecomeDirty(client, tab, false);
// When you change something again tab should be Dirty
await client.setValue(docker, "someText1");
await waitUntilTabBecomeDirty(client, tab);
// Click to close the tab, Dirty Apps Modal should appear
await client.click(`${tab} .close-icon`);
await client.waitForVisible(closingDirtyAppsModal);
// If you click on Save button app should be saved and Dirty state should be false
await client.click(`${closingDirtyAppsModal} [data-test="dirty-app-modal-save-button"]`);
await waitUntilTabBecomeDirty(client, tab, false);
// If you click on close button now, tab should be closed
await client.click(`${tab} .close-icon`);
await client.waitUntil(async () => {
const isVisible = await client.isVisible(tab);
return !isVisible;
}, 5000);
});
it("modal that prevents closing dirty tabs should have discard button", async function () {
app = await boot(this, {
prepareTestData: [{
name: "demo-app-tool.json",
content: localTool
}],
localRepository: {
credentials: [user],
activeCredentials: user,
openTabs: [{
id: "test:/demo-app-tool.json",
type: "CommandLineTool",
label: "My Demo App",
isWritable: true
}]
},
platformRepositories: {
[user.id]: {
projects: [project],
openProjects: [project.id]
}
}
});
const client = app.client;
const visualEditor = `ct-tool-visual-editor`;
const tab = `ct-workbox .tab`;
const closingDirtyAppsModal = `ct-modal-closing-dirty-apps`;
const docker = `[data-test="docker-pull-input"]`;
await client.waitForVisible(visualEditor);
await client.waitForVisible(docker);
// Set docker value
await client.setValue(docker, "someText");
// Wait until tab is dirty
await waitUntilTabBecomeDirty(client, tab);
// Click to close the tab, Dirty Apps Modal should appear
await client.click(`${tab} .close-icon`);
await client.waitForVisible(closingDirtyAppsModal);
// If you click on Discard button app tab should be closed
await client.click(`${closingDirtyAppsModal} [data-test="dirty-app-modal-discard-button"]`);
await client.waitUntil(async () => {
const isVisible = await client.isVisible(tab);
return !isVisible;
}, 5000);
});
it("Close all tabs context menu item should work as expected", async function () {
app = await boot(this, {
prepareTestData: [{
name: "demo-app-tool1.json",
content: localTool
},
{
name: "demo-app-tool2.json",
content: localTool
}],
localRepository: {
credentials: [user],
activeCredentials: user,
openTabs: [{
id: "test:/demo-app-tool1.json",
type: "CommandLineTool",
label: "My Demo App",
isWritable: true
},
{
id: "test:/demo-app-tool2.json",
type: "CommandLineTool",
label: "My Demo App",
isWritable: true
}]
},
platformRepositories: {
[user.id]: {
projects: [project],
openProjects: [project.id]
}
}
});
const client = app.client;
const visualEditor = `ct-tool-visual-editor`;
const tab = `ct-workbox .tab`;
const activeTab = `ct-workbox .tab.active`;
const docker = `[data-test="docker-pull-input"]`;
const contextMenu = `ct-menu`;
const contextMenuItem = `ct-menu-item`;
const modalConfirm = `ct-modal-confirm`;
await client.waitForVisible(visualEditor);
await client.waitForVisible(docker);
let tabs = await client.elements(`.tab`);
assert.equal(tabs.value.length, 2, "2 tabs should be visible");
await client.setValue(docker, "someText");
// Wait until active tab becomes dirty
await waitUntilTabBecomeDirty(client, activeTab);
// Right click on active tab (second one is active) to open the context menu
await client.rightClick(activeTab);
await client.waitForVisible(contextMenu);
// click on close all item
await client.click(`${contextMenuItem}:nth-of-type(2)`);
// Confirm modal should appear
await client.waitForVisible(modalConfirm);
// click on Cancel button
await client.click(`${modalConfirm} .btn-secondary`);
// Both tabs should be still visible
tabs = await client.elements(`.tab`);
assert.equal(tabs.value.length, 2, "2 tabs should be still here");
// Click on first tab to activate it
await client.click(`${tab}:nth-of-type(1)`);
// Right click on active tab (first one is active) to open the context menu
await client.rightClick(activeTab);
// click on close all
await client.click(`${contextMenuItem}:nth-of-type(2)`);
// Confirm modal should appear
await client.waitForVisible(modalConfirm);
// Click on confirmation button
await client.click(`${modalConfirm} .btn-primary`);
// All tabs should be closed
tabs = await client.elements(tab);
assert.equal(tabs.value.length, 0);
});
it("Close others context menu item should close items if they are not dirty", async function () {
app = await boot(this, {
prepareTestData: [{
name: "demo-app-tool1.json",
content: localTool
},
{
name: "demo-app-tool2.json",
content: localTool
}],
localRepository: {
credentials: [user],
activeCredentials: user,
openTabs: [{
id: "test:/demo-app-tool1.json",
type: "CommandLineTool",
label: "My Demo App",
isWritable: true
},
{
id: "test:/demo-app-tool2.json",
type: "CommandLineTool",
label: "My Demo App",
isWritable: true
}]
},
platformRepositories: {
[user.id]: {
projects: [project],
openProjects: [project.id]
}
}
});
const client = app.client;
const visualEditor = `ct-tool-visual-editor`;
const tab = `ct-workbox .tab`;
const activeTab = `ct-workbox .tab.active`;
const docker = `[data-test="docker-pull-input"]`;
const contextMenu = `ct-menu`;
const contextMenuItem = `ct-menu-item`;
await client.waitForVisible(visualEditor);
await client.waitForVisible(docker);
await client.setValue(docker, "someText");
// Wait until tab is dirty
await waitUntilTabBecomeDirty(client, activeTab);
// Right click on active tab (second one is active) to open the context menu
await client.rightClick(activeTab);
await client.waitForVisible(contextMenu);
// Click on Close others menu item
await client.click(`${contextMenuItem}:nth-of-type(1)`);
const tabs = await client.elements(tab);
assert.equal(tabs.value.length, 1, "One tab should be open.");
});
it("Close others tab menu item should show modal if there are dirty tabs", async function () {
app = await boot(this, {
prepareTestData: [{
name: "demo-app-tool1.json",
content: localTool
},
{
name: "demo-app-tool2.json",
content: localTool
}],
localRepository: {
credentials: [user],
activeCredentials: user,
openTabs: [{
id: "test:/demo-app-tool1.json",
type: "CommandLineTool",
label: "My Demo App",
isWritable: true
},
{
id: "test:/demo-app-tool2.json",
type: "CommandLineTool",
label: "My Demo App",
isWritable: true
}]
},
platformRepositories: {
[user.id]: {
projects: [project],
openProjects: [project.id]
}
}
});
const client = app.client;
const visualEditor = `ct-tool-visual-editor`;
const tab = `ct-workbox .tab`;
const activeTab = `ct-workbox .tab.active`;
const docker = `[data-test="docker-pull-input"]`;
const contextMenu = `ct-menu`;
const contextMenuItem = `ct-menu-item`;
const modalConfirm = `ct-modal-confirm`;
await client.waitForVisible(visualEditor);
await client.waitForVisible(docker);
await client.setValue(docker, "someText");
await waitUntilTabBecomeDirty(client, activeTab);
// Click on first tab to activate it
await client.click(`${tab}:nth-of-type(1)`);
// Right click to open context menu
await client.rightClick(activeTab);
await client.waitForVisible(contextMenu);
// Click on Close Others menu item
await client.click(`${contextMenuItem}:nth-of-type(1)`);
// Modal should appear
await client.waitForVisible(modalConfirm);
// Click on cancel button
await client.click(`${modalConfirm} .btn-secondary`);
let tabs = await client.elements(tab);
assert.equal(tabs.value.length, 2, "Both tabs should be open");
// Right click on active tab (first one is active) to open context menu
await client.rightClick(activeTab);
// Click on Close Others menu item
await client.click(`${contextMenuItem}:nth-of-type(1)`);
// Modal should appear
await client.waitForVisible(modalConfirm);
// Click on Close Others button
await client.click(`${modalConfirm} .btn-primary`);
tabs = await client.elements(tab);
assert.equal(tabs.value.length, 1, "One tab should be open");
});
it("Close all tabs context menu item should close all tabs if there is no dirty ones", async function () {
app = await boot(this, {
prepareTestData: [{
name: "demo-app-tool1.json",
content: localTool
},
{
name: "demo-app-tool2.json",
content: localTool
}],
localRepository: {
credentials: [user],
activeCredentials: user,
openTabs: [{
id: "test:/demo-app-tool1.json",
type: "CommandLineTool",
label: "My Demo App",
isWritable: true
},
{
id: "test:/demo-app-tool2.json",
type: "CommandLineTool",
label: "My Demo App",
isWritable: true
}]
},
platformRepositories: {
[user.id]: {
projects: [project],
openProjects: [project.id]
}
}
});
const client = app.client;
const visualEditor = `ct-tool-visual-editor`;
const tab = `ct-workbox .tab`;
const activeTab = `ct-workbox .tab.active`;
const contextMenu = `ct-menu`;
const contextMenuItem = `ct-menu-item`;
await client.waitForVisible(visualEditor);
await client.rightClick(activeTab);
await client.waitForVisible(contextMenu);
// Click on Close All context menu item
await client.click(`${contextMenuItem}:nth-of-type(2)`);
const tabs = await client.elements(tab);
assert.equal(tabs.value.length, 0, "There should be no open tabs");
});
});
describe("actions in FileEditor should make tab dirty", async () => {
it("modifing content should make tab dirty", async function () {
app = await boot(this, {
prepareTestData: [{
name: "demo-file.json",
content: localFile
}],
localRepository: {
credentials: [user],
activeCredentials: user,
openTabs: [{
id: "test:/demo-file.json",
type: "Code",
label: "My Demo App",
isWritable: true
}]
},
platformRepositories: {
[user.id]: {
projects: [project],
openProjects: [project.id]
}
}
});
const client = app.client;
const tab = `ct-workbox .tab`;
const fileEditor = `ct-file-editor`;
const modal = `ct-modal-closing-dirty-apps`;
const aceEditorContent = `.ace_content`;
await client.waitForVisible(fileEditor);
await client.waitForVisible(aceEditorContent);
// Modify some text in code editor
await client.click(aceEditorContent);
client.keys("maxi");
// Wait until tab is dirty
await waitUntilTabBecomeDirty(client, tab);
// Click to close the tab, Dirty Apps Modal should appear
await client.click(`.tab .close-icon`);
await client.waitForVisible(modal);
});
});
describe("actions in CommandLineTool should make tab dirty", async () => {
it("Changing Code editor content should make tab dirty", async function () {
app = await boot(this, {
prepareTestData: [{
name: "demo-app-tool.json",
content: localTool
}],
localRepository: {
credentials: [user],
activeCredentials: user,
openTabs: [{
id: "test:/demo-app-tool.json",
type: "CommandLineTool",
label: "My Demo App",
isWritable: true
}]
},
platformRepositories: {
[user.id]: {
projects: [project],
openProjects: [project.id]
}
}
});
const client = app.client;
const visualEditor = `ct-tool-visual-editor`;
const tab = `ct-workbox .tab`;
const codeTab = `[data-test="code-tab"]`;
const codeTabContent = `ct-code-editor`;
const aceEditorContent = `.ace_content`;
await client.waitForVisible(visualEditor);
// Click on Code to activate code editor
await client.click(codeTab);
await client.waitForVisible(codeTabContent);
// Tab should not be dirty
await waitUntilTabBecomeDirty(client, tab, false);
// Add some text in code editor
await client.click(aceEditorContent);
client.keys("Some random text");
// Tab should become dirty
await waitUntilTabBecomeDirty(client, tab);
});
it("Changing App info content should make tab dirty", async function () {
app = await boot(this, {
prepareTestData: [{
name: "demo-app.json",
content: localTool
}],
localRepository: {
credentials: [user],
activeCredentials: user,
openTabs: [{
id: "test:/demo-app.json",
type: "CommandLineTool",
label: "My Demo App",
isWritable: true
}]
},
platformRepositories: {
[user.id]: {
projects: [project],
openProjects: [project.id]
}
}
});
const client = app.client;
const visualEditor = `ct-tool-visual-editor`;
const tab = `ct-workbox .tab`;
const infoTab = `[data-test="info-tab"]`;
const infoTabSection = `ct-app-info`;
const inlineEditor = `ct-inline-editor`;
await client.waitForVisible(visualEditor);
// Click on App info to activate app info page
await client.click(infoTab);
await client.waitForVisible(infoTabSection);
// Click on first inline editor area
await client.click(inlineEditor);
// Change some text
await client.setValue(`${inlineEditor} input`, "sometext");
// Save changes
await client.click(`${inlineEditor} .btn-primary`);
// Tab should be dirty
await waitUntilTabBecomeDirty(client, tab);
});
it("modal should prevent changing revisions if tab is dirty", async function () {
app = await boot(this, {
localRepository: {
credentials: [user],
activeCredentials: user,
openTabs: []
},
platformRepositories: {
[user.id]: {
projects: [project],
openProjects: [project.id],
openTabs: [{
id: "marijanlekic89/div-nesto-input/draft2",
type: "CommandLineTool",
label: "My Demo App",
isWritable: true
}]
}
},
overrideModules: [
{
module: "./sbg-api-client/sbg-client",
override: {
SBGClient: mockSBGClient({
getApp: proxerialize((appContent) => {
return () => {
return Promise.resolve({raw: JSON.parse(appContent)});
};
}, platformTool)
}),
}
}
]
});
const client = app.client;
const visualEditor = `ct-tool-visual-editor`;
const tab = `ct-workbox .tab`;
const docker = `[data-test="docker-pull-input"]`;
const revisionBtn = `[data-test="revision-button"]`;
const revisionComponent = `ct-revision-list`;
const closingDirtyAppsModal = `ct-modal-closing-dirty-apps`;
await client.waitForVisible(visualEditor);
await client.waitForVisible(docker);
await client.setValue(docker, "someText");
// Tab should be dirty
await waitUntilTabBecomeDirty(client, tab);
// Click on revision button
await client.click(revisionBtn);
// Revision component should appear
await client.waitForVisible(revisionComponent);
// Click on revision entry
await client.click(`${revisionComponent} .revision-entry:nth-of-type(2)`);
// Modal should prevent changing revision
await client.waitForVisible(closingDirtyAppsModal);
// Click on cancel button
await client.click(`${closingDirtyAppsModal} [data-test="dirty-app-modal-cancel-button"]`);
// Tab should be still dirty
await waitUntilTabBecomeDirty(client, tab);
// Click again to change the revision
await client.click(`${revisionComponent} .revision-entry:nth-of-type(2)`);
// Click on discard button
await client.click(`${closingDirtyAppsModal} [data-test="dirty-app-modal-discard-button"]`);
// Tab should not be dirty anymore
await waitUntilTabBecomeDirty(client, tab, false);
});
});
describe("actions in Workflow should make tab dirty", async () => {
it("Changing App info content should make tab dirty", async function () {
app = await boot(this, {
prepareTestData: [{
name: "demo-workflow.json",
content: localWorkflow
}],
localRepository: {
credentials: [user],
activeCredentials: user,
openTabs: [{
id: "test:/demo-workflow.json",
type: "Workflow",
label: "My Demo App",
isWritable: true
}]
},
platformRepositories: {
[user.id]: {
projects: [project],
openProjects: [project.id]
}
}
});
const client = app.client;
const visualEditor = `ct-workflow-graph-editor`;
const tab = `ct-workbox .tab`;
const infoTab = `[data-test="info-tab"]`;
const infoTabSection = `ct-app-info`;
const inlineEditor = `ct-inline-editor`;
await client.waitForVisible(visualEditor);
// Click on App info to activate app info page
await client.click(infoTab);
await client.waitForVisible(infoTabSection);
// Click on first inline editor area
await client.click(inlineEditor);
// Change some text
await client.setValue(`${inlineEditor} input`, "sometext");
// Save changes
await client.click(`${inlineEditor} .btn-primary`);
// Tab should be dirty
await waitUntilTabBecomeDirty(client, tab);
});
it("actions in visual editor should make tab dirty ", async function () {
app = await boot(this, {
prepareTestData: [{
name: "/demo-workflow.json",
content: localWorkflow
}],
localRepository: {
credentials: [user],
activeCredentials: user,
openTabs: [{
id: "test:/demo-workflow.json",
type: "Workflow",
label: "My Demo App",
isWritable: true
}]
},
platformRepositories: {
[user.id]: {
projects: [project],
openProjects: [project.id]
}
}
});
const client = app.client;
const visualEditor = `ct-workflow-graph-editor`;
const tab = `ct-workbox .tab`;
const arrange = `[data-test="workflow-graph-arrange-button"]`;
await client.waitForVisible(visualEditor);
// Click on arrange button
await client.waitForVisible(arrange);
await client.click(arrange);
// Tab should be dirty
await waitUntilTabBecomeDirty(client, tab);
});
it("Changing Code editor content should make tab dirty", async function () {
app = await boot(this, {
prepareTestData: [{
name: "demo-workflow.json",
content: localWorkflow
}],
localRepository: {
credentials: [user],
activeCredentials: user,
openTabs: [{
id: "test:/demo-workflow.json",
type: "Workflow",
label: "My Demo App",
isWritable: true
}]
},
platformRepositories: {
[user.id]: {
projects: [project],
openProjects: [project.id]
}
}
});
const client = app.client;
const visualEditor = `ct-workflow-graph-editor`;
const tab = `ct-workbox .tab`;
const codeTab = `[data-test="code-tab"]`;
const codeTabContent = `ct-code-editor`;
const aceEditorContent = `.ace_content`;
await client.waitForVisible(visualEditor);
// Click on Code to activate code editor
await client.click(codeTab);
await client.waitForVisible(codeTabContent);
// Tab should not be dirty
await waitUntilTabBecomeDirty(client, tab, false);
// Add some text in code editor
await client.click(aceEditorContent);
client.keys("Some random text");
// Tab should become dirty
await waitUntilTabBecomeDirty(client, tab);
});
it("modal should prevent changing revisions if tab is dirty", async function () {
app = await boot(this, {
localRepository: {
credentials: [user],
activeCredentials: user,
openTabs: []
},
platformRepositories: {
[user.id]: {
projects: [project],
openProjects: [project.id],
openTabs: [{
id: "marijanlekic89/div-nesto-input/draft2",
type: "Workflow",
label: "My Demo App",
isWritable: true
}]
}
},
overrideModules: [
{
module: "./sbg-api-client/sbg-client",
override: {
SBGClient: mockSBGClient({
getApp: proxerialize((appContent) => {
return () => {
return Promise.resolve({raw: JSON.parse(appContent)});
};
}, platformWorkflow)
}),
}
}
]
});
const client = app.client;
const visualEditor = `ct-workflow-graph-editor`;
const tab = `ct-workbox .tab`;
const arrange = `[data-test="workflow-graph-arrange-button"]`;
const revisionBtn = `[data-test="revision-button"]`;
const revisionComponent = `ct-revision-list`;
const closingDirtyAppsModal = `ct-modal-closing-dirty-apps`;
await client.waitForVisible(visualEditor, 5000);
await client.waitForVisible(arrange, 5000);
await client.click(arrange);
// Tab should be dirty
await waitUntilTabBecomeDirty(client, tab);
// Click on revision button
await client.click(revisionBtn);
// Revision component should appear
await client.waitForVisible(revisionComponent, 5000);
// Click on revision entry
await client.click(`${revisionComponent} .revision-entry:nth-of-type(2)`);
// Modal should prevent changing revision
await client.waitForVisible(closingDirtyAppsModal, 5000);
// Click on cancel button
await client.click(`${closingDirtyAppsModal} [data-test="dirty-app-modal-cancel-button"]`);
// Tab should be still dirty
await waitUntilTabBecomeDirty(client, tab);
// Click again to change the revision
await client.click(`${revisionComponent} .revision-entry:nth-of-type(2)`);
// Click on discard button
await client.click(`${closingDirtyAppsModal} [data-test="dirty-app-modal-discard-button"]`);
// Tab should not be dirty anymore
await waitUntilTabBecomeDirty(client, tab, false);
});
});
});
async function waitUntilTabBecomeDirty(client, tab, dirty = true) {
return await client.waitUntil(async () => {
const has = await hasClass(client, tab);
return dirty ? has : !has;
}, 5000, `Tab should${!dirty ? " not " : ""}be dirty`);
}
async function hasClass(client, element) {
const elementClass = await client.getAttribute(element, "class").then((r) => r);
return elementClass.split(" ").includes("isDirty");
} | the_stack |
import * as M from 'fp-ts/lib/Monoid'
import * as T from 'fp-ts/lib/Traced'
import { identity, Endomorphism, flow } from 'fp-ts/lib/function'
// -------------------------------------------------------------------------------------
// models
// -------------------------------------------------------------------------------------
/**
* @category models
* @since 0.0.1
*/
export interface ExpressionBuilder extends T.Traced<Expression, Expression> {}
/**
* @category models
* @since 0.0.1
*/
export interface Expression {
/**
* The expression pattern prefix.
*/
readonly prefix: string
/**
* The expression pattern.
*/
readonly pattern: string
/**
* The expression pattern suffix.
*/
readonly suffix: string
/**
* The expression source.
*/
readonly source: string
/**
* The expression flags.
*/
readonly flags: Flags
}
/**
* @category model
* @since 0.0.1
*/
export interface Flags {
/**
* Sets the global search flag (`g`) which indicates that the expression should be
* tested against all possible matches in the input.
*/
readonly allowMultiple: boolean
/**
* Sets the case-insensitive search flag (`i`) which indicates that the expression
* should not distinguish between uppercase and lowercase characters in the input.
*/
readonly caseInsensitive: boolean
/**
* Sets the multi-line search flag (`m`) which indicates that the expression should
* treat a multiline input as multiple lines.
*/
readonly lineByLine: boolean
/**
* Sets the dotAll flag (`s`) which indicates that the expression should allow the
* dot special character (`.`) to additionally match line terminator characters in
* the input.
*/
readonly singleLine: boolean
/**
* Sets the sticky flag (`s`) which indicates that the expression should match only
* beginning at the index indicated by the `lastIndex` property of the expression.
*/
readonly sticky: boolean
/**
* Sets the unicode flag (`u`) which enables various Unicode-related features within
* the expression.
*/
readonly unicode: boolean
}
// -------------------------------------------------------------------------------------
// destructors
// -------------------------------------------------------------------------------------
const toFlags: (flags: Flags) => string = (flags) => {
let s = ''
s += flags.allowMultiple ? 'g' : ''
s += flags.caseInsensitive ? 'i' : ''
s += flags.lineByLine ? 'm' : ''
s += flags.singleLine ? 's' : ''
s += flags.unicode ? 'u' : ''
s += flags.sticky ? 'y' : ''
return s
}
/**
* @category destructors
* @since 0.0.1
*/
export const toRegex: (builder: ExpressionBuilder) => RegExp = (builder) => {
const expression = builder(monoidExpression.empty)
const flags = toFlags(expression.flags)
return new RegExp(expression.pattern, flags)
}
/**
* @category destructors
* @since 0.0.1
*/
export const toRegexString: (builder: ExpressionBuilder) => string = (builder) => {
return `${toRegex(builder)}`
}
// -------------------------------------------------------------------------------------
// pipeables
// -------------------------------------------------------------------------------------
/**
* @category pipeables
* @since 0.0.1
*/
export const withMultiple: (flag: boolean) => (wa: ExpressionBuilder) => Expression = (flag) => (wa) =>
wa({ ...monoidExpression.empty, flags: { ...monoidFlags.empty, allowMultiple: flag } })
/**
* @category pipeables
* @since 0.0.1
*/
export const withCaseInsensitive: (flag: boolean) => (wa: ExpressionBuilder) => Expression = (flag) => (wa) =>
wa({ ...monoidExpression.empty, flags: { ...monoidFlags.empty, caseInsensitive: flag } })
/**
* @category pipeables
* @since 0.0.1
*/
export const withLineByLine: (flag: boolean) => (wa: ExpressionBuilder) => Expression = (flag) => (wa) =>
wa({ ...monoidExpression.empty, flags: { ...monoidFlags.empty, lineByLine: flag } })
/**
* @category pipeables
* @since 0.0.1
*/
export const withSingleLine: (flag: boolean) => (wa: ExpressionBuilder) => Expression = (flag) => (wa) =>
wa({ ...monoidExpression.empty, flags: { ...monoidFlags.empty, singleLine: flag } })
/**
* @category pipeables
* @since 0.0.1
*/
export const withSticky: (flag: boolean) => (wa: ExpressionBuilder) => Expression = (flag) => (wa) =>
wa({ ...monoidExpression.empty, flags: { ...monoidFlags.empty, sticky: flag } })
/**
* @category pipeables
* @since 0.0.1
*/
export const withUnicode: (flag: boolean) => (wa: ExpressionBuilder) => Expression = (flag) => (wa) =>
wa({ ...monoidExpression.empty, flags: { ...monoidFlags.empty, unicode: flag } })
// -------------------------------------------------------------------------------------
// combinators
// -------------------------------------------------------------------------------------
const add: (value: string) => Endomorphism<ExpressionBuilder> = (value) =>
T.map((e) => ({
...e,
source: M.fold(M.monoidString)([e.source, value]),
pattern: M.fold(M.monoidString)([e.prefix, e.source, value, e.suffix])
}))
const prefix: (value: string) => Endomorphism<ExpressionBuilder> = (value) =>
T.map((e) => ({
...e,
prefix: M.fold(M.monoidString)([e.prefix, value])
}))
const suffix: (value: string) => Endomorphism<ExpressionBuilder> = (value) =>
T.map((e) => ({
...e,
suffix: M.fold(M.monoidString)([value, e.suffix])
}))
/**
* @category combinators
* @since 0.0.1
*/
export const allowMultiple: Endomorphism<ExpressionBuilder> = (wa) => C.extend(wa, withMultiple(true))
/**
* @category combinators
* @since 0.0.1
*/
export const caseInsensitive: Endomorphism<ExpressionBuilder> = (wa) => C.extend(wa, withCaseInsensitive(true))
/**
* @category combinators
* @since 0.0.1
*/
export const lineByLine: Endomorphism<ExpressionBuilder> = (wa) => C.extend(wa, withLineByLine(true))
/**
* @category combinators
* @since 0.0.1
*/
export const singleLine: Endomorphism<ExpressionBuilder> = (wa) => C.extend(wa, withSingleLine(true))
/**
* @category combinators
* @since 0.0.1
*/
export const sticky: Endomorphism<ExpressionBuilder> = (wa) => C.extend(wa, withSticky(true))
/**
* @category combinators
* @since 0.0.1
*/
export const unicode: Endomorphism<ExpressionBuilder> = (wa) => C.extend(wa, withUnicode(true))
/**
* @category combinators
* @since 0.0.1
*/
export const compile: ExpressionBuilder = identity
/**
* @category combinators
* @since 0.0.1
*/
export const startOfInput: Endomorphism<ExpressionBuilder> = add('^')
/**
* @category combinators
* @since 0.0.1
*/
export const endOfInput: Endomorphism<ExpressionBuilder> = add('$')
/**
* @category combinators
* @since 0.0.1
*/
export const string: (value: string) => Endomorphism<ExpressionBuilder> = (value) => add(`(?:${sanitize(value)})`)
/**
* @category combinators
* @since 0.0.1
*/
export const maybe: (value: string) => Endomorphism<ExpressionBuilder> = (value) => add(`(?:${sanitize(value)})?`)
/**
* @deprecated
* @category combinators
* @since 0.0.1
*/
export const or: (value: string) => Endomorphism<ExpressionBuilder> = (value) =>
flow(prefix(`(?:`), suffix(`)`), add(`)|(?:`), string(value))
/**
* @category combinators
* @since 0.0.2
*/
export const orExpression: Endomorphism<ExpressionBuilder> = add(`|`)
/**
* @category combinators
* @since 0.0.1
*/
export const anything: Endomorphism<ExpressionBuilder> = add(`(?:.*)`)
/**
* @category combinators
* @since 0.0.1
*/
export const anythingBut: (value: string) => Endomorphism<ExpressionBuilder> = (value) =>
add(`(?:[^${sanitize(value)}]*)`)
/**
* @category combinators
* @since 0.0.1
*/
export const something: Endomorphism<ExpressionBuilder> = add(`(?:.+)`)
/**
* @category combinators
* @since 0.0.1
*/
export const somethingBut: (value: string) => Endomorphism<ExpressionBuilder> = (value) =>
add(`(?:[^${sanitize(value)}]+)`)
/**
* @category combinators
* @since 0.0.1
*/
export const anyOf: (value: string) => Endomorphism<ExpressionBuilder> = (value) => add(`[${sanitize(value)}]`)
/**
* @category combinators
* @since 0.0.1
*/
export const not: (value: string) => Endomorphism<ExpressionBuilder> = (value) => add(`(?!${sanitize(value)})`)
/**
* @category combinators
* @since 0.0.1
*/
export const range: (from: string, to: string) => Endomorphism<ExpressionBuilder> = (from, to) =>
add(`[${sanitize(from)}-${sanitize(to)}]`)
/**
* @category combinators
* @since 0.0.1
*/
export const lineBreak: Endomorphism<ExpressionBuilder> = add(`(?:\\r\\n|\\r|\\n)`)
/**
* @category combinators
* @since 0.0.1
*/
export const tab: Endomorphism<ExpressionBuilder> = add(`\\t`)
/**
* @category combinators
* @since 0.0.1
*/
export const word: Endomorphism<ExpressionBuilder> = add(`\\w+`)
/**
* @category combinators
* @since 0.0.1
*/
export const digit: Endomorphism<ExpressionBuilder> = add(`\\d`)
/**
* @category combinators
* @since 0.0.1
*/
export const whitespace: Endomorphism<ExpressionBuilder> = add(`\\s`)
/**
* @category combinators
* @since 0.0.1
*/
export const zeroOrMore: Endomorphism<ExpressionBuilder> = add(`*`)
/**
* @category combinators
* @since 0.0.1
*/
export const zeroOrMoreLazy: Endomorphism<ExpressionBuilder> = add(`*?`)
/**
* @category combinators
* @since 0.0.1
*/
export const oneOrMore: Endomorphism<ExpressionBuilder> = add(`+`)
/**
* @category combinators
* @since 0.0.1
*/
export const oneOrMoreLazy: Endomorphism<ExpressionBuilder> = add(`+?`)
/**
* @category combinators
* @since 0.0.1
*/
export const exactly: (amount: number) => Endomorphism<ExpressionBuilder> = (amount) => add(`{${amount}}`)
/**
* @category combinators
* @since 0.0.1
*/
export const atLeast: (min: number) => Endomorphism<ExpressionBuilder> = (min) => add(`{${min},}`)
/**
* @category combinators
* @since 0.0.1
*/
export const between: (min: number, max: number) => Endomorphism<ExpressionBuilder> = (min, max) =>
add(`{${min},${max}}`)
/**
* @category combinators
* @since 0.0.1
*/
export const betweenLazy: (min: number, max: number) => Endomorphism<ExpressionBuilder> = (min, max) =>
add(`{${min},${max}}?`)
/**
* @category combinators
* @since 0.0.1
*/
export const beginCapture: Endomorphism<ExpressionBuilder> = add(`(`)
/**
* @category combinators
* @since 0.0.1
*/
export const endCapture: Endomorphism<ExpressionBuilder> = add(`)`)
// -------------------------------------------------------------------------------------
// instances
// -------------------------------------------------------------------------------------
/**
* @category instances
* @since 0.0.1
*/
export const monoidFlags: M.Monoid<Flags> = M.getStructMonoid({
allowMultiple: M.monoidAny,
caseInsensitive: M.monoidAny,
lineByLine: M.monoidAny,
singleLine: M.monoidAny,
sticky: M.monoidAny,
unicode: M.monoidAny
})
/**
* @category instances
* @since 0.0.1
*/
export const monoidExpression: M.Monoid<Expression> = M.getStructMonoid({
prefix: M.monoidString,
pattern: M.monoidString,
suffix: M.monoidString,
source: M.monoidString,
flags: monoidFlags
})
const C = T.getComonad(monoidExpression)
// -------------------------------------------------------------------------------------
// utils
// -------------------------------------------------------------------------------------
// Regular expression to match meta characters
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
const toEscape = /([\].|*?+(){}^$\\:=[])/g
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastMatch
const lastMatch = '$&'
// Escape meta characters
const sanitize: (value: string) => string = (value) => value.replace(toEscape, `\\${lastMatch}`) | the_stack |
import {
parse,
readZip,
ensureDir,
move,
walk,
semver,
} from "./deps.ts";
const baseExecutableFileName = "worker";
const bundleFileName = "worker.bundle.js";
const commonDenoOptions = ["--allow-env", "--allow-net", "--allow-read"];
const additionalDenoOptions:string[] = [];
const parsedArgs = parse(Deno.args);
const bundleStyles = ["executable", "jsbundle", "none"];
const STYLE_EXECUTABLE = 0;
const STYLE_JSBUNDLE = 1;
const STYLE_NONE = 2;
if (parsedArgs._[0] === "help") {
printHelp();
Deno.exit();
}
if (parsedArgs._.length >= 1 && parsedArgs._[0] === "init") {
const templateDownloadBranch: string | undefined = parsedArgs?._[1]?.toString();
await initializeFromTemplate(templateDownloadBranch);
} else if (
parsedArgs._.length === 1 && parsedArgs._[0] === "start" ||
parsedArgs._.length === 2 && parsedArgs._.join(' ') === "host start"
) {
await generateFunctions();
await createJSBundle();
await runFunc("start");
} else if (parsedArgs._[0] === "publish" && parsedArgs._.length === 2) {
const bundleStyle = parsedArgs["bundle-style"] // use specified bundle style
|| (semver.satisfies(Deno.version.deno, ">=1.6.0") // default style depends on Deno runtime version
? bundleStyles[STYLE_EXECUTABLE] // for v1.6.0 or later
: bundleStyles[STYLE_JSBUNDLE] // for others
);
if (!bundleStyles.includes(bundleStyle)) {
console.error(`The value \`${parsedArgs["bundle-style"]}\` of \`--bundle-style\` option is not acceptable.`)
Deno.exit(1);
} else if (semver.satisfies(Deno.version.deno, "<1.6.0") && bundleStyle === bundleStyles[STYLE_EXECUTABLE]) {
console.error(`Deno version v${Deno.version.deno} doesn't support \`${bundleStyles[STYLE_EXECUTABLE]}\` for bundle style.`);
Deno.exit(1);
}
// adding options which names start with `--allow-` and are not included in `commonDenoOptions`.
additionalDenoOptions.splice(0, 0,
...Object.keys(parsedArgs).map(p => `--${p}`)
.filter(key => key.startsWith('--allow-') && !commonDenoOptions.includes(key))
);
const appName = parsedArgs._[1].toString();
const slotName = parsedArgs["slot"]?.toString();
const platform = await getAppPlatform(appName, slotName);
if (!["windows", "linux"].includes(platform)) {
console.error(`The value \`${platform}\` for the function app \`${appName + (slotName ? `/${slotName}` : "")}\` is not valid.`);
Deno.exit(1);
}
await updateHostJson(platform, bundleStyle);
await generateFunctions();
if (bundleStyle === bundleStyles[STYLE_EXECUTABLE]) {
await generateExecutable(platform);
} else {
await downloadBinary(platform);
if (bundleStyle === bundleStyles[STYLE_JSBUNDLE]) await createJSBundle();
}
await publishApp(appName, slotName);
} else {
printHelp();
}
async function fileExists(path: string) {
try {
const f = await Deno.lstat(path);
return f.isFile;
} catch {
return false;
}
}
async function directoryExists(path: string) {
try {
const f = await Deno.lstat(path);
return f.isDirectory;
} catch {
return false;
}
}
async function listFiles(dir: string) {
const files: string[] = [];
for await (const dirEntry of Deno.readDir(dir)) {
files.push(`${dir}/${dirEntry.name}`);
if (dirEntry.isDirectory) {
(await listFiles(`${dir}/${dirEntry.name}`)).forEach((s) => {
files.push(s);
});
}
}
return files;
}
async function generateExecutable(platformArg?: string) {
try {
await Deno.remove('./bin', { recursive: true });
await Deno.remove(`./${bundleFileName}`);
} catch { }
const platform = platformArg || Deno.build.os;
await Deno.mkdir(`./bin/${platform}`, { recursive: true });
const cmd = [
"deno",
"compile",
"--unstable",
...(semver.satisfies(Deno.version.deno, ">=1.7.1 <1.10.0") ? ["--lite"] : []), // `--lite` option is implemented only between v1.7.1 and v1.9.x
...commonDenoOptions.concat(additionalDenoOptions),
"--output",
`./bin/${platform}/${baseExecutableFileName}`,
...(['windows', 'linux'].includes(platform)
? ['--target', platform === 'windows' ? 'x86_64-pc-windows-msvc' : 'x86_64-unknown-linux-gnu']
: []
),
"worker.ts"
];
console.info(`Running command: ${cmd.join(" ")}`);
const generateProcess = Deno.run({ cmd });
await generateProcess.status();
}
async function createJSBundle() {
const cmd = ["deno", "bundle", "--unstable", "worker.ts", bundleFileName];
console.info(`Running command: ${cmd.join(" ")}`);
const generateProcess = Deno.run({ cmd });
await generateProcess.status();
}
async function getAppPlatform(appName: string, slotName?: string): Promise<string> {
console.info(`Checking platform type of : ${appName + (slotName ? `/${slotName}` : "")} ...`);
const azResourceCmd = [
"az",
"resource",
"list",
"--resource-type",
`Microsoft.web/sites${slotName ? "/slots" : ""}`,
"-o",
"json",
];
const azResourceProcess = await runWithRetry(
{ cmd: azResourceCmd, stdout: "piped" },
"az.cmd",
);
const azResourceOutput = await azResourceProcess.output();
const resources = JSON.parse(
new TextDecoder().decode(azResourceOutput),
);
azResourceProcess.close();
try {
const resource = resources.find((resource: any) =>
resource.name === (appName + (slotName ? `/${slotName}` : ""))
);
const azFunctionAppSettingsCmd = [
"az",
"functionapp",
"config",
"appsettings",
"set",
"--ids",
resource.id,
...(slotName
? ["--slot", slotName]
: []
),
"--settings",
"FUNCTIONS_WORKER_RUNTIME=custom",
"-o",
"json",
];
const azFunctionAppSettingsProcess = await runWithRetry(
{ cmd: azFunctionAppSettingsCmd, stdout: "null" },
"az.cmd",
);
await azFunctionAppSettingsProcess.status();
azFunctionAppSettingsProcess.close();
return (resource.kind as string).includes("linux") ? "linux" : "windows";
} catch {
throw new Error(`Not found: ${appName + (slotName ? `/${slotName}` : "")}`);
}
}
async function updateHostJson(platform: string, bundleStyle: string) {
// update `defaultExecutablePath` and `arguments` in host.json
const hostJsonPath = "./host.json";
if (!(await fileExists(hostJsonPath))) {
throw new Error(`\`${hostJsonPath}\` not found`);
}
const hostJSON: any = await readJson(hostJsonPath);
if (!hostJSON.customHandler) hostJSON.customHandler = {};
hostJSON.customHandler.description = {
defaultExecutablePath: `bin/${platform}/${bundleStyle === bundleStyles[STYLE_EXECUTABLE] ? baseExecutableFileName : "deno"}${platform === "windows" ? ".exe" : ""}`,
arguments: bundleStyle === bundleStyles[STYLE_EXECUTABLE]
? []
: [
"run",
...commonDenoOptions.concat(additionalDenoOptions),
bundleStyle === bundleStyles[STYLE_JSBUNDLE] ? bundleFileName : "worker.ts"
]
};
await writeJson(hostJsonPath, hostJSON); // returns a promise
}
function writeJson(path: string, data: object): void {
Deno.writeTextFileSync(path, JSON.stringify(data, null, 2));
}
function readJson(path: string): string {
const decoder = new TextDecoder("utf-8");
return JSON.parse(decoder.decode(Deno.readFileSync(path)));
}
async function downloadBinary(platform: string) {
const binDir = `./bin/${platform}`;
const binPath = `${binDir}/deno${platform === "windows" ? ".exe" : ""}`;
const archive: any = {
"windows": "pc-windows-msvc",
"linux": "unknown-linux-gnu",
};
// remove unnecessary files/dirs in "./bin"
if (await directoryExists("./bin")) {
const entries = (await listFiles("./bin"))
.filter((entry) => !binPath.startsWith(entry))
.sort((str1, str2) => str1.length < str2.length ? 1 : -1);
for (const entry of entries) {
await Deno.remove(entry);
}
}
try {
await Deno.remove(`./${bundleFileName}`);
} catch { }
const binZipPath = `${binDir}/deno.zip`;
if (!(await fileExists(binPath))) {
const downloadUrl =
`https://github.com/denoland/deno/releases/download/v${Deno.version.deno}/deno-x86_64-${archive[platform]
}.zip`;
console.info(`Downloading deno binary from: ${downloadUrl} ...`);
// download deno binary (that gets deployed to Azure)
const response = await fetch(downloadUrl);
await ensureDir(binDir);
const zipFile = await Deno.create(binZipPath);
const download = new Deno.Buffer(await response.arrayBuffer());
await Deno.copy(download, zipFile);
Deno.close(zipFile.rid);
const zip = await readZip(binZipPath);
await zip.unzip(binDir);
if (Deno.build.os !== "windows") {
await Deno.chmod(binPath, 0o755);
}
await Deno.remove(binZipPath);
console.info(`Downloaded deno binary at: ${await Deno.realPath(binPath)}`);
}
}
async function initializeFromTemplate(downloadBranch: string = "main") {
const templateZipPath = `./template.zip`;
const templateDownloadPath = `https://github.com/anthonychu/azure-functions-deno-template/archive/${downloadBranch}.zip`;
let isEmpty = true;
for await (const dirEntry of Deno.readDir(".")) {
isEmpty = false;
}
if (isEmpty) {
console.info("Initializing project...");
console.info(`Downloading from ${templateDownloadPath}...`);
// download deno binary (that gets deployed to Azure)
const response = await fetch(templateDownloadPath);
const zipFile = await Deno.create(templateZipPath);
const download = new Deno.Buffer(await response.arrayBuffer());
await Deno.copy(download, zipFile);
Deno.close(zipFile.rid);
const zip = await readZip(templateZipPath);
const subDirPath = `azure-functions-deno-template-${downloadBranch}`;
await zip.unzip(".");
await Deno.remove(templateZipPath);
for await (const entry of walk(".")) {
if (entry.path.startsWith(subDirPath) && entry.path !== subDirPath) {
const dest = entry.path.replace(subDirPath, ".");
console.info(dest);
if (entry.isDirectory) {
await Deno.mkdir(dest, { recursive: true });
} else {
await move(entry.path, dest);
}
}
}
await Deno.remove(subDirPath, { recursive: true });
} else {
console.error("Cannot initialize. Folder is not empty.");
}
}
async function generateFunctions() {
console.info("Generating functions...");
const generateProcess = Deno.run({
cmd: [
"deno",
"run",
...commonDenoOptions,
"--allow-write",
"--unstable",
"--no-check",
"worker.ts",
],
env: { "DENOFUNC_GENERATE": "1" },
});
const status = await generateProcess.status();
if (status.code || !status.success) Deno.exit(status.code);
}
async function runFunc(...args: string[]) {
let cmd = ["func", ...args];
const env = {
"logging__logLevel__Microsoft": "warning",
"logging__logLevel__Worker": "warning",
};
const proc = await runWithRetry({ cmd, env }, "func.cmd");
await proc.status();
proc.close();
}
async function runWithRetry(
runOptions: Deno.RunOptions,
backupCommand: string,
) {
try {
console.info(`Running command: ${runOptions.cmd.join(" ")}`);
return Deno.run(runOptions);
} catch (ex) {
if (Deno.build.os === "windows") {
console.info(
`Could not start ${runOptions.cmd[0]
} from path, searching for executable...`,
);
const whereCmd = ["where.exe", backupCommand];
const proc = Deno.run({
cmd: whereCmd,
stdout: "piped",
});
await proc.status();
const rawOutput = await proc.output();
const newPath = new TextDecoder().decode(rawOutput).split(/\r?\n/).find(
(p) => p.endsWith(backupCommand),
);
if (newPath) {
const newCmd = [...runOptions.cmd].map(e => e.toString());
newCmd[0] = newPath;
const newOptions = { ...runOptions };
newOptions.cmd = newCmd;
console.info(`Running command: ${newOptions.cmd.join(" ")}`);
return Deno.run(newOptions);
} else {
throw `Could not locate ${backupCommand}. Please ensure it is installed and in the path.`;
}
} else {
throw ex;
}
}
}
async function publishApp(appName: string, slotName?: string) {
const runFuncArgs = [
"azure",
"functionapp",
"publish",
appName
];
await runFunc(...(slotName ? runFuncArgs.concat(["--slot", slotName]) : runFuncArgs));
}
function printLogo() {
const logo = `
@@@@@@@@@@@,
@@@@@@@@@@@@@@@@@@@ %%%%%%
@@@@@@ @@@@@@@@@@ %%%%%%
@@@@@ @ @ *@@@@@ @ %%%%%% @
@@@ @@@@@ @@ %%%%%% @@
@@@@@ @@@@@ @@@ %%%%%%%%%%% @@@
@@@@@@@@@@@@@@@ @@@@ @@ %%%%%%%%%% @@
@@@@@@@@@@@@@@ @@@@ @@ %%%% @@
@@@@@@@@@@@@@@ @@@ @@ %%% @@
@@@@@@@@@@@@@ @ @@ %% @@
@@@@@@@@@@@ %%
@@@@@@@ %
`;
console.info(logo);
}
function printHelp() {
printLogo();
console.info("Deno for Azure Functions - CLI");
console.info(`
Commands:
denofunc --help
This screen
denofunc init
Initialize project in an empty folder
denofunc start
Generate functions artifacts and start Azure Functions Core Tools
denofunc publish <function_app_name> [options]
Publish to Azure
options:
--slot <slot_name> Specify name of the deployment slot
--bundle-style executable|jsbundle|none Select bundle style on deployment
executable: Bundle as one executable(default option for Deno v1.6.0 or later).
jsbundle: Bundle as one javascript worker & Deno runtime
none: No bundle
--allow-run Same as Deno's permission option
--allow-write Same as Deno's permission option
`);
} | the_stack |
import { mainAction } from '../../main/actions';
import { chatAction } from '../actions';
import { roomAction } from '../../room/actions';
import { ChatStore } from '../stores/chat.store';
import { chatInit } from '../model';
import { contactAction } from '../../contact/actions';
import { global, authPayload } from '../../../services/common';
import { Util } from '../../../services/util';
export const chatReducer = (state: ChatStore = chatInit, { type, payload }) => {
state.actionType = type;
switch (type) {
// 初始化state
case chatAction.init:
state = Util.deepCopyObj(chatInit);
break;
// 初始化会话列表
case chatAction.getConversationSuccess:
if (payload.storage) {
state.conversation = payload.conversation;
if (payload.messageList.length > 0) {
state.messageList = payload.messageList;
}
filterRecentMsg(state);
filterAtList(state);
state.isLoaded = true;
completionMessageList(state);
}
if (payload.shield) {
initGroupShield(state, payload.shield);
}
if (payload.noDisturb) {
state.noDisturb = payload.noDisturb;
initNoDisturb(state, payload.noDisturb);
}
if (state.friendList.length > 0) {
filterConversationMemoName(state);
}
conversationUnreadNum(state);
break;
// 获取好友列表
case chatAction.getFriendListSuccess:
if (payload && payload.type) {
compareFriendList(state, payload.friendList);
state.friendList = payload.friendList;
} else {
state.friendList = payload;
}
filterFriendList(state, payload);
if (state.conversation.length > 0) {
filterConversationMemoName(state);
}
break;
// 登陆后,离线消息同步消息列表
case chatAction.getAllMessageSuccess:
state.messageList = payload;
state.imageViewer = filterImageViewer(state);
break;
// 接收消息
case chatAction.receiveMessageSuccess:
addMessage(state, payload);
newMessageIsActive(state, payload);
conversationUnreadNum(state);
break;
// 发送单聊文本消息
case chatAction.sendSingleMessage:
// 发送群组文本消息
case chatAction.sendGroupMessage:
// 发送单聊图片消息
case chatAction.sendSinglePic:
// 发送群组图片消息
case chatAction.sendGroupPic:
// 发送单聊文件消息
case chatAction.sendSingleFile:
// 发送群组文件消息
case chatAction.sendGroupFile:
// 判断是否是重发消息
if (!payload.msgs.repeatSend) {
addMessage(state, payload);
}
const extras = payload.msgs.content.msg_body.extras;
if (extras && extras.businessCard) {
state.sendBusinessCardSuccess = 0;
}
break;
// 发送消息完成(包括所有类型的消息)
case chatAction.sendMsgComplete:
sendMsgComplete(state, payload);
if (payload.msgs) {
const bussinessExtras = payload.msgs.content.msg_body.extras;
if (bussinessExtras && bussinessExtras.businessCard && payload.success !== 2) {
state.sendBusinessCardSuccess = 0;
} else {
state.sendBusinessCardSuccess++;
}
}
break;
// 转发单聊文本消息
case chatAction.transmitSingleMessage:
// 转发单聊图片消息
case chatAction.transmitSinglePic:
// 转发单聊文件消息
case chatAction.transmitSingleFile:
// 转发群聊文本消息
case chatAction.transmitGroupMessage:
// 转发单聊图片消息
case chatAction.transmitGroupPic:
// 转发单聊文件消息
case chatAction.transmitGroupFile:
// 转发单聊位置
case chatAction.transmitSingleLocation:
// 转发群聊位置
case chatAction.transmitGroupLocation:
if (!payload.msgs.repeatSend) {
state.transmitSuccess = 0;
transmitMessage(state, payload);
state.newMessage = payload.msgs;
}
break;
// 转发消息完成
case chatAction.transmitMessageComplete:
sendMsgComplete(state, payload);
if (payload.success !== 2) {
state.transmitSuccess = 0;
} else {
state.transmitSuccess++;
}
break;
// 切换当前会话用户
case chatAction.changeActivePerson:
clearVoiceTimer(state);
state.activePerson = Util.deepCopyObj(payload.item);
state.defaultPanelIsShow = payload.defaultPanelIsShow;
emptyUnreadNum(state, payload.item);
state.unreadCount = {
key: state.activePerson.key,
name: state.activePerson.name,
type: state.activePerson.type
};
changeActivePerson(state);
conversationUnreadNum(state);
break;
// 选择联系人
case contactAction.selectContactItem:
// 选择搜索出来的本地用户
case mainAction.selectSearchUser:
state.defaultPanelIsShow = false;
clearVoiceTimer(state);
selectUserResult(state, payload, 'search');
changeActivePerson(state);
emptyUnreadNum(state, payload);
state.unreadCount = {
key: state.activePerson.key,
name: state.activePerson.name,
type: state.activePerson.type
};
conversationUnreadNum(state);
break;
// 删除本地会话列表
case chatAction.deleteConversationItem:
showGroupSetting(state, false);
deleteConversationItem(state, payload);
conversationUnreadNum(state);
break;
// 保存草稿
case chatAction.saveDraft:
if (state.messageList[payload[1].activeIndex]) {
state.messageList[payload[1].activeIndex].draft = payload[0];
}
for (let item of state.conversation) {
if (Number(payload[1].key) === Number(item.key)) {
item.draft = payload[0];
}
}
break;
// 搜索本地用户
case mainAction.searchUserSuccess:
state.searchUserResult = searchUser(state, payload.keywords);
if (payload.room) {
state.searchUserResult.result.roomArr.push(payload.room);
}
break;
// 消息转发的搜索用户
case chatAction.searchMessageTransmit:
state.messageTransmit.searchResult = searchUser(state, payload);
break;
// 成功查看别人的信息
case chatAction.watchOtherInfoSuccess:
payload.info.isFriend = filterFriend(state, payload.info);
filterSingleBlack(state, payload.info);
filterSingleNoDisturb(state, payload.info);
state.otherInfo.info = payload.info;
state.otherInfo.show = payload.show;
break;
// 隐藏别人的信息框
case chatAction.hideOtherInfo:
state.otherInfo = payload;
break;
// 获取群组信息
case chatAction.groupInfo:
initGroupInfo(state, payload);
break;
// 显示隐藏群组设置
case chatAction.groupSetting:
const msg = state.messageList[state.activePerson.activeIndex];
if (msg && !msg.groupSetting) {
state.messageList[state.activePerson.activeIndex] = Object.assign({}, msg,
{ groupSetting: {} });
}
if (msg && payload.loading &&
(!msg.groupSetting || (msg.groupSetting && !msg.groupSetting.groupInfo))) {
state.messageList[state.activePerson.activeIndex].groupSetting.loading = true;
}
showGroupSetting(state, payload.show);
break;
// 创建单聊/添加好友
case mainAction.createSingleChatSuccess:
/**
* info.showType
* 1 发起单聊-非好友-非会话人
* 2 发起单聊-好友
* 3 发起单聊-非好友-会话人
* 4 添加好友-非会话人
* 5 添加好友-会话人
* 6 查看资料-好友
* 7 查看资料-非好友-会话人
* 8 查看资料-非好友-非会话人
*/
payload.isFriend = filterFriend(state, payload);
filterSingleBlack(state, payload);
filterSingleNoDisturb(state, payload);
state.otherInfo.info = payload;
state.otherInfo.show = true;
break;
// 从验证消息列表中查看对方的资料
case contactAction.watchVerifyUserSuccess:
payload.isFriend = filterFriend(state, payload);
filterSingleBlack(state, payload);
filterSingleNoDisturb(state, payload);
state.otherInfo.info = payload;
state.otherInfo.show = true;
break;
// 创建群组成功
case mainAction.createGroupSuccess:
clearVoiceTimer(state);
state.activePerson = Util.deepCopyObj(payload);
state.defaultPanelIsShow = false;
selectUserResult(state, payload);
changeActivePerson(state);
state.groupList.push(payload);
break;
// 从用户的个人资料创建单聊联系人会话
case chatAction.createOtherChat:
showGroupSetting(state, false);
clearVoiceTimer(state);
if (payload.username) {
payload.name = payload.username;
}
if (payload.nickname) {
payload.nickName = payload.nickname;
}
state.defaultPanelIsShow = false;
filterFriend(state, payload);
selectUserResult(state, payload);
state.activePerson = Util.deepCopyObj(payload);
changeActivePerson(state);
emptyUnreadNum(state, payload);
state.unreadCount = {
key: state.activePerson.key,
name: state.activePerson.name,
type: state.activePerson.type
};
conversationUnreadNum(state);
break;
// 获取群组列表成功
case contactAction.getGroupListSuccess:
state.groupList = payload;
break;
// 退群成功
case mainAction.exitGroupSuccess:
const isActive = (payload.item.name === state.activePerson.name &&
payload.item.type === 3 && state.activePerson.type === 3) ||
(payload.item.type === 4 &&
Number(payload.item.key) === Number(state.activePerson.key));
if (isActive) {
showGroupSetting(state, false);
state.defaultPanelIsShow = true;
}
exitGroup(state, payload.item);
deleteConversationItem(state, payload);
conversationUnreadNum(state);
break;
// 加入黑名单成功
case mainAction.addBlackListSuccess:
state.otherInfo.info.black = true;
updateBlackMenu(state, payload.deleteItem.item);
break;
// 更新群描述
case chatAction.groupDescription:
state.groupDeacriptionShow = payload.show;
break;
// 显示个人信息
case mainAction.showSelfInfo:
if (payload.info) {
state.selfInfo.info = Object.assign({}, state.selfInfo.info, payload.info);
}
if (payload.avatar) {
state.selfInfo.info.avatarUrl = payload.avatar.url;
}
break;
// 获取用户信息头像url
case chatAction.getSingleAvatarUrl:
const msgs = state.messageList[state.activePerson.activeIndex].msgs;
for (let item of msgs) {
if (item.content.from_id !== global.user) {
item.content.avatarUrl = state.activePerson.avatarUrl;
}
}
break;
// 切换群屏蔽
case chatAction.changeGroupShieldSuccess:
changeGroupShield(state, payload);
break;
// 切换群组免打扰
case chatAction.changeGroupNoDisturbSuccess:
changeGroupNoDisturb(state, payload);
conversationUnreadNum(state);
break;
// 群聊事件
case chatAction.addGroupMembersEventSuccess:
groupMembersEvent(state, payload, '被添加进群聊了');
state.currentIsActive = currentIsActive(state, payload);
for (let user of payload.to_usernames) {
if (user.username === global.user) {
addToGroupList(state, payload);
break;
}
}
break;
// 更新群组成员事件
case chatAction.updateGroupMembersEvent:
updateGroupMembers(state, payload.eventData);
break;
// 删除群组成员
case chatAction.deleteGroupMembersEvent:
groupMembersEvent(state, payload, '被移出群聊了');
state.currentIsActive = currentIsActive(state, payload);
deleteGroupMembersEvent(state, payload);
for (let user of payload.to_usernames) {
if (user.username === global.user) {
exitGroup(state, payload);
break;
}
}
break;
// 退群事件
case chatAction.exitGroupEvent:
groupMembersEvent(state, payload, '退出群聊了');
state.currentIsActive = currentIsActive(state, payload);
deleteGroupMembersEvent(state, payload);
break;
// 更新群组信息成功事件
case chatAction.updateGroupInfoEventSuccess:
updateGroupInfoEventSuccess(state, payload);
break;
// 从localstorage获取已经播放的voice的列表
case chatAction.getVoiceStateSuccess:
state.voiceState = payload;
break;
// 显示视频模态框
case chatAction.playVideoShow:
state.playVideoShow = payload;
break;
// 创建群聊事件消息
case chatAction.createGroupSuccessEvent:
createGroupSuccessEvent(state, payload);
break;
// 消息撤回
case chatAction.msgRetractEvent:
msgRetract(state, payload);
break;
// 显示验证消息模态框
case chatAction.showVerifyModal:
state.verifyModal = payload;
break;
// 在黑名单列表中删除黑名单
case mainAction.delSingleBlackSuccess:
updateBlackMenu(state, payload);
break;
// 获取黑名单成功
case mainAction.blackMenuSuccess:
state.blackMenu = payload.menu;
break;
// 在个人资料中删除黑名单
case chatAction.deleteSingleBlackSuccess:
updateBlackMenu(state, payload);
state.otherInfo.info.black = false;
break;
// 添加单聊用户免打扰成功
case mainAction.addSingleNoDisturbSuccess:
state.otherInfo.info.noDisturb = true;
changeSingleNoDisturb(state, payload);
conversationUnreadNum(state);
break;
// 删除单聊用户免打扰成功
case chatAction.deleteSingleNoDisturbSuccess:
state.otherInfo.info.noDisturb = false;
changeSingleNoDisturb(state, payload);
conversationUnreadNum(state);
break;
// 好友资料中保存备注名及备注名同步
case chatAction.saveMemoNameSuccess:
saveMemoNameSuccess(state, payload);
break;
// 删除好友同步事件
case chatAction.deleteFriendSyncEvent:
deleteFriendSyncEvent(state, payload);
break;
// 添加好友同步事件
case chatAction.addFriendSyncEvent:
for (let user of payload.to_usernames) {
friendSyncEvent(state, user, true);
}
break;
// 删除好友
case mainAction.deleteFriendSuccess:
otherInfoDeleteFriend(state, payload);
break;
// 同意添加好友
case contactAction.agreeAddFriendSuccess:
addNewFriendToConversation(state, payload, 'agree');
break;
// 好友应答成功事件
case chatAction.friendReplyEventSuccess:
// 如果在好友应答时正好打开了该好友的资料
updateOtherInfo(state, payload);
addNewFriendToConversation(state, payload, 'reply');
break;
// 加载图片预览没有加载的图片url
case chatAction.loadViewerImageSuccess:
state.viewerImageUrl = payload;
break;
// 聊天文件模态框显示隐藏
case chatAction.msgFile:
state.msgFile.show = payload.show;
break;
// 聊天文件显示成功
case chatAction.msgFileSuccess:
if (payload.isFirst) {
state.messageList = payload.messageList;
filterMsgFile(state, payload.type);
}
filterMsgFileImageViewer(state, payload.type);
break;
// 聊天文件中的文件中的图片加载成功
case chatAction.fileImageLoad:
fileImageLoad(state, payload);
break;
// 置顶成功
case chatAction.conversationToTopSuccess:
conversationToTop(state, payload);
break;
// 显示未读列表
case chatAction.watchUnreadList:
state.unreadList = {
show: payload.show,
info: {
read: [],
unread: []
},
loading: true
};
break;
// 加载未读列表成功
case chatAction.watchUnreadListSuccess:
if (payload.info) {
filterUnreadListMemoName(state, payload);
state.unreadList.info.read = payload.info.read_list;
state.unreadList.info.unread = payload.info.unread_list;
}
state.unreadList.loading = payload.loading;
break;
// 已读消息回执事件
case chatAction.msgReceiptChangeEvent:
msgReceiptChangeEvent(state, payload);
break;
// 上报消息已读
case chatAction.addReceiptReportAction:
state.readObj = filterReceiptReport(state, payload);
break;
// 清空未读数的同步事件
case chatAction.emptyUnreadNumSyncEvent:
emptyUnreadNumSyncEvent(state, payload);
conversationUnreadNum(state);
break;
// 添加单聊免打扰同步事件
case chatAction.addSingleNoDisturbSyncEvent:
addSingleNoDisturbSyncEvent(state, payload);
conversationUnreadNum(state);
break;
// 删除单聊免打扰同步事件
case chatAction.deleteSingleNoDisturbSyncEvent:
deleteSingleNoDisturbSyncEvent(state, payload);
conversationUnreadNum(state);
break;
// 添加群组免打扰同步事件
case chatAction.addGroupNoDisturbSyncEvent:
addGroupNoDisturbSyncEvent(state, payload);
conversationUnreadNum(state);
break;
// 删除群组免打扰同步事件
case chatAction.deleteGroupNoDisturbSyncEvent:
deleteGroupNoDisturbSyncEvent(state, payload);
conversationUnreadNum(state);
break;
// 添加群组屏蔽同步事件
case chatAction.addGroupShieldSyncEvent:
addGroupShieldSyncEvent(state, payload);
break;
// 删除群组屏蔽同步事件
case chatAction.deleteGroupShieldSyncEvent:
deleteGroupShieldSyncEvent(state, payload);
break;
// 添加单聊黑名单同步事件
case chatAction.addSingleBlackSyncEvent:
singleBlackSyncEvent(state, payload, true);
break;
// 删除单聊黑名单同步事件
case chatAction.deleteSingleBlackSyncEvent:
singleBlackSyncEvent(state, payload, false);
break;
// 用户信息更新事件
case chatAction.userInfUpdateEventSuccess:
userInfUpdateEventSuccess(state, payload);
break;
// 创建群聊、多人会话、添加群成员搜索成功
case chatAction.createGroupSearchComplete:
state.createGroupSearch = searchSingleUser(state, payload);
break;
// 转发聊天室的消息
case roomAction.transmitAllMsg:
state.roomTransmitMsg = payload;
break;
// 收到正在输入的透传消息
case chatAction.receiveInputMessage:
state.isInput = payload;
break;
// 添加群成员禁言事件
case chatAction.addGroupMemberSilenceEvent:
addGroupMemberSilenceEvent(state, payload);
state.currentIsActive = currentIsActive(state, payload);
break;
// 移除群成员禁言事件
case chatAction.deleteGroupMemberSilenceEvent:
deleteGroupMemberSilenceEvent(state, payload);
state.currentIsActive = currentIsActive(state, payload);
break;
// 收到入群邀请事件
case chatAction.receiveGroupInvitationEventSuccess:
filterInvitationEventMeMoName(state, payload);
state.receiveGroupInvitationEventObj = payload;
break;
// 收到被拒绝入群事件
case chatAction.receiveGroupRefuseEventSuccess:
filterInvitationEventMeMoName(state, payload);
state.receiveGroupRefuseEventObj = payload;
break;
default:
}
return state;
};
// 登录时处理会话at提示
function filterAtList(state: ChatStore) {
if (state.messageList.length > 0) {
for (let conversation of state.conversation) {
let num = conversation.unreadNum;
if (num > 0) {
for (let messageList of state.messageList) {
let group = messageList.type === 4 && conversation.type === 4 &&
Number(messageList.key) === Number(conversation.key);
if (messageList.msgs && messageList.msgs.length > 0 && group) {
let length = messageList.msgs.length;
for (let i = length - 1; i >= length - 1 - num && i >= 0; i--) {
let atUser = messageHasAtList(messageList.msgs[i].content.at_list);
if (atUser !== '') {
conversation.atUser = atUser;
break;
}
}
break;
}
}
}
}
}
}
// 上报已读回执,防止漏报
function filterReceiptReport(state: ChatStore, payload) {
if (payload.msg_id.length === 0) {
return payload;
}
for (let messageList of state.messageList) {
const group = messageList.type === 4 && payload.type === 4 &&
Number(messageList.key) === Number(payload.gid);
const single = messageList.type === 3 && payload.type === 3 &&
messageList.name === payload.username;
if (group || single) {
for (let msgId of payload.msg_id) {
for (let message of messageList.msgs) {
if (message.msg_id === msgId) {
message.hasRead = true;
break;
}
}
}
for (let message of messageList.msgs) {
if (message.msg_id === payload.msg_id[0]) {
for (let i = messageList.msgs.length - 1; i >= 0; i--) {
if (messageList.msgs[i].msg_id &&
messageList.msgs[i].msg_id !== payload.msg_id[0] &&
!messageList.msgs[i].hasRead &&
messageList.msgs[i].content.from_id !== global.user) {
messageList.msgs[i].hasRead = true;
payload.msg_id.push(messageList.msgs[i].msg_id);
}
if (messageList.msgs[i].msg_id === payload.msg_id[0]) {
break;
}
}
break;
}
}
break;
}
}
return payload;
}
// 处理好友列表数据
function filterFriendList(state: ChatStore, payload) {
for (let friend of payload) {
if (friend.username && !friend.name) {
friend.name = friend.username;
}
if (friend.nickname && !friend.nickName) {
friend.nickName = friend.nickname;
}
friend.type = 3;
}
}
// 客户端修改好友关系,对比删除了哪个好友,将整个应用中该好友的备注名换成昵称或者用户名
function compareFriendList(state: ChatStore, payload) {
for (let friend of state.friendList) {
const result = payload.filter((newFriend) => {
return newFriend.username === friend.username && newFriend.appkey === friend.appkey;
});
if (result.length === 0 && friend.memo_name) {
friend.memo_name = '';
modifyOtherInfoMemoName(state, friend);
modifyConversationMemoName(state, friend);
modifyActiveMessageList(state, friend);
if (state.activePerson.type === 3 && state.activePerson.name === friend.username &&
state.activePerson.appkey === friend.appkey) {
state.activePerson.memo_name = '';
}
}
}
}
// 添加群到群组列表
function addToGroupList(state: ChatStore, payload) {
state.groupList.push({
appkey: payload.from_appkey,
name: payload.group_name,
gid: payload.gid,
avatar: payload.avatar,
avatarUrl: payload.avatarUrl || ''
});
}
// 收到新消息,如果是当前会话,需要标识是否是当前会话
function newMessageIsActive(state, payload) {
const singleFlag = Number(state.activePerson.key) === Number(state.newMessage.key)
&& state.newMessage.msg_type === 3 && state.activePerson.type === 3;
const groupFlag = Number(state.activePerson.key) === Number(state.newMessage.key)
&& state.newMessage.msg_type === 4 && state.activePerson.type === 4;
state.newMessageIsActive = (singleFlag || groupFlag) ? true : false;
}
// 保存备注名成功
function saveMemoNameSuccess(state: ChatStore, payload) {
for (let user of payload.to_usernames) {
if (user.username) {
user.name = user.username;
}
if (user.nickname) {
user.nickName = user.nickname;
}
if (payload.description && payload.description.memo_name) {
user.memo_name = payload.description.memo_name;
}
modifyOtherInfoMemoName(state, user);
modifyFriendListMemoName(state, user);
modifyConversationMemoName(state, user);
modifyActiveMessageList(state, user);
}
}
// 删除好友同步事件
function deleteFriendSyncEvent(state: ChatStore, payload) {
for (let user of payload.to_usernames) {
user.name = user.username;
user.nickName = user.nickname;
modifyOtherInfoMemoName(state, user);
modifyFriendListMemoName(state, user);
modifyConversationMemoName(state, user);
modifyActiveMessageList(state, user);
friendSyncEvent(state, user, false);
}
}
// 用户信息更新事件
function userInfUpdateEventSuccess(state: ChatStore, payload) {
for (let friend of state.friendList) {
if (payload.name === friend.name) {
friend.nickName = payload.nickName;
friend.avatarUrl = payload.avatarUrl;
break;
}
}
for (let conversation of state.conversation) {
if (conversation.type === 3 && conversation.name === payload.name) {
conversation.nickName = payload.nickName;
conversation.avatarUrl = payload.avatarUrl;
}
if (conversation.recentMsg && conversation.recentMsg.content.from_id === payload.name) {
conversation.recentMsg.content.from_name = payload.nickName;
}
}
for (let messageList of state.messageList) {
for (let msg of messageList.msgs) {
if (msg.content.from_id === payload.name) {
msg.content.from_name = payload.nickName;
msg.content.avatarUrl = payload.avatarUrl;
}
}
if (messageList.groupSetting && messageList.groupSetting.memberList) {
for (let member of messageList.groupSetting.memberList) {
if (member.username === payload.name) {
member.avatarUrl = payload.avatarUrl;
member.nickName = payload.nickName;
}
}
}
}
if (payload.name === state.otherInfo.info.name) {
state.otherInfo.info = Object.assign({}, state.otherInfo.info, payload);
}
}
// 好友关系同步事件
function friendSyncEvent(state: ChatStore, user, bool) {
if (state.otherInfo.info.name === user.username &&
state.otherInfo.info.appkey === user.appkey) {
state.otherInfo.info.isFriend = bool;
}
}
// 单聊黑名单同步事件
function singleBlackSyncEvent(state: ChatStore, payload, bool) {
for (let addUser of payload.to_usernames) {
if (addUser.username === state.otherInfo.info.name &&
addUser.appkey === state.otherInfo.info.appkey) {
state.otherInfo.info.black = bool;
}
}
}
// 添加群组屏蔽同步事件
function addGroupShieldSyncEvent(state: ChatStore, payload) {
state.groupShield = state.groupShield.concat(payload.to_groups);
for (let addGroup of payload.to_groups) {
for (let conversation of state.conversation) {
if (conversation.type === 4 && Number(addGroup.gid) === Number(conversation.key)) {
conversation.shield = true;
break;
}
}
if (state.activePerson.type === 4 &&
Number(state.activePerson.key) === Number(addGroup.gid)) {
state.activePerson.shield = true;
}
}
}
// 删除群组屏蔽同步事件
function deleteGroupShieldSyncEvent(state: ChatStore, payload) {
for (let deleteGroup of payload.to_groups) {
for (let conversation of state.conversation) {
if (conversation.type === 4 && Number(deleteGroup.gid) === Number(conversation.key)) {
conversation.shield = false;
break;
}
}
for (let i = 0; i < state.groupShield.length; i++) {
if (Number(state.groupShield[i].gid) === Number(deleteGroup.gid)) {
state.groupShield.splice(i, 1);
break;
}
}
if (state.activePerson.type === 4 &&
Number(state.activePerson.key) === Number(deleteGroup.gid)) {
state.activePerson.shield = false;
}
}
}
// 添加群组免打扰同步事件
function addGroupNoDisturbSyncEvent(state: ChatStore, payload) {
state.noDisturb.groups = state.noDisturb.groups.concat(payload.to_groups);
for (let addGroup of payload.to_groups) {
addGroup.key = addGroup.gid;
for (let conversation of state.conversation) {
if (conversation.type === 4 && Number(conversation.key) === Number(addGroup.gid)) {
conversation.noDisturb = true;
break;
}
}
if (state.activePerson.type === 4 &&
Number(state.activePerson.key) === Number(addGroup.gid)) {
state.activePerson.noDisturb = true;
}
}
}
// 删除群组免打扰同步事件
function deleteGroupNoDisturbSyncEvent(state: ChatStore, payload) {
for (let deleteGroup of payload.to_groups) {
for (let i = 0; i < state.noDisturb.groups.length; i++) {
if (Number(state.noDisturb.groups[i].gid) === Number(deleteGroup.gid)) {
state.noDisturb.groups.splice(i, 1);
break;
}
}
for (let conversation of state.conversation) {
if (conversation.type === 4 &&
Number(conversation.key) === Number(deleteGroup.gid)) {
conversation.noDisturb = false;
break;
}
}
if (state.activePerson.type === 4 &&
Number(state.activePerson.key) === Number(deleteGroup.gid)) {
state.activePerson.noDisturb = false;
}
}
}
// 删除单聊免打扰同步事件
function deleteSingleNoDisturbSyncEvent(state: ChatStore, payload) {
for (let deleteUser of payload.to_usernames) {
for (let i = 0; i < state.noDisturb.users.length; i++) {
if (deleteUser.appkey === state.noDisturb.users[i].appkey &&
deleteUser.username === state.noDisturb.users[i].username) {
state.noDisturb.users.splice(i, 1);
break;
}
}
for (let conversation of state.conversation) {
if (conversation.type === 3 && conversation.appkey === deleteUser.appkey &&
conversation.name === deleteUser.username) {
conversation.noDisturb = false;
break;
}
}
if (state.activePerson.type === 3 && deleteUser.appkey === state.activePerson.appkey &&
deleteUser.username === state.activePerson.name) {
state.activePerson.noDisturb = false;
}
if (state.otherInfo.info.name === deleteUser.username &&
deleteUser.appkey === state.otherInfo.info.appkey) {
state.otherInfo.info.noDisturb = false;
}
}
}
// 添加单聊免打扰同步事件
function addSingleNoDisturbSyncEvent(state: ChatStore, payload) {
state.noDisturb.users = state.noDisturb.users.concat(payload.to_usernames);
for (let addUser of payload.to_usernames) {
for (let conversation of state.conversation) {
if (conversation.type === 3 && conversation.appkey === addUser.appkey &&
conversation.name === addUser.username) {
conversation.noDisturb = true;
break;
}
}
if (state.activePerson.type === 3 && addUser.appkey === state.activePerson.appkey &&
addUser.username === state.activePerson.name) {
state.activePerson.noDisturb = true;
}
if (state.otherInfo.info.name === addUser.username &&
addUser.appkey === state.otherInfo.info.appkey) {
state.otherInfo.info.noDisturb = true;
}
}
}
// 清空未读数同步事件
function emptyUnreadNumSyncEvent(state: ChatStore, payload) {
for (let conversation of state.conversation) {
const group = conversation.type === 4 && payload.type === 4 &&
(Number(conversation.key) === Number(payload.gid));
const single = conversation.type === 3 && payload.type === 3 &&
conversation.name === payload.name;
if (group || single) {
conversation.unreadNum = 0;
break;
}
}
}
// 获取群组信息
function initGroupInfo(state: ChatStore, payload) {
if (payload.groupInfo) {
if (payload.groupInfo.name === '') {
for (let conversation of state.conversation) {
if (conversation.type === 4 &&
Number(conversation.key) === Number(payload.groupInfo.gid)) {
payload.groupInfo.name = conversation.name;
break;
}
}
}
for (let messageList of state.messageList) {
if (messageList.type === 4 &&
Number(messageList.key) === Number(payload.groupInfo.gid)) {
if (!messageList.groupSetting) {
messageList.groupSetting = {};
}
messageList.groupSetting.groupInfo = payload.groupInfo;
messageList.groupSetting.loading = false;
break;
}
}
}
if (payload.memberList) {
sortGroupMember(payload.memberList);
for (let messageList of state.messageList) {
if (messageList.type === 4 &&
Number(messageList.key) === Number(payload.key)) {
for (let member of payload.memberList) {
for (let friend of state.friendList) {
if (friend.name === member.username) {
member.memo_name = friend.memo_name;
Util.getMemo_nameFirstLetter(member);
break;
}
}
}
if (!messageList.groupSetting) {
messageList.groupSetting = {};
}
messageList.groupSetting.memberList = payload.memberList;
break;
}
}
}
}
// 处理未读列表备注名
function filterUnreadListMemoName(state: ChatStore, payload) {
for (let read of payload.info.read_list) {
filterFriend(state, read);
}
for (let unread of payload.info.unread_list) {
filterFriend(state, unread);
}
}
// 更新群组信息事件
function updateGroupInfoEventSuccess(state: ChatStore, payload) {
payload.eventData.key = payload.eventData.gid;
payload.eventData.name = payload.eventData.username = payload.eventData.from_username;
payload.eventData.nickName = payload.eventData.nickname = payload.eventData.from_nickname;
filterFriend(state, payload.eventData);
if (Number(payload.eventData.gid) === Number(state.activePerson.key)) {
if (payload.groupInfo.name !== '') {
state.activePerson.name = payload.groupInfo.name;
}
state.newMessageIsActive = true;
} else {
state.newMessageIsActive = false;
}
let item = null;
let msg = {
ctime_ms: payload.eventData.ctime_ms,
msg_type: 5,
content: {
msg_body: {
text: `${payload.eventData.memo_name ||
payload.eventData.nickName || payload.eventData.name || '管理员'}修改了群信息`
},
msg_type: 'event'
},
time_show: '',
conversation_time_show: 'today'
};
for (let list of state.messageList) {
if (list.type === 4 && Number(list.key) === Number(payload.eventData.key)) {
if (list.msgs.length > 0) {
if (Util.fiveMinutes(list.msgs[list.msgs.length - 1].ctime_ms,
payload.eventData.ctime_ms)) {
msg.time_show = 'today';
}
} else {
msg.time_show = 'today';
}
list.msgs.push(msg);
if (list.groupSetting && list.groupSetting.groupInfo) {
let name;
if (!payload.groupInfo.name || payload.groupInfo.name === '') {
name = list.groupSetting.groupInfo.name;
}
list.groupSetting.groupInfo = payload.groupInfo;
if (name) {
list.groupSetting.groupInfo.name = name;
}
}
break;
}
}
for (let i = 0; i < state.conversation.length; i++) {
if (state.conversation[i].type === 4 &&
Number(state.conversation[i].key) === Number(payload.eventData.key)) {
item = state.conversation.splice(i, 1)[0];
if (payload.groupInfo.avatarUrl && payload.groupInfo.avatarUrl !== '') {
item.avatarUrl = payload.groupInfo.avatarUrl;
}
if (payload.groupInfo.name !== '') {
item.name = payload.groupInfo.name;
}
break;
}
}
for (let group of state.groupList) {
if (Number(payload.eventData.key) === Number(group.gid)) {
if (payload.groupInfo.avatarUrl !== '') {
group.avatarUrl = payload.groupInfo.avatarUrl;
}
if (payload.groupInfo.name !== '') {
group.name = payload.groupInfo.name;
}
}
}
if (item === null) {
item = payload.groupInfo;
item.type = 4;
state.messageList.push({
key: payload.eventData.key,
msgs: [
msg
],
type: 4
});
}
item.recentMsg = msg;
filterTopConversation(state, item);
}
// 已读事件监听
function msgReceiptChangeEvent(state: ChatStore, payload) {
if (payload instanceof Array) {
for (let item of payload) {
msgReceiptChange(state, item);
}
} else {
msgReceiptChange(state, payload);
}
}
function msgReceiptChange(state: ChatStore, payload) {
for (let messageList of state.messageList) {
if (payload.type === 3) {
if (messageList.type === 3 && payload.username === messageList.name
&& payload.appkey === messageList.appkey) {
updateUnreadCount(state, messageList, payload);
for (let conversation of state.conversation) {
if (payload.type === 3 && conversation.type === 3 &&
payload.username === conversation.name &&
payload.appkey === conversation.appkey) {
emptyUnreadText(conversation, payload);
}
}
}
} else if (payload.type === 4) {
if (messageList.type === 4 && Number(payload.gid) === Number(messageList.key)) {
updateUnreadCount(state, messageList, payload);
}
}
}
}
// 更新未读数
function updateUnreadCount(state: ChatStore, messageList, payload) {
for (let receipt of payload.receipt_msgs) {
for (let i = messageList.msgs.length - 1; i >= 0; i--) {
if (messageList.msgs[i].msg_id === receipt.msg_id) {
if (messageList.msgs[i].unread_count > receipt.unread_count) {
messageList.msgs[i].unread_count = receipt.unread_count;
}
break;
}
}
}
}
// 清空会话的未读标识
function emptyUnreadText(conversation, payload) {
for (let receipt of payload.receipt_msgs) {
if (conversation.recentMsg &&
conversation.recentMsg.msg_id === receipt.msg_id) {
conversation.recentMsg.unread_count = 0;
break;
}
}
}
// 会话置顶和取消置顶
function conversationToTop(state: ChatStore, payload) {
for (let i = 0; i < state.conversation.length; i++) {
if (Number(state.conversation[i].key) === Number(payload.key)) {
let item = state.conversation.splice(i, 1)[0];
if (item.extras && item.extras.top_time_ms) {
delete item.extras.top_time_ms;
} else {
item.extras.top_time_ms = new Date().getTime();
}
filterTopConversation(state, item);
break;
}
}
}
// 聊天文件中的文件中的图片加载成功
function fileImageLoad(state: ChatStore, payload) {
for (let message of state.msgFileImageViewer) {
const msgIdFlag = payload.msg_id && message.msg_id === payload.msg_id;
const msgKeyFlag = payload.msgKey && message.msgKey === payload.msgKey;
if (msgIdFlag || msgKeyFlag) {
message.width = payload.content.msg_body.width;
message.height = payload.content.msg_body.height;
break;
}
}
}
// 处理聊天文件中的图片预览对象
function filterMsgFileImageViewer(state: ChatStore, type: string) {
state.msgFileImageViewer = [];
for (let message of state.messageList[state.activePerson.activeIndex].msgs) {
let fileType = '';
if (message.content.msg_type === 'file') {
if (message.content.msg_body.extras) {
if (message.content.msg_body.extras.video) {
fileType = 'video';
} else if (message.content.msg_body.extras.fileType) {
fileType = Util.sortByExt(message.content.msg_body.extras.fileType);
} else {
fileType = 'other';
}
} else {
fileType = 'other';
}
}
if ((message.content.msg_type === 'image') || fileType === 'image') {
state.msgFileImageViewer.push({
src: message.content.msg_body.media_url,
width: message.content.msg_body.width,
height: message.content.msg_body.height,
msgKey: message.msgKey,
msg_id: message.msg_id
});
}
}
state.msgFileImageViewer.reverse();
}
// 处理聊天文件中的文件列表
function filterMsgFile(state: ChatStore, type: string) {
let fileArr = [];
let msgFile = [];
for (let message of state.messageList[state.activePerson.activeIndex].msgs) {
let fileType = '';
if (message.content.msg_type === 'file') {
if (message.content.msg_body.extras) {
if (message.content.msg_body.extras.video) {
fileType = 'video';
} else if (message.content.msg_body.extras.fileType) {
fileType = Util.sortByExt(message.content.msg_body.extras.fileType);
} else {
fileType = 'other';
}
} else {
fileType = 'other';
}
}
if ((message.content.msg_type === type && type === 'image') || fileType === type) {
fileArr.push(message);
state.msgFileImageViewer.push({
src: message.content.msg_body.media_url,
width: message.content.msg_body.width,
height: message.content.msg_body.height,
msgKey: message.msgKey,
msg_id: message.msg_id
});
}
}
for (let i = fileArr.length - 1; i >= 0; i--) {
const time = new Date(fileArr[i].ctime_ms);
const year = time.getFullYear();
const month = Util.doubleNumber(time.getMonth() + 1);
let flag = true;
const showTime = year + '年' + month + '月';
for (let item of msgFile) {
if (item.time === showTime) {
item.msgs.push(fileArr[i]);
flag = false;
break;
}
}
if (flag) {
msgFile.push({
time: showTime,
msgs: [fileArr[i]]
});
}
}
state.msgFile[type] = msgFile;
}
// 给会话列表和当前消息列表添加备注名
function filterConversationMemoName(state: ChatStore) {
for (let conversation of state.conversation) {
for (let friend of state.friendList) {
if (conversation.name === friend.name && conversation.type === 3) {
conversation.memo_name = friend.memo_name;
}
if (conversation.recentMsg && conversation.recentMsg.content.from_id === friend.name
&& conversation.type === 4) {
conversation.recentMsg.content.memo_name = friend.memo_name;
}
}
}
if (state.activePerson.activeIndex >= 0 && state.activePerson.type === 4
&& state.messageList[state.activePerson.activeIndex]) {
for (let message of state.messageList[state.activePerson.activeIndex].msgs) {
for (let friend of state.friendList) {
if (message.content.from_id === friend.name) {
message.content.memo_name = friend.memo_name;
}
}
}
}
}
// 更新其他用户资料
function updateOtherInfo(state: ChatStore, payload) {
if (payload.return_code === 0 && state.otherInfo.info.name === payload.from_username) {
state.otherInfo.info.isFriend = true;
}
}
// 用户资料中删除好友
function otherInfoDeleteFriend(state: ChatStore, payload) {
if (state.otherInfo.info.name === payload.name) {
state.otherInfo.info.isFriend = false;
state.otherInfo.show = false;
}
let hasMemoName = false;
for (let i = 0; i < state.friendList.length; i++) {
if (state.friendList[i].name === payload.name) {
if (state.friendList[i].memo_name && state.friendList[i].memo_name !== '') {
hasMemoName = true;
}
state.friendList.splice(i, 1);
break;
}
}
for (let i = 0; i < state.conversation.length; i++) {
if (state.conversation[i].name === payload.name && state.conversation[i].type === 3) {
state.conversation.splice(i, 1);
break;
}
}
if (state.activePerson.name === payload.name && state.activePerson.type === 3) {
state.defaultPanelIsShow = true;
}
if (hasMemoName) {
for (let messageList of state.messageList) {
if (messageList.type === 4) {
for (let msg of messageList.msgs) {
if (msg.content.from_id === payload.name) {
msg.content.memo_name = '';
}
}
if (messageList.groupSetting && messageList.groupSetting.memberList) {
for (let member of messageList.groupSetting.memberList) {
if (member.username === payload.name) {
member.memo_name = '';
break;
}
}
}
}
}
for (let conversation of state.conversation) {
if (conversation.type === 4 && conversation.recentMsg) {
if (conversation.recentMsg.content.from_id === payload.name) {
conversation.recentMsg.content.memo_name = '';
}
}
}
}
}
// 修改会话列表的备注名
function modifyConversationMemoName(state: ChatStore, payload) {
for (let conversation of state.conversation) {
if (conversation.name === payload.name && conversation.type === 3) {
conversation.memo_name = payload.memo_name;
}
if (conversation.recentMsg &&
conversation.recentMsg.content.from_id === payload.name) {
conversation.recentMsg.content.memo_name = payload.memo_name;
}
}
if (state.activePerson.type === 3 && state.activePerson.name === payload.name) {
state.activePerson.memo_name = payload.memo_name;
}
}
// 修改好友列表的备注名
function modifyFriendListMemoName(state: ChatStore, payload) {
for (let friend of state.friendList) {
if (friend.name === payload.name) {
friend.memo_name = payload.memo_name;
break;
}
}
}
// 修改用户信息的备注名
function modifyOtherInfoMemoName(state: ChatStore, payload) {
if (payload.name === state.otherInfo.info.name) {
state.otherInfo.info.memo_name = payload.memo_name;
}
}
// 当前会话有修改了备注的用户时,修改消息列表的备注和群成员的备注
function modifyActiveMessageList(state: ChatStore, payload) {
if (state.activePerson.activeIndex > 0 && state.activePerson.type === 4) {
let messageList = state.messageList[state.activePerson.activeIndex];
let msgs = messageList.msgs;
for (let message of msgs) {
if (message.content.from_id === payload.name ||
message.content.from_id === payload.username) {
message.content.memo_name = payload.memo_name;
}
}
if (messageList.groupSetting && messageList.groupSetting.memberList) {
for (let member of messageList.groupSetting.memberList) {
if (member.username === payload.name || member.username === payload.username) {
member.memo_name = payload.memo_name;
Util.getMemo_nameFirstLetter(member);
}
}
}
}
}
// 更新(增加或删除)黑名单列表里的用户
function updateBlackMenu(state: ChatStore, payload) {
let flag = true;
for (let i = 0; i < state.blackMenu.length; i++) {
if (state.blackMenu[i].username === payload.username) {
state.blackMenu.splice(i, 1);
flag = false;
break;
}
}
if (flag) {
state.blackMenu.push({
username: payload.username,
appkey: payload.appkey
});
}
}
// 判断用户是否是黑名单
function filterSingleBlack(state: ChatStore, payload) {
for (let black of state.blackMenu) {
if (black.username === payload.name) {
payload.black = true;
break;
}
}
}
// 判断用户是否是免打扰
function filterSingleNoDisturb(state: ChatStore, payload) {
for (let user of state.noDisturb.users) {
if (user.username === payload.name) {
payload.noDisturb = true;
break;
}
}
}
// 判断是否是好友
function filterFriend(state: ChatStore, payload) {
const result = state.friendList.filter((friend) => {
return friend.name === payload.name || friend.name === payload.username
|| friend.name === payload.from_username;
});
if (result.length > 0) {
payload.memo_name = result[0].memo_name;
}
return result.length > 0 ? true : false;
}
// 同意添加好友后添加好友到会话列表
function addNewFriendToConversation(state: ChatStore, payload, type) {
if (payload.return_code !== 0 && type !== 'agree') {
return;
}
if (payload.from_username) {
payload.name = payload.from_username;
payload.username = payload.from_username;
payload.nickName = payload.from_nickname;
payload.nickname = payload.from_nickname;
}
if (state.activePerson.type === 3 && payload.from_username === state.activePerson.name) {
state.newMessageIsActive = true;
}
const result = state.friendList.filter((friend) => {
return friend.name === payload.name;
});
if (result.length === 0) {
state.friendList.push(payload);
}
let item = null;
let msg = {
ctime_ms: payload.ctime_ms,
msg_type: 5,
content: {
msg_body: {
text: '已成功添加为好友'
},
msg_type: 'event'
},
time_show: '',
conversation_time_show: Util.reducerDate(payload.ctime_ms)
};
for (let i = 0; i < state.conversation.length; i++) {
if (state.conversation[i].type === 3 && state.conversation[i].name === payload.name) {
for (let list of state.messageList) {
if (state.conversation[i].name === list.name &&
state.conversation[i].appkey === list.appkey) {
if (list.msgs.length > 0) {
if (Util.fiveMinutes(list.msgs[list.msgs.length - 1].ctime_ms,
payload.ctime_ms)) {
msg.time_show = Util.reducerDate(payload.ctime_ms);
}
} else {
msg.time_show = Util.reducerDate(payload.ctime_ms);
}
list.msgs.push(msg);
break;
}
}
if (!state.conversation[i].extras || !state.conversation[i].extras.top_time_ms) {
item = state.conversation.splice(i, 1)[0];
} else {
state.conversation[i].recentMsg = msg;
return;
}
break;
}
}
if (item === null) {
item = payload;
state.messageList.push({
msgs: [
msg
],
appkey: payload.appkey || authPayload.appkey,
name: payload.name,
type: 3
});
msg.time_show = Util.reducerDate(payload.ctime_ms);
}
item.recentMsg = msg;
filterTopConversation(state, item);
}
// 退群
function exitGroup(state: ChatStore, item) {
if (item.gid) {
item.key = item.gid;
}
for (let i = 0; i < state.groupList.length; i++) {
if (Number(state.groupList[i].gid) === Number(item.key)) {
state.groupList.splice(i, 1);
break;
}
}
}
// 隐藏群设置
function showGroupSetting(state: ChatStore, show) {
if (state.activePerson.activeIndex >= 0) {
let groupSetting = state.messageList[state.activePerson.activeIndex].groupSetting;
if (groupSetting) {
groupSetting.show = show;
}
}
}
// 判断当前用户是否是目标用户
function currentIsActive(state: ChatStore, payload) {
return state.activePerson.type === 4 &&
Number(state.activePerson.key) === Number(payload.gid) ? true : false;
}
// 消息撤回
function msgRetract(state: ChatStore, payload) {
let name = '';
let recentMsg = {};
let index;
let singleSendName = '';
if (payload.type === 0 && payload.from_username === global.user) {
singleSendName = payload.to_usernames[0].username;
} else if (payload.type === 0) {
singleSendName = payload.from_username;
}
for (let i = 0; i < state.conversation.length; i++) {
const isGroup = payload.type === 1 && state.conversation[i].type === 4 &&
Number(payload.from_gid) === Number(state.conversation[i].key);
const isSingle = payload.type === 0 && state.conversation[i].type === 3 &&
state.conversation[i].name === singleSendName;
if (isGroup || isSingle) {
const msgType = isGroup ? 4 : 3;
if (payload.from_username === global.user) {
name = '您';
} else if (msgType === 4) {
payload.name = payload.from_username;
if (filterFriend(state, payload) && payload.memo_name && payload.memo_name !== '') {
name = payload.memo_name;
} else if (payload.from_nickname && payload.from_nickname !== '') {
name = payload.from_nickname;
} else {
name = payload.from_username;
}
} else if (msgType === 3) {
name = '对方';
}
recentMsg = {
ctime_ms: payload.ctime_ms,
content: {
msg_body: {
text: `${name}撤回了一条消息`
},
msg_type: 'event'
},
conversation_time_show: Util.reducerDate(payload.ctime_ms),
msg_type: msgType
};
payload.key = state.conversation[i].key;
index = i;
if (!state.conversation[i].extras || !state.conversation[i].extras.top_time_ms) {
const item = state.conversation.splice(i, 1);
index = filterTopConversation(state, item[0]);
}
break;
}
}
for (let messageList of state.messageList) {
const group = payload.type === 1 && messageList.type === 4 &&
Number(payload.key) === Number(messageList.key);
const single = payload.type === 0 && messageList.type === 3 &&
singleSendName === messageList.name;
if (single || group) {
for (let i = 0; i < messageList.msgs.length; i++) {
if (Number(messageList.msgs[i].msg_id) === Number(payload.msg_ids[0])) {
let eventMsg = {
ctime_ms: payload.ctime_ms,
msg_type: 5,
content: {
msg_body: {
text: `${name}撤回了一条消息`
}
},
time_show: ''
};
let item = messageList.msgs.splice(i, 1);
eventMsg.ctime_ms = item[0].ctime_ms;
messageList.msgs.splice(i, 0, eventMsg);
if (i === messageList.msgs.length - 1) {
state.conversation[index].recentMsg = recentMsg;
}
break;
}
}
break;
}
}
}
// 删除群成员事件
function deleteGroupMembersEvent(state: ChatStore, payload) {
for (let messageList of state.messageList) {
if (messageList.type === 4 && Number(messageList.key) === Number(payload.gid)) {
if (messageList.groupSetting && messageList.groupSetting.memberList) {
let memberList = messageList.groupSetting.memberList;
for (let user of payload.to_usernames) {
for (let i = 0; i < memberList.length; i++) {
if (user.username === memberList[i].username) {
memberList.splice(i, 1);
break;
}
}
}
if (payload.new_owner) {
for (let i = 0; i < memberList.length; i++) {
if (payload.new_owner.username === memberList[i].username) {
let item = memberList.splice(i, 1)[0];
item.flag = 1;
memberList.unshift(item);
break;
}
}
}
}
break;
}
}
}
// 切换用户前清除语音的定时器
function clearVoiceTimer(state: ChatStore) {
let activeIndex = state.activePerson.activeIndex;
let activeMessageList = state.messageList[activeIndex];
if (activeIndex < 0 || !activeMessageList) {
return;
}
for (let msg of activeMessageList.msgs) {
if (msg.content.msg_type === 'voice') {
msg.content.playing = false;
}
}
}
// 被添加进群时更新群成员
function updateGroupMembers(state: ChatStore, eventData) {
for (let messageList of state.messageList) {
if (messageList.type === 4 &&
Number(messageList.key) === Number(eventData.gid)) {
if (messageList.groupSetting) {
for (let user of eventData.to_usernames) {
user.flag = 0;
}
if (messageList.groupSetting.memberList) {
for (let user of eventData.to_usernames) {
let flag = true;
for (let member of messageList.groupSetting.memberList) {
if (user.username === member.username) {
flag = false;
}
}
if (flag) {
messageList.groupSetting.memberList.push(user);
}
}
}
}
break;
}
}
}
// 接收到管理员建群时自动添加会话和消息
function createGroupSuccessEvent(state: ChatStore, payload) {
let item = {
key: payload.gid,
name: payload.name,
type: 4,
unreadNum: 0,
recentMsg: {
ctime_ms: payload.ctime_ms,
content: {
msg_body: {
text: '创建群聊'
},
msg_type: 'event'
},
conversation_time_show: Util.reducerDate(payload.ctime_ms),
msg_type: 4
}
};
filterTopConversation(state, item);
state.groupList.push({
appkey: payload.from_appkey,
name: payload.group_name,
gid: payload.gid,
avatar: payload.avatar,
avatarUrl: payload.avatarUrl || ''
});
state.messageList.push({
key: payload.gid,
msgs: [
{
ctime_ms: payload.ctime_ms,
msg_type: 5,
content: {
msg_body: {
text: '创建群聊'
}
},
time_show: Util.reducerDate(payload.ctime_ms)
}
],
type: 4
});
if (payload.isOffline) {
sortConversationByRecentMsg(state);
}
}
// 给群聊事件添加最近一条聊天消息
function isRecentmsg(state: ChatStore, payload, addGroupOther, operation, index) {
let flag = false;
for (let messageList of state.messageList) {
if (state.conversation[index].type === 4 &&
Number(state.conversation[index].key) === Number(messageList.key)) {
flag = true;
let msg = messageList['msgs'];
if (msg.length === 0 || payload.ctime_ms > msg[msg.length - 1].ctime_ms) {
state.conversation[index].recentMsg = {
ctime_ms: payload.ctime_ms,
content: {
msg_body: {
text: addGroupOther + operation
},
msg_type: 'event'
},
conversation_time_show: Util.reducerDate(payload.ctime_ms),
msg_type: 4
};
}
break;
}
}
if (!flag) {
state.conversation[index].recentMsg = {
ctime_ms: payload.ctime_ms,
content: {
msg_body: {
text: addGroupOther + operation
},
msg_type: 'event'
},
conversation_time_show: Util.reducerDate(payload.ctime_ms),
msg_type: 4
};
}
}
// 通过recentMsg去对conversation排序
function sortConversationByRecentMsg(state: ChatStore) {
for (let conversation of state.conversation) {
if (conversation.recentMsg) {
conversation.lastMsgTime = conversation.recentMsg.ctime_ms;
} else {
conversation.lastMsgTime = 0;
}
}
let len = state.conversation.length;
let maxIndex;
let temp;
let topIndex = 0;
for (let i = 0; i < len; i++) {
if (!state.conversation[i].extras || !state.conversation[i].extras.top_time_ms) {
topIndex = i;
break;
}
}
for (let i = topIndex; i < len - 1; i++) {
maxIndex = i;
for (let j = i + 1; j < len; j++) {
if (state.conversation[j].lastMsgTime >
state.conversation[maxIndex].lastMsgTime) {
maxIndex = j;
}
}
temp = Util.deepCopyObj(state.conversation[i]);
state.conversation[i] = Util.deepCopyObj(state.conversation[maxIndex]);
state.conversation[maxIndex] = temp;
}
}
// 被添加进群、移出群、退出群的事件
function groupMembersEvent(state: ChatStore, payload, operation) {
for (let shield of state.groupShield) {
if (Number(shield.gid) === Number(payload.gid)) {
return;
}
}
let usernames = payload.to_usernames;
let addGroupOther = '';
for (let user of usernames) {
if (user.nickname) {
user.nickName = user.nickname;
}
if (user.username) {
user.name = user.username;
}
filterFriend(state, user);
if (user.username === global.user) {
addGroupOther = '您' + '、';
} else {
let name = '';
if (filterFriend(state, user) && user.memo_name && user.memo_name !== '') {
name = user.memo_name;
} else if (user.nickname && user.nickname !== '') {
name = user.nickname;
} else {
name = user.username;
}
addGroupOther += name + '、';
}
}
if (addGroupOther.length > 0) {
addGroupOther = addGroupOther.slice(0, addGroupOther.length - 1);
}
let flag1 = true;
for (let i = 0; i < state.conversation.length; i++) {
if (state.conversation[i].type === 4 &&
Number(payload.gid) === Number(state.conversation[i].key)) {
flag1 = false;
let index = i;
if (!state.conversation[i].extras || !state.conversation[i].extras.top_time_ms) {
let item = state.conversation.splice(i, 1);
index = filterTopConversation(state, item[0]);
}
isRecentmsg(state, payload, addGroupOther, operation, index);
break;
}
}
if (flag1) {
for (let group of state.groupList) {
if (Number(group.gid) === Number(payload.gid)) {
let conversation = Util.deepCopyObj(group);
conversation.type = 4;
conversation.key = group.gid;
conversation.unreadNum = 0;
for (let noDisturbGroup of state.noDisturb.groups) {
if (Number(noDisturbGroup.gid) === Number(payload.gid)) {
conversation.noDisturb = true;
break;
}
}
const index = filterTopConversation(state, conversation);
flag1 = false;
isRecentmsg(state, payload, addGroupOther, operation, index);
break;
}
}
}
// 对群组列表和会话列表中没有的群,并且是离线的事件消息,不做任何处理
if (flag1 && payload.isOffline) {
return;
}
if (flag1) {
let conversation = {
key: payload.gid,
name: payload.name,
type: 4,
unreadNum: 0,
avatarUrl: payload.avatarUrl,
recentMsg: {
ctime_ms: payload.ctime_ms,
content: {
msg_body: {
text: addGroupOther + operation
},
msg_type: 'event'
},
conversation_time_show: Util.reducerDate(payload.ctime_ms),
msg_type: 4
}
};
// 如果群聊事件消息的群名和群头像不存在,去群组列表获取
for (let group of state.groupList) {
if (Number(group.gid) === Number(payload.gid)) {
if (group.avatarUrl) {
conversation.avatarUrl = group.avatarUrl;
}
if (!payload.name || payload.name === '') {
conversation.name = group.name;
}
break;
}
}
filterTopConversation(state, conversation);
}
// 重新对conversation排序
if (payload.isOffline) {
sortConversationByRecentMsg(state);
}
addEventMsgToMessageList(state, payload, addGroupOther, operation);
}
// 将群聊事件消息添加到消息列表
function addEventMsgToMessageList(state: ChatStore, payload, addGroupOther, operation) {
let message = {
ctime_ms: payload.ctime_ms,
msg_type: 5,
content: {
msg_body: {
text: addGroupOther + operation
}
},
time_show: ''
};
let flag2 = true;
for (let messageList of state.messageList) {
if (Number(payload.gid) === Number(messageList.key)) {
flag2 = false;
let msgs = messageList.msgs;
if (payload.isOffline) {
if (msgs.length === 0) {
message.time_show = Util.reducerDate(payload.ctime_ms);
msgs.push(message);
} else if (msgs[msgs.length - 1].ctime_ms < payload.ctime_ms) {
if (Util.fiveMinutes(msgs[msgs.length - 1].ctime_ms, payload.ctime_ms)) {
message.time_show = Util.reducerDate(payload.ctime_ms);
}
msgs.push(message);
} else {
for (let j = 0; j < msgs.length - 1; j++) {
if (msgs[j].ctime_ms < payload.ctime_ms &&
payload.ctime_ms < msgs[j + 1].ctime_ms) {
if (Util.fiveMinutes(msgs[j].ctime_ms, payload.ctime_ms)) {
message.time_show = Util.reducerDate(payload.ctime_ms);
}
if (!Util.fiveMinutes(payload.ctime_ms, msgs[j + 1].ctime_ms)) {
messageList.msgs[j + 1].time_show = '';
}
messageList.msgs.splice(j + 1, 0, message);
break;
}
}
}
} else {
if (msgs.length === 0 ||
Util.fiveMinutes(msgs[msgs.length - 1].ctime_ms, payload.ctime_ms)) {
message.time_show = Util.reducerDate(payload.ctime_ms);
}
msgs.push(message);
}
break;
}
}
if (flag2) {
message.time_show = Util.reducerDate(payload.ctime_ms);
state.messageList.push({
key: payload.gid,
msgs: [message],
type: 4
});
}
}
// 离线消息15天后消失,而会话列表依然存在,导致不一一对应,所以补全离线消息
function completionMessageList(state: ChatStore) {
for (let conversation of state.conversation) {
let flag = false;
for (let messageList of state.messageList) {
const group = messageList.type === 4 &&
Number(conversation.key) === Number(messageList.key);
const single = messageList.type === 3 &&
conversation.name === messageList.name;
if (group || single) {
flag = true;
break;
}
}
if (!flag) {
if (conversation.type === 3) {
state.messageList.push({
key: conversation.key,
msgs: [],
type: 3,
appkey: conversation.appkey,
name: conversation.name
});
} else if (conversation.type === 4) {
state.messageList.push({
key: conversation.key,
msgs: [],
type: 4
});
}
}
}
}
// 切换单聊用户免打扰
function changeSingleNoDisturb(state: ChatStore, payload) {
let flag = true;
for (let i = 0; i < state.noDisturb.users.length; i++) {
if (payload.name === state.noDisturb.users[i].username) {
flag = false;
state.noDisturb.users.splice(i, 1);
}
}
if (flag) {
state.noDisturb.users.push({
username: payload.name,
appkey: payload.appkey
});
}
for (let conversation of state.conversation) {
if (conversation.type === 3 && conversation.name === payload.name) {
if (flag) {
conversation.noDisturb = true;
} else {
conversation.noDisturb = false;
}
break;
}
}
}
// 初始化免打扰
function initNoDisturb(state: ChatStore, noDisturb) {
for (let user of noDisturb.users) {
for (let conversation of state.conversation) {
if (conversation.type === 3 && user.username === conversation.name) {
conversation.noDisturb = true;
break;
}
}
}
for (let group of noDisturb.groups) {
group.key = group.gid;
for (let conversation of state.conversation) {
if (conversation.type === 4 && Number(group.key) === Number(conversation.key)) {
conversation.noDisturb = true;
break;
}
}
}
}
// 切换群免打扰
function changeGroupNoDisturb(state: ChatStore, payload) {
for (let conversation of state.conversation) {
const group = conversation.type === 4 && payload.type === 4 &&
Number(payload.key) === Number(conversation.key);
if (group) {
conversation.noDisturb = !conversation.noDisturb;
break;
}
}
let flag = true;
for (let i = 0; i < state.noDisturb.groups.length; i++) {
if (Number(state.noDisturb.groups[i].key) === Number(payload.key)) {
state.noDisturb.groups.splice(i, 1);
flag = false;
break;
}
}
if (flag) {
state.noDisturb.groups.push({
key: Number(payload.key),
name: payload.name,
appkey: payload.appkey
});
}
}
// 初始化群屏蔽
function initGroupShield(state: ChatStore, shield) {
for (let shieldItem of shield) {
for (let conversation of state.conversation) {
if (conversation.type === 4 && Number(shieldItem.gid) === Number(conversation.key)) {
conversation.shield = true;
break;
}
}
}
state.groupShield = shield;
}
// 切换群屏蔽
function changeGroupShield(state: ChatStore, payload) {
for (let item of state.conversation) {
if (item.type === 4 && Number(payload.key) === Number(item.key)) {
item.shield = !item.shield;
if (item.shield) {
state.groupShield.push({
gid: item.key,
name: item.name
});
} else {
for (let i = 0; i < state.groupShield.length; i++) {
if (item.type === 4 && Number(state.groupShield[i].gid) === Number(item.key)) {
state.groupShield.splice(i, 1);
break;
}
}
}
break;
}
}
}
// 过滤出当前图片预览的数组
function filterImageViewer(state: ChatStore) {
let messageList = state.messageList[state.activePerson.activeIndex];
if (state.activePerson.activeIndex < 0 || !messageList || !messageList.msgs) {
return [];
}
let imgResult = [];
let msgs = messageList.msgs;
for (let message of msgs) {
let content = message.content;
const jpushEmoji = (!content.msg_body.extras || !content.msg_body.extras.kLargeEmoticon
|| content.msg_body.extras.kLargeEmoticon !== 'kLargeEmoticon');
if (content.msg_type === 'image' && jpushEmoji) {
imgResult.push({
mediaId: content.msg_body.media_id,
src: content.msg_body.media_url,
width: content.msg_body.width,
height: content.msg_body.height,
msg_id: message.msg_id
});
}
}
return imgResult;
}
// 切换当前会话用户
function changeActivePerson(state: ChatStore) {
if (state.activePerson.type === 4 && state.activePerson.gid) {
state.activePerson.key = state.activePerson.gid;
}
for (let i = 0; i < state.messageList.length; i++) {
const group = state.activePerson.type === 4 && state.messageList[i].type === 4 &&
Number(state.messageList[i].key) === Number(state.activePerson.key);
const single = state.activePerson.type === 3 && state.messageList[i].type === 3 &&
state.messageList[i].name === state.activePerson.name;
if (group || single) {
state.activePerson.activeIndex = i;
break;
}
}
let list = state.messageList[state.activePerson.activeIndex];
for (let msg of list.msgs) {
const video = (msg.content.msg_body.extras && msg.content.msg_body.extras.video);
if (msg.content.msg_type === 'file' && video) {
// audio 0 正在加载 1 加载完成 2 正在播放
msg.content.load = 0;
// 加载进度 0%
msg.content.range = 0;
} else if (msg.content.msg_type === 'voice') {
// voice 播放时的动画
msg.content.playing = false;
msg.content.load = 0;
}
// 给群聊消息中的好友添加备注名
for (let friend of state.friendList) {
if (friend.name === msg.content.from_id) {
msg.content.memo_name = friend.memo_name;
break;
}
}
// 初始化图片消息的loading状态
if (msg.content.msg_type === 'image') {
msg.content.msg_body.loading = false;
}
}
// 给群成员中的好友添加备注名
if (state.activePerson.type === 4 &&
list && list.groupSetting && list.groupSetting.memberList) {
for (let member of list.groupSetting.memberList) {
for (let friend of state.friendList) {
if (friend.name === member.username) {
member.memo_name = friend.memo_name;
Util.getMemo_nameFirstLetter(member);
break;
}
}
}
}
// 初始化已读语音消息的状态
for (let i = 0; i < state.voiceState.length; i++) {
if (Number(state.voiceState[i].key) === Number(list.key)) {
let flag = true;
for (let msg of list.msgs) {
if (Number(state.voiceState[i].msgId) === Number(msg.msg_id)) {
msg.content.havePlay = true;
flag = false;
break;
}
}
if (flag) {
state.voiceState.splice(i, 1);
}
}
}
state.imageViewer = filterImageViewer(state);
}
// 添加最近一条聊天消息
function filterRecentMsg(state: ChatStore) {
for (let conversation of state.conversation) {
for (let messageList of state.messageList) {
const group = conversation.type === 4 && messageList.type === 4 &&
Number(conversation.key) === Number(messageList.key);
const single = conversation.type === 3 && messageList.type === 3 &&
conversation.name === messageList.name;
if (group || single) {
let msgs = messageList.msgs;
if (msgs.length > 0) {
msgs[msgs.length - 1].conversation_time_show =
Util.reducerDate(msgs[msgs.length - 1].ctime_ms);
conversation.recentMsg = msgs[msgs.length - 1];
}
break;
}
}
}
sortConversationByRecentMsg(state);
}
// 将群主放在第一位
function sortGroupMember(memberList) {
for (let i = 0; i < memberList.length; i++) {
if (memberList[i].flag === 1) {
let temp = memberList.splice(i, 1);
memberList.unshift(temp[0]);
break;
}
}
}
// 完成消息的发送接口的调用后,返回成功或者失败状态
function sendMsgComplete(state: ChatStore, payload) {
if (payload.success === 2) {
payload.msgs.success = 2;
for (let conversation of state.conversation) {
// 转发消息时没有key
if (!payload.key) {
if (payload.name === conversation.name) {
payload.key = conversation.key;
conversation.key = payload.msgs.key;
}
// 转发或者发送消息时key < 0
} else if (Number(payload.key) < 0) {
if (Number(payload.key) === Number(conversation.key)) {
conversation.key = payload.msgs.key;
}
}
// 给recentMsg添加msg_id
if (payload.type === 3 && payload.name === conversation.name &&
conversation.type === 3) {
payload.msgs.unread_count = 1;
payload.msgs.conversation_time_show =
conversation.recentMsg.conversation_time_show;
payload.msgs.ctime_ms = conversation.recentMsg.ctime_ms;
conversation.recentMsg = payload.msgs;
}
}
}
for (let messageList of state.messageList) {
const group = payload.type === 4 && messageList.type === 4 &&
Number(messageList.key) === Number(payload.key);
const single = payload.type === 3 && messageList.type === 3 &&
messageList.name === payload.name;
if (group || single) {
if (Number(payload.key) < 0 && payload.success === 2) {
messageList.key = payload.msgs.key;
if (Number(payload.key) === Number(state.activePerson.key)) {
state.activePerson.key = payload.msgs.key;
}
}
let msgs = messageList.msgs;
for (let j = msgs.length - 1; j >= 0; j--) {
if (msgs[j].msgKey && Number(payload.msgKey) === Number(msgs[j].msgKey)) {
if (payload.msgs && payload.success === 2) {
let url = msgs[j].content.msg_body.media_url;
let localExtras = msgs[j].content.msg_body.extras;
if (url) {
payload.msgs.content.msg_body.media_url = url;
}
if (localExtras && localExtras.businessCard) {
payload.msgs.content.msg_body.extras.media_url = localExtras.media_url;
payload.msgs.content.msg_body.extras.nickName = localExtras.nickName;
}
delete msgs[j].msg_id;
let from_name = payload.msgs.content.from_name;
let nickname = msgs[j].content.from_name;
msgs[j] = Object.assign({}, msgs[j], payload.msgs);
if (!from_name) {
msgs[j].content.from_name = nickname;
}
}
msgs[j].success = payload.success;
return;
}
}
}
}
}
// 删除本地的会话列表
function deleteConversationItem(state: ChatStore, payload) {
let itemKey = Number(payload.item.key);
for (let i = 0; i < state.conversation.length; i++) {
let conversationKey = Number(state.conversation[i].key);
if (conversationKey === itemKey ||
(state.conversation[i].name === payload.item.name &&
payload.item.type === 3 && state.conversation[i].type === 3)) {
state.conversation.splice(i, 1);
break;
}
}
const group = state.activePerson.type === 4 && payload.item.type === 4 &&
itemKey === Number(state.activePerson.key);
const single = state.activePerson.type === 3 && payload.item.type === 3 &&
payload.item.name === state.activePerson.name;
if (group || single) {
state.defaultPanelIsShow = true;
state.activePerson = {
key: '0',
name: '',
nickName: '',
activeIndex: -1,
noDisturb: false,
avatarUrl: '',
shield: false,
memo_name: '',
appkey: ''
};
}
}
// 转发消息
function transmitMessage(state: ChatStore, payload) {
payload.msgs.key = payload.select.key;
let flag1 = true;
let flag2 = true;
for (let a = 0; a < state.conversation.length; a++) {
const groupExist = payload.select.type === 4 && state.conversation[a].type === 4 &&
Number(state.conversation[a].key) === Number(payload.select.key);
const singleExist = payload.select.type === 3 && state.conversation[a].type === 3 &&
state.conversation[a].name === payload.select.name;
if (groupExist || singleExist) {
flag1 = false;
payload.select.conversation_time_show = 'today';
state.conversation[a].recentMsg = payload.msgs;
if (!state.conversation[a].extras || !state.conversation[a].extras.top_time_ms) {
let item = state.conversation.splice(a, 1);
filterTopConversation(state, item[0]);
}
break;
}
}
for (let messageList of state.messageList) {
const group = payload.select.type === 4 && messageList.type === 4 &&
Number(messageList.key) === Number(payload.select.key);
const single = payload.select.type === 3 && messageList.type === 3 &&
messageList.name === payload.select.name;
if (group || single) {
flag2 = false;
let msgs = messageList.msgs;
if (msgs.length === 0 ||
Util.fiveMinutes(msgs[msgs.length - 1].ctime_ms, payload.msgs.ctime_ms)) {
payload.msgs.time_show = 'today';
}
msgs.push(payload.msgs);
state.newMessage = payload.msgs;
break;
}
}
if (flag1 && payload.select.type === 3) {
payload.select.conversation_time_show = 'today';
payload.msgs.time_show = 'today';
payload.select.recentMsg = payload.msgs;
initConversation(state, payload.select);
filterTopConversation(state, payload.select);
if (flag2) {
state.messageList.push({
msgs: [payload.msgs],
type: 3,
name: payload.select.name,
appkey: payload.select.appkey || authPayload.appkey
});
}
state.newMessage = payload.msgs;
} else if (flag1 && payload.select.type === 4) {
payload.select.conversation_time_show = 'today';
payload.msgs.time_show = 'today';
payload.select.recentMsg = payload.msgs;
initConversation(state, payload.select);
filterTopConversation(state, payload.select);
if (flag2) {
state.messageList.push({
key: payload.msgs.key,
msgs: [payload.msgs],
type: 4
});
}
state.newMessage = payload.msgs;
}
// 更新imageViewer的数组
if (payload.msgs.content.msg_type === 'image') {
const isSingleMessage = payload.select.type === 3 && state.activePerson.type === 3 &&
payload.select.name === state.activePerson.name;
const isGroupMessage = payload.select.type === 4 && state.activePerson.type === 4 &&
Number(payload.select.key) === Number(state.activePerson.key);
if (isSingleMessage || isGroupMessage) {
state.imageViewer.push({
src: payload.msgs.content.msg_body.media_url,
width: payload.msgs.content.msg_body.width,
height: payload.msgs.content.msg_body.height,
msgKey: payload.msgs.msgKey
});
}
}
}
// 添加消息到消息面板
function addMessage(state: ChatStore, payload) {
// 接收到别人的消息添加到消息列表/同步自己发送的消息
if (payload.messages && payload.messages[0]) {
let message = payload.messages[0];
if (message.msg_type === 3) {
const isMySelf = message.content.from_id !== global.user;
message.content.name = isMySelf ? message.content.from_id : message.content.target_id;
message.content.nickName =
isMySelf ? message.content.from_name : message.content.target_name;
message.content.appkey =
isMySelf ? message.content.from_appkey : message.content.target_appkey;
} else {
message.content.name = message.content.from_id;
message.content.nickName = message.content.from_name;
message.content.appkey = message.content.from_appkey;
}
filterFriend(state, message.content);
filterNewMessage(state, payload, message);
let flag = false;
// 如果发送人在会话列表里
for (let a = 0; a < state.conversation.length; a++) {
const groupMsg = message.msg_type === 4 && state.conversation[a].type === 4 &&
Number(state.conversation[a].key) === Number(message.key);
const singleMsg = message.msg_type === 3 && state.conversation[a].type === 3 &&
state.conversation[a].name === message.content.name;
if (groupMsg || singleMsg) {
if (groupMsg && message.content.target_name === '') {
message.content.target_name = state.conversation[a].name;
}
const groupNoActive = message.msg_type === 4 &&
Number(state.activePerson.key) !== Number(message.key);
const singleNoActive = message.msg_type === 3 &&
state.activePerson.name !== message.content.name;
if (groupNoActive || singleNoActive) {
if (message.content.from_id !== global.user) {
if (!state.conversation[a].unreadNum) {
state.conversation[a].unreadNum = 1;
} else {
state.conversation[a].unreadNum++;
}
}
const atList = messageHasAtList(payload.messages[0].content.at_list);
if (atList !== '') {
state.conversation[a].atUser = atList;
}
}
flag = true;
if (state.conversation[a].key < 0) {
const oldKey = Number(state.conversation[a].key);
if (oldKey === Number(state.activePerson.key)) {
state.activePerson.key = message.key;
}
state.conversation[a].key = message.key;
for (let messageList of state.messageList) {
if (oldKey === Number(messageList.key)) {
messageList.key = message.key;
break;
}
}
}
let index = a;
if (!state.conversation[a].extras || !state.conversation[a].extras.top_time_ms) {
let item = state.conversation.splice(a, 1);
index = filterTopConversation(state, item[0]);
}
state.conversation[index].recentMsg = payload.messages[0];
payload.messages[0].conversation_time_show = 'today';
state.newMessageIsDisturb = state.conversation[index].noDisturb ? true : false;
break;
}
}
for (let messageList of state.messageList) {
const groupMsg = message.msg_type === 4 && messageList.type === 4 &&
Number(messageList.key) === Number(message.key);
const singleMsg = message.msg_type === 3 && messageList.type === 3 &&
messageList.name === message.content.name;
if (groupMsg || singleMsg) {
let msgs = messageList.msgs;
if (msgs.length === 0 ||
Util.fiveMinutes(msgs[msgs.length - 1].ctime_ms, message.ctime_ms)) {
payload.messages[0].time_show = 'today';
}
msgs.push(payload.messages[0]);
break;
}
}
// 如果发送人不在会话列表里
if (!flag) {
addMessageUserNoConversation(state, payload, message);
}
state.newMessage = payload.messages[0];
} else {
// 自己发消息将消息添加到消息列表
addMyselfMesssge(state, payload);
// 清空会话草稿标志
for (let conversation of state.conversation) {
const single = payload.active.type === 3 && conversation.type === 3 &&
payload.active.name === conversation.name;
const group = payload.active.type === 4 && conversation.type === 4 &&
Number(payload.active.key) === Number(conversation.key);
if (single || group) {
if (payload.msgs.content.msg_type === 'text') {
conversation.draft = '';
}
break;
}
}
}
}
// 添加自己发的消息到消息面板
function addMyselfMesssge(state: ChatStore, payload) {
const result = state.conversation.filter((item) => {
const single = item.type === 3 && payload.active.type === 3 &&
item.name === payload.active.name;
const group = item.type === 4 && payload.active.type === 4 &&
Number(item.key) === Number(payload.active.key);
return single || group;
});
if (result.length === 0) {
payload.active.extras = {};
payload.msgs.conversation_time_show = 'today';
payload.active.recentMsg = payload.msgs;
let flag = true;
for (let message of state.messageList) {
const group = payload.active.type === 4 && message.type === 4 &&
Number(payload.active.key) === Number(message.key);
const single = payload.active.type === 3 && message.type === 3 &&
payload.active.name === message.name;
if (group || single) {
message.msgs.push(payload.msgs);
flag = false;
break;
}
}
if (flag && payload.active.type === 3) {
state.messageList.push({
msgs: [payload.msgs],
type: 3,
name: payload.active.name,
appkey: payload.active.appkey || authPayload.appkey
});
} else if (flag && payload.active.type === 4) {
state.messageList.push({
msgs: [payload.msgs],
type: 4,
key: payload.active.key
});
}
filterTopConversation(state, payload.active);
} else {
// 更新imageViewer的数组
if (payload.msgs && payload.msgs.content.from_id === global.user
&& payload.msgs.content.msg_type === 'image') {
const single = payload.active.type === 3 && state.activePerson.type === 3 &&
payload.active.name === state.activePerson.name;
const group = payload.active.type === 4 && state.activePerson.type === 4 &&
Number(payload.active.key) === Number(state.activePerson.key);
if (single || group) {
state.imageViewer.push({
src: payload.msgs.content.msg_body.media_url,
width: payload.msgs.content.msg_body.width,
height: payload.msgs.content.msg_body.height,
msgKey: payload.msgs.msgKey
});
}
}
for (let messageList of state.messageList) {
const single = payload.active.type === 3 && messageList.type === 3 &&
messageList.name === payload.active.name;
const group = messageList.type === 4 && payload.active.type === 4 &&
Number(messageList.key) === Number(payload.key);
if (single || group) {
let msgs = messageList.msgs;
if (msgs.length === 0 ||
Util.fiveMinutes(msgs[msgs.length - 1].ctime_ms, payload.msgs.ctime_ms)) {
payload.msgs.time_show = 'today';
}
msgs.push(payload.msgs);
state.newMessage = payload.msgs;
break;
}
}
// 将当前会话放在第一位
for (let a = 0; a < state.conversation.length; a++) {
const group = payload.active.type === 4 && state.conversation[a].type === 4 &&
Number(state.conversation[a].key) === Number(payload.key);
const single = payload.active.type === 3 && state.conversation[a].type === 3 &&
state.conversation[a].name === payload.active.name;
if (group || single) {
payload.msgs.conversation_time_show = 'today';
if (payload.msgs.msg_type === 3) {
payload.msgs.unread_count = 1;
}
state.conversation[a].recentMsg = payload.msgs;
if (!state.conversation[a].extras || !state.conversation[a].extras.top_time_ms) {
let item = state.conversation.splice(a, 1);
filterTopConversation(state, item[0]);
}
break;
}
}
}
}
// 处理新消息
function filterNewMessage(state: ChatStore, payload, message) {
// 更新imageViewer的数组
const isGroupMessage = message.msg_type === 4 && state.activePerson.type === 4 &&
Number(message.key) === Number(state.activePerson.key);
const isSingleMessage = message.msg_type === 3 && state.activePerson.type === 3 &&
message.content.from_id === state.activePerson.name;
const isImage = message.content.msg_type === 'image';
if ((isGroupMessage || isSingleMessage) && isImage) {
state.imageViewer.push({
src: message.content.msg_body.media_url,
width: message.content.msg_body.width,
height: message.content.msg_body.height,
msg_id: message.msg_id
});
}
// 接收到语音初始化播放动画
const isVoice = message.content.msg_type === 'voice';
if (isVoice) {
payload.messages[0].content.playing = false;
payload.messages[0].content.havePlay = false;
payload.messages[0].content.load = 0;
}
// 接收到小视频初始化loading
const isVideo = message.content.msg_type === 'file' &&
message.content.msg_body.extras &&
message.content.msg_body.extras.video;
if (isVideo) {
payload.messages[0].content.load = 0;
payload.messages[0].content.range = 0;
}
}
// 新消息用户不在会话列表中
function addMessageUserNoConversation(state: ChatStore, payload, message) {
let msg;
let conversationItem;
if (message.msg_type === 3) {
msg = {
key: message.key,
msgs: [
message
],
draft: '',
content: message.content,
type: 3,
name: message.content.name,
appkey: message.content.appkey
};
conversationItem = {
avatar: '',
avatarUrl: message.content.avatarUrl,
key: message.key,
mtime: message.ctime_ms,
name: message.content.name,
nickName: message.content.nickName,
type: 3,
unreadNum: message.content.from_id !== global.user ? 1 : 0,
noDisturb: false,
extras: {}
};
for (let user of state.noDisturb.users) {
if (user.username === message.content.name) {
conversationItem.noDisturb = true;
state.newMessageIsDisturb = true;
break;
}
}
} else {
// 如果新消息没群名,从群列表中获取
if (!message.content.target_name || message.content.target_name.length === 0) {
for (let group of state.groupList) {
if (Number(group.gid) === Number(message.key)) {
message.content.target_name = group.name;
break;
}
}
}
msg = {
key: message.key,
msgs: [
message
],
draft: '',
content: message.content,
type: 4
};
let avatarUrl;
for (let group of state.groupList) {
if (Number(group.gid) === Number(message.key)) {
avatarUrl = group.avatarUrl;
break;
}
}
conversationItem = {
avatar: '',
avatarUrl: avatarUrl || '',
key: message.key,
mtime: message.ctime_ms,
name: message.content.target_name,
type: 4,
unreadNum: message.content.from_id !== global.user ? 1 : 0,
noDisturb: false,
extras: {}
};
for (let group of state.noDisturb.groups) {
if (Number(group.key) === Number(message.key)) {
conversationItem.noDisturb = true;
state.newMessageIsDisturb = true;
break;
}
}
}
if (!conversationItem.noDisturb) {
state.newMessageIsDisturb = false;
}
payload.messages[0].conversation_time_show = 'today';
payload.messages[0].time_show = 'today';
state.newMessage = msg;
state.messageList.push(msg);
const index = filterTopConversation(state, conversationItem);
state.conversation[index].recentMsg = payload.messages[0];
const atList = messageHasAtList(payload.messages[0].content.at_list);
if (atList !== '') {
state.conversation[index].atUser = atList;
}
}
// 添加会话列表中的@文本
function messageHasAtList(atList) {
let atUser = '';
if (atList && atList.length === 0) {
atUser = '@所有成员';
} else if (atList && atList.length > 0) {
for (let atItem of atList) {
if (atItem.username === global.user) {
atUser = '有人@我';
break;
}
}
}
return atUser;
}
// 搜索单聊或者好友
function searchSingleUser(state: ChatStore, payload) {
let singleArr = [];
// 查找最近联系人
for (let item of state.conversation) {
searchSingle(payload.keywords, singleArr, item);
}
// 查找好友
for (let item of state.friendList) {
searchSingle(payload.keywords, singleArr, item);
}
if (payload.result) {
const item = singleArr.filter((single) => {
return single.name === payload.result.name;
});
if (item.length === 0) {
singleArr.push(payload.result);
}
}
return singleArr;
}
// 搜索用户、群组
function searchUser(state: ChatStore, payload) {
if (payload === '') {
return {
result: {
groupArr: [],
singleArr: [],
roomArr: []
},
isSearch: false
};
}
let singleArr = [];
let groupArr = [];
// 查找最近联系人
for (let item of state.conversation) {
searchSingle(payload, singleArr, item);
}
// 查找好友
for (let item of state.friendList) {
searchSingle(payload, singleArr, item);
}
// 查找群组
for (let item of state.groupList) {
const existGroup = (item.name.toLowerCase().indexOf(payload.toLowerCase()) !== -1);
if (existGroup) {
groupArr.push(item);
}
}
return {
result: {
singleArr,
groupArr,
roomArr: []
},
isSearch: true
};
}
// 搜索单聊用户或好友
function searchSingle(payload, singleArr, item) {
const existMemoName = item.memo_name &&
item.memo_name.toLowerCase().indexOf(payload.toLowerCase()) !== -1;
const existNickName = item.nickName &&
item.nickName.toLowerCase().indexOf(payload.toLowerCase()) !== -1;
const existName = item.name &&
item.name.toLowerCase().indexOf(payload.toLowerCase()) !== -1;
const existSingle = item.type === 3;
const isExist = singleArr.filter((single) => {
return single.name === item.name;
});
if (isExist.length > 0) {
return;
}
if (existSingle && (existMemoName || existNickName || existName)) {
singleArr.push(item);
}
}
// 选择搜索的用户、发起单聊
function selectUserResult(state: ChatStore, payload, type?: string) {
if (payload.gid) {
payload.key = payload.gid;
}
let conversation = state.conversation;
let flag = false;
let index;
for (let i = 0; i < conversation.length; i++) {
const group = payload.type === 4 && conversation[i].type === 4 &&
Number(conversation[i].key) === Number(payload.key);
const single = payload.type === 3 && conversation[i].type === 3 &&
conversation[i].name === payload.name;
if (group || single) {
index = i;
payload.key = conversation[i].key;
if (!conversation[i].extras || !conversation[i].extras.top_time_ms) {
let item = conversation.splice(i, 1);
index = filterTopConversation(state, item[0]);
}
if (!conversation[index].name) {
conversation[index].name = payload.name;
conversation[index].unreadNum = 0;
}
flag = true;
break;
}
}
const result = state.messageList.filter((item) => {
const group = item.type === 4 && payload.type === 4 &&
Number(item.key) === Number(payload.key);
const single = payload.type === 3 && item.type === 3 && payload.name === item.name;
return group || single;
});
if (result.length === 0) {
if (payload.type === 3) {
state.messageList.push({
key: payload.key,
msgs: [],
type: 3,
name: payload.name,
appkey: payload.appkey || authPayload.appkey
});
} else if (payload.type === 4) {
state.messageList.push({
key: payload.key,
msgs: [],
type: 4
});
}
}
if (!flag) {
initConversation(state, payload);
if (result.length > 0 && result[0].msgs.length > 0) {
payload.recentMsg = result[0].msgs[result[0].msgs.length - 1];
}
filterTopConversation(state, payload);
}
if (type === 'search' && index) {
state.activePerson = Util.deepCopyObj(state.conversation[index]);
} else if (type === 'search') {
state.activePerson = Util.deepCopyObj(payload);
}
}
// 创建会话时初始化会话
function initConversation(state: ChatStore, payload) {
payload.extras = {};
if (payload.type === 3) {
const single = state.noDisturb.users.filter((item) => {
return payload.name === item.username;
});
if (single.length !== 0) {
payload.noDisturb = true;
}
} else if (payload.type === 4) {
const group = state.noDisturb.groups.filter((item) => {
return Number(payload.key) === Number(item.gid);
});
if (group.length !== 0) {
payload.noDisturb = true;
}
const shield = state.groupShield.filter((item) => {
return Number(item.gid) === Number(payload.key);
});
if (shield.length !== 0) {
payload.shield = true;
}
}
}
// 切换当前会话时,清空未读消息数目
function emptyUnreadNum(state: ChatStore, payload) {
state.readObj = [];
for (let item of state.conversation) {
const group = payload.type === 4 && item.type === 4 &&
Number(item.key) === Number(payload.key);
const single = payload.type === 3 && item.type === 3 && item.name === payload.name;
if (group || single) {
item.atUser = '';
if (item.unreadNum) {
item.unreadNum = 0;
}
break;
}
}
}
// 将会话插入到置顶会话之后
function filterTopConversation(state: ChatStore, item) {
let flag = true;
let index;
for (let i = 0; i < state.conversation.length; i++) {
if (!state.conversation[i].extras || !state.conversation[i].extras.top_time_ms) {
state.conversation.splice(i, 0, item);
index = i;
flag = false;
break;
}
}
if (flag) {
state.conversation.push(item);
index = state.conversation.length - 1;
}
return index;
}
// 添加群成员禁言事件
function addGroupMemberSilenceEvent(state: ChatStore, payload) {
changeGroupMemberSilence(state, payload, true, '被禁言');
}
// 取消群成员禁言事件
function deleteGroupMemberSilenceEvent(state: ChatStore, payload) {
changeGroupMemberSilence(state, payload, false, '被解除禁言');
}
// 切换群成员禁言
function changeGroupMemberSilence(state: ChatStore, payload, silence: boolean, text: string) {
for (let shield of state.groupShield) {
if (Number(shield.gid) === Number(payload.gid)) {
return;
}
}
for (let messageList of state.messageList) {
if (Number(payload.gid) === Number(messageList.key)) {
if (messageList.groupSetting && messageList.groupSetting.memberList) {
for (let user of payload.to_usernames) {
for (let member of messageList.groupSetting.memberList) {
if (member.username === user.username) {
member.keep_silence = silence;
break;
}
}
}
}
break;
}
}
for (let user of payload.to_usernames) {
let name = user.nickname || user.username;
for (let friend of state.friendList) {
if (friend.name === user.username) {
if (friend.memo_name) {
name = friend.memo_name;
}
break;
}
}
let msg = {
ctime_ms: payload.ctime_ms,
msg_type: 5,
content: {
msg_body: {
text: `${name} ${text}`
},
msg_type: 'event'
},
time_show: '',
conversation_time_show: Util.reducerDate(payload.ctime_ms)
};
let flag = false;
for (let i = 0; i < state.conversation.length; i++) {
if (state.conversation[i].type === 4 &&
Number(state.conversation[i].key) === Number(payload.gid)) {
state.conversation[i].recentMsg = msg;
let item = state.conversation.splice(i, 1)[0];
filterTopConversation(state, item);
flag = true;
for (let messageList of state.messageList) {
if (messageList.type === 4 &&
Number(messageList.key) === Number(payload.gid)) {
let msgs = messageList.msgs;
if (msgs.length > 0) {
if (Util.fiveMinutes(msgs[msgs.length - 1].ctime_ms,
payload.ctime_ms)) {
msg.time_show = Util.reducerDate(payload.ctime_ms);
}
} else {
msg.time_show = Util.reducerDate(payload.ctime_ms);
}
msgs.push(msg);
break;
}
}
break;
}
}
if (!flag) {
for (let group of state.groupList) {
if (Number(group.gid) === Number(payload.gid)) {
let conversation = Util.deepCopyObj(group);
for (let noDisturbGroup of state.noDisturb.groups) {
if (Number(noDisturbGroup.gid) === Number(payload.gid)) {
conversation.noDisturb = true;
break;
}
}
conversation.type = 4;
conversation.recentMsg = msg;
if (conversation.gid) {
conversation.key = conversation.gid;
}
filterTopConversation(state, conversation);
let flag2 = false;
for (let messageList of state.messageList) {
if (messageList.type === 4 &&
Number(messageList.key) === Number(payload.gid)) {
let msgs = messageList.msgs;
if (msgs.length > 0) {
if (Util.fiveMinutes(msgs[msgs.length - 1].ctime_ms,
payload.ctime_ms)) {
msg.time_show = Util.reducerDate(payload.ctime_ms);
}
} else {
msg.time_show = Util.reducerDate(payload.ctime_ms);
}
flag2 = true;
msgs.push(msg);
break;
}
}
if (!flag2) {
msg.time_show = Util.reducerDate(payload.ctime_ms);
state.messageList.push({
key: payload.gid,
msgs: [
msg
],
type: 4
});
}
break;
}
}
}
}
}
// 更新会话的未读总数
function conversationUnreadNum(state: ChatStore) {
let count = 0;
for (let conversation of state.conversation) {
if (!conversation.noDisturb && conversation.unreadNum) {
count += conversation.unreadNum;
}
}
state.conversationUnreadNum = count;
}
// 给入群邀请的邀请者和被邀请者添加备注名
function filterInvitationEventMeMoName(state: ChatStore, payload) {
for (let friend of state.friendList) {
if (payload.from_username === friend.username && payload.from_appkey === friend.appkey) {
if (friend.memo_name) {
payload.from_memo_name = friend.memo_name;
}
break;
}
}
for (let user of payload.to_usernames) {
for (let friend of state.friendList) {
if (user.username === friend.username && user.appkey === friend.appkey) {
if (friend.memo_name) {
user.memo_name = friend.memo_name;
}
break;
}
}
}
} | the_stack |
import {
parsedView,
syncingProxy,
deepSyncingProxy,
transformingCache,
makeListenerProxy,
deepProxy,
} from './parse-tools'
const deepClone = object => JSON.parse(JSON.stringify(object))
describe('parsedView', () => {
const exampleString = 'from "abc" to "xyz".'
// Hard-code the parse function to give us the quoted pieces in the example string.
const parse = string => [
{ token: 'abc', index: 6 },
{ token: 'xyz', index: 15 },
]
test('should look like the output of parse()', () => {
const view = parsedView(parse)(exampleString)
expect([...view]).toEqual([
{ token: 'abc', index: 6 },
{ token: 'xyz', index: 15 },
])
})
test('should have toString() return the input string', () => {
const view = parsedView(parse)(exampleString)
expect(view.toString()).toEqual(exampleString)
})
test('should reflect token modifications in the value of toString()', () => {
const view = parsedView(parse)(exampleString)
view[1].token = 'æøå'
expect(view.toString()).toEqual('from "abc" to "æøå".')
})
})
describe('syncingProxy', () => {
let currentObject
const getCurrentObject = jest.fn(() => deepClone(currentObject))
const setCurrentObject = jest.fn(value => { currentObject = deepClone(value) })
beforeEach(() => {
jest.clearAllMocks()
})
test('should mirror the current value of get()', () => {
currentObject = {}
const proxy = syncingProxy({ get: getCurrentObject, set: setCurrentObject })
currentObject = { v: 9 }
expect(proxy.v).toEqual(9)
currentObject = { v: 10 }
expect(proxy.v).toEqual(10)
})
test('should write back changes using set()', () => {
currentObject = {}
const proxy = syncingProxy({ get: getCurrentObject, set: setCurrentObject })
proxy.v = 4
expect(currentObject.v).toEqual(4)
})
test('should work with e.g. an array', () => {
// The proxy needs to be created with an Array as initial target (so the property descriptor
// for '.length' is correct).
currentObject = [1, 2, 3]
const proxy = syncingProxy({ get: getCurrentObject, set: setCurrentObject })
proxy.push(4) // Would fail if the initial target was not an Array.
expect(proxy[3]).toEqual(4)
})
})
describe('deepSyncingProxy', () => {
let currentObject
const getCurrentObject = jest.fn(() => deepClone(currentObject))
const setCurrentObject = jest.fn(value => { currentObject = deepClone(value) })
beforeEach(() => {
jest.clearAllMocks()
})
test('should deeply mirror the current value of get()', () => {
currentObject = { t: { u: { v: 2 } } }
const proxy = deepSyncingProxy({ get: getCurrentObject, set: setCurrentObject })
const innerProxy = proxy.t.u
currentObject = { t: { u: { v: 6 } } }
expect(innerProxy.v).toEqual(6)
})
test('should run set() when an inner object is mutated.', () => {
currentObject = { t: { u: { v: 2 } } }
const proxy = deepSyncingProxy({ get: getCurrentObject, set: setCurrentObject })
const innerProxy = proxy.t.u
innerProxy.v = 3
expect(innerProxy.v).toEqual(3)
expect(currentObject.t.u.v).toEqual(3)
})
test('by default, should not run set() after non-mutating operations', () => {
currentObject = { t: { u: { v: 2 } } }
const proxy = deepSyncingProxy({ get: getCurrentObject, set: setCurrentObject })
const v = proxy.t.u.v
expect(setCurrentObject).not.toHaveBeenCalled()
})
test('with alwaysSet === true, should run set() also after non-mutating operations', () => {
currentObject = { t: { u: { v: 2 } } }
const proxy = deepSyncingProxy({
get: getCurrentObject,
set: setCurrentObject,
alwaysSet: true,
})
const v = proxy.t.u
expect(setCurrentObject).toHaveBeenCalled()
})
test('should throw a TypeError when accessing a member object that has disappeared', () => {
currentObject = { t: { u: { v: 2 } } }
const proxy = deepSyncingProxy({ get: getCurrentObject, set: setCurrentObject })
const innerProxy = proxy.t.u
currentObject = { t: { u: null } }
expect(() => innerProxy.v).toThrow(
TypeError('Expected get().t.u to be an object, but get().t.u is null.')
)
currentObject = { t: { u: 98 } } // A primitive value cannot be proxied either.
expect(() => innerProxy.v).toThrow(
TypeError('Expected get().t.u to be an object, but get().t.u is 98.')
)
currentObject = {}
expect(() => innerProxy.v).toThrow(
TypeError('Expected get().t.u to be an object, but get().t is undefined.')
)
currentObject = null
expect(() => innerProxy.v).toThrow(
TypeError('Expected get().t.u to be an object, but get() is null.')
)
})
})
describe('transformingCache', () => {
// For testing, we create a cache that turns a JSON string x into an object, and vice versa.
let x, cache
const getX = jest.fn(() => x)
const setX = jest.fn(value => { x = value })
const transform = jest.fn(x => JSON.parse(x))
const untransform = jest.fn(obj => JSON.stringify(obj))
beforeEach(() => {
jest.clearAllMocks()
x = undefined
cache = transformingCache({ get: getX, set: setX, transform, untransform })
})
test('should get the transformed value', () => {
x = '{"b":2}'
expect(cache.get()).toEqual({ b: 2 })
})
test('should set the untransformed value', () => {
cache.set({ c: 3 })
expect(x).toEqual('{"c":3}')
})
test('should get cached object on get+get', () => {
x = '{}'
const object1 = cache.get()
const object2 = cache.get()
expect(object1).toBe(object2) // Note we test for identity equality (===) here
})
test('should not get stale cache on get+<change>+get', () => {
x = '{}'
cache.get()
x = '{"m":0}'
const object = cache.get()
expect(object).toEqual({ m: 0 })
})
test('should get cached object on set+get', () => {
const object = {}
cache.set(object)
expect(cache.get()).toBe(object) // Note we test for identity equality (===) here
})
test('should not get stale cache on set+<change>+get', () => {
cache.set({ l: 3 })
x = '{"q":8}'
const object = cache.get()
expect(object).toEqual({ q: 8 })
})
test('should omit setX() on get+set', () => {
x = '{"z":45}'
const object = cache.get()
cache.set(object)
expect(setX).not.toHaveBeenCalled()
})
test('should omit setX() when untransformed value is equal', () => {
x = '{"w":37}'
cache.set({w: 37})
expect(setX).not.toHaveBeenCalled()
})
test('should not omit setX on get+<change>+set', () => {
x = '{"n":20}'
const object = cache.get()
x = '{"r":1}'
cache.set(object)
expect(setX).toHaveBeenCalled()
})
test('should not check staleness on get+<change>+set with trustCache', () => {
// Note: this is not what you usually want to do.
x = '{"k":76}'
const object = cache.get()
x = '{"c":30}'
cache.set(object, { trustCache: true })
expect(getX).toHaveBeenCalledTimes(1)
expect(setX).not.toHaveBeenCalled()
expect(x).toEqual('{"c":30}')
})
test('should omit second setX() on set+set', () => {
const object = { a: 123 }
cache.set(object)
cache.set(object)
expect(setX).toHaveBeenCalledTimes(1)
})
test('should not omit second setX() on set+<change>+set', () => {
const object = { t: 10 }
cache.set(object)
x = '{"t":30}'
cache.set(object)
expect(setX).toHaveBeenCalledTimes(2)
expect(x).toEqual('{"t":10}')
})
test('should not check staleness on set+<change>+set with trustCache', () => {
// Note: this is what you usually want to avoid.
const object = { t: 10 }
cache.set(object)
x = '{"t":30}'
cache.set(object, { trustCache: true })
expect(getX).toHaveBeenCalledTimes(1) // only in the first cache.set()
expect(setX).toHaveBeenCalledTimes(1) // only in the first cache.set()
expect(x).toEqual('{"t":30}')
})
test('should use custom equality comparison when getting', () => {
cache = transformingCache({
get: getX, set: setX, transform, untransform,
// Ignore whitespace when comparing the JSON strings.
isEqual: (a, b) => a.replace(/\s/g, '') === b.replace(/\s/g, ''),
})
x = '{"f":3}'
const object1 = cache.get()
x = '{"f" : 3}'
const object2 = cache.get()
expect(object1).toBe(object2) // Note we test for identity equality (===) here
})
test('should use custom equality comparison when setting', () => {
cache = transformingCache({
get: getX, set: setX, transform, untransform,
// Ignore whitespace when comparing the JSON strings.
isEqual: (a, b) => a.replace(/\s/g, '') === b.replace(/\s/g, ''),
})
x = '{"g" : 94}'
cache.set({g: 94}) // will transform into '{"g":94}'
expect(setX).not.toHaveBeenCalled()
})
})
describe('makeListenerProxy', () => {
test('should call before() and after() before and after an operation, respectively', () => {
// expect().toHaveReturnedWith() seems to have disappeared from jest, hence using variables.
let xBefore, xAfter
const before = jest.fn((method, [target, ...args]) => { xBefore = target.x })
const after = jest.fn((method, [target, ...args]) => { xAfter = target.x })
const object = { x: 1, y: 2 }
const proxy = makeListenerProxy<typeof object>(before, after)(object)
proxy.x = 4
expect(xBefore).toEqual(1)
expect(xAfter).toEqual(4)
expect(object).toEqual({ x: 4, y: 2 })
})
})
describe('deepProxy', () => {
// A simple proxy creator that multiplies every set value by ten.
const bigFish = object => new Proxy(object, {
set: (target, property, value) => {
target[property] = value * 10
return true
},
})
test('should wrap member objects using the same proxy creator', () => {
const object = { x: 1, innerObject: { y: 2 } }
const proxy = deepProxy(bigFish)(object)
proxy.x = 3
proxy.innerObject.y = 4
expect(object).toEqual({ x: 30, innerObject: { y: 40 } })
})
test('should recursively wrap member objects using the same proxy creator', () => {
const object = { x: 1, innerObject: { y: { z: 2 } } }
const proxy = deepProxy(bigFish)(object)
proxy.innerObject.y.z = 5
expect(object).toEqual({ x: 1, innerObject: { y: { z: 50 } } })
})
test('should memoize proxies for inner objects', () => {
const object = { x: 1, innerObject: { y: 2 } }
const proxy = deepProxy(bigFish)(object)
const innerProxy1 = proxy.innerObject
const innerProxy2 = proxy.innerObject
expect(innerProxy1).toBe(innerProxy2)
})
test("should pass the sub-object's path to the proxy creator", () => {
const countOccurrences = (string, substring) => string.split(substring).length - 1
// Alternatingly wraps or does not wrap inner objects.
const proxyCreator = (object, path) => {
if (countOccurrences(path, '.') % 2 === 0) {
return bigFish(object)
} else {
return object // no proxy.
}
}
const object = { inner1: { inner2: { inner3: {} } } }
const proxy = deepProxy(proxyCreator)(object)
proxy.v = 1
proxy.inner1.v = 2
proxy.inner1.inner2.v = 3
proxy.inner1.inner2.inner3.v = 4
expect(object).toEqual({ v: 10, inner1: { v: 2, inner2: { v: 30, inner3: { v: 4 } } } })
})
}) | the_stack |
import EventEmitter = NodeJS.EventEmitter;
interface NodeMpvOptions {
// Print debug lines
debug?: boolean;
// Print more lines
verbose?: boolean;
// Specify socket
socket?: string;
// Don't open video display
audio_only?: boolean;
// Auto-restart on a crash
auto_restart?: boolean;
// Time update for timeposition event
time_update?: number;
// Path to mpv binary
binary?: string;
}
/*interface NodeMpvError {
}*/
// these are the emitted events
type EventNames =
| "crashed"
| "getrequest"
| "seek"
| "started"
| "stopped"
| "paused"
| "resumed"
| "status"
| "timeposition"
| "quit";
type VoidCallback = () => void;
type VoidCallbackWithData<ArgType> = (arg: ArgType) => void;
type VoidCallbackWithData2<ArgType, ArgType2> = (
arg: ArgType,
arg2: ArgType2
) => void;
type LoadMode = "replace" | "append";
type MediaLoadMode = LoadMode | "append-play";
type AudioFlag = "select" | "auto" | "cached";
type SeekMode = "relative" | "absolute";
type RepeatMode = number | "inf" | "no";
type PlaylistMode = "weak" | "force";
interface TimePosition {
start: number;
end: number;
}
type StatusObjectProperties =
| "mute"
| "pause"
| "duration"
| "volume"
| "filename"
| "path"
| "media-title"
| "playlist-pos"
| "playlist-count"
| "loop"
| "fullscreen"
| "sub-visibility";
interface StatusObject {
property: StatusObjectProperties;
value: string | number | boolean;
}
type EventListenerArgs<EventName extends EventNames> = [
EventName,
VoidCallback
];
type EventListenerArgsWithData<EventName extends EventNames, DataType> = [
EventName,
VoidCallbackWithData<DataType>
];
type EventListenerArgsWithMultipleData<
EventName extends EventNames,
DataType,
DataType1
> = [EventName, VoidCallbackWithData2<DataType, DataType1>];
export default class NodeMpv implements EventEmitter {
/**
* Listen to certain events which are emitted after any kind of
* status change of mpv player.
* @param args
* @see for Events https://github.com/j-holub/Node-MPV#events
*/
addListener(...args: EventListenerArgs<"crashed">): this;
addListener(
...args: EventListenerArgsWithMultipleData<"getrequest", string, any>
): this;
addListener(...args: EventListenerArgs<"paused">): this;
addListener(...args: EventListenerArgs<"quit">): this;
addListener(...args: EventListenerArgs<"resumed">): this;
addListener(...args: EventListenerArgsWithData<"seek", TimePosition>): this;
addListener(...args: EventListenerArgs<"started">): this;
addListener(...args: EventListenerArgsWithData<"status", StatusObject>): this;
addListener(...args: EventListenerArgs<"stopped">): this;
addListener(...args: EventListenerArgsWithData<"timeposition", number>): this;
/**
* Listen to certain events which are emitted after any kind of
* status change of mpv player
* @param args
* @see for Events https://github.com/j-holub/Node-MPV#events
*/
on(...args: EventListenerArgs<"crashed">): this;
on(
...args: EventListenerArgsWithMultipleData<"getrequest", string, any>
): this;
on(...args: EventListenerArgs<"paused">): this;
on(...args: EventListenerArgs<"quit">): this;
on(...args: EventListenerArgs<"resumed">): this;
on(...args: EventListenerArgsWithData<"seek", TimePosition>): this;
on(...args: EventListenerArgs<"started">): this;
on(...args: EventListenerArgsWithData<"status", StatusObject>): this;
on(...args: EventListenerArgs<"stopped">): this;
on(...args: EventListenerArgsWithData<"timeposition", number>): this;
/**
* Listen to certain events which are emitted after any kind of
* status change of mpv player
* @param args
* @see for Events https://github.com/j-holub/Node-MPV#events
*/
once(...args: EventListenerArgs<"crashed">): this;
once(
...args: EventListenerArgsWithMultipleData<"getrequest", string, any>
): this;
once(...args: EventListenerArgs<"paused">): this;
once(...args: EventListenerArgs<"quit">): this;
once(...args: EventListenerArgs<"resumed">): this;
once(...args: EventListenerArgsWithData<"seek", TimePosition>): this;
once(...args: EventListenerArgs<"started">): this;
once(...args: EventListenerArgsWithData<"status", StatusObject>): this;
once(...args: EventListenerArgs<"stopped">): this;
once(...args: EventListenerArgsWithData<"timeposition", number>): this;
/**
* Remove listener that is listening to the provided event `eventName`
* @param args
*/
off(...args: EventListenerArgs<"crashed">): this;
off(
...args: EventListenerArgsWithMultipleData<"getrequest", string, any>
): this;
off(...args: EventListenerArgs<"paused">): this;
off(...args: EventListenerArgs<"quit">): this;
off(...args: EventListenerArgs<"resumed">): this;
off(...args: EventListenerArgsWithData<"seek", TimePosition>): this;
off(...args: EventListenerArgs<"started">): this;
off(...args: EventListenerArgsWithData<"status", StatusObject>): this;
off(...args: EventListenerArgs<"stopped">): this;
off(...args: EventListenerArgsWithData<"timeposition", number>): this;
/**
* Remove listener that is listening to the provided event `eventName`
* @param args
*/
removeListener(...args: EventListenerArgs<"crashed">): this;
removeListener(
...args: EventListenerArgsWithMultipleData<"getrequest", string, any>
): this;
removeListener(...args: EventListenerArgs<"paused">): this;
removeListener(...args: EventListenerArgs<"quit">): this;
removeListener(...args: EventListenerArgs<"resumed">): this;
removeListener(
...args: EventListenerArgsWithData<"seek", TimePosition>
): this;
removeListener(...args: EventListenerArgs<"started">): this;
removeListener(
...args: EventListenerArgsWithData<"status", StatusObject>
): this;
removeListener(...args: EventListenerArgs<"stopped">): this;
removeListener(
...args: EventListenerArgsWithData<"timeposition", number>
): this;
/**
* Removes all listeners listening to a particular event `eventName`
* @param {EventNames?} event - Event names
*/
removeAllListeners(event?: EventNames): this;
setMaxListeners(n: number): this;
getMaxListeners(): number;
listeners(event: EventNames): Function[];
rawListeners(event: EventNames): Function[];
emit(event: EventNames, ...args: any[]): boolean;
listenerCount(event: EventNames): number;
// Added in Node 6...
prependListener(...args: EventListenerArgs<"crashed">): this;
prependListener(
...args: EventListenerArgsWithMultipleData<"getrequest", string, any>
): this;
prependListener(...args: EventListenerArgs<"paused">): this;
prependListener(...args: EventListenerArgs<"quit">): this;
prependListener(...args: EventListenerArgs<"resumed">): this;
prependListener(
...args: EventListenerArgsWithData<"seek", TimePosition>
): this;
prependListener(...args: EventListenerArgs<"started">): this;
prependListener(
...args: EventListenerArgsWithData<"status", StatusObject>
): this;
prependListener(...args: EventListenerArgs<"stopped">): this;
prependListener(
...args: EventListenerArgsWithData<"timeposition", number>
): this;
prependOnceListener(...args: EventListenerArgs<"crashed">): this;
prependOnceListener(
...args: EventListenerArgsWithMultipleData<"getrequest", string, any>
): this;
prependOnceListener(...args: EventListenerArgs<"paused">): this;
prependOnceListener(...args: EventListenerArgs<"quit">): this;
prependOnceListener(...args: EventListenerArgs<"resumed">): this;
prependOnceListener(
...args: EventListenerArgsWithData<"seek", TimePosition>
): this;
prependOnceListener(...args: EventListenerArgs<"started">): this;
prependOnceListener(
...args: EventListenerArgsWithData<"status", StatusObject>
): this;
prependOnceListener(...args: EventListenerArgs<"stopped">): this;
prependOnceListener(
...args: EventListenerArgsWithData<"timeposition", number>
): this;
eventNames(): Array<string | symbol>;
/**
* A mpv wrapper for node
*
* @param options - Tweak NodeMPV behaviour
* @param mpv_args - Arrays of CLI options to pass to mpv. IPC options are automatically appended.
*/
constructor(options?: NodeMpvOptions, mpv_args?: string[]);
/**
* Loads a file into MPV
*
* @param source - Path to the media file
* @param mode
* `replace`: replace the current media
*
* `append`: Append at the end of the playlist
*
* `append-play`: Append after the current song
* @param options - Options formatted as option=label
*/
load(source: string, mode?: MediaLoadMode, options?: string[]): Promise<void>;
// https://github.com/j-holub/Node-MPV/blob/master/lib/mpv/_audio.js
/**
* Add an audio track to the media file
*
* @param file - Path to the audio track
* @param flag - Flag to use (select, auto, cached)
* @param title - Title in OSD/OSC
* @param lang - Language
*/
addAudioTrack(
file: string,
flag?: AudioFlag,
title?: string,
lang?: string
): Promise<void>;
/**
* Remove an audio track based on its id.
*
* @param id - ID of the audio track to remove
*/
removeAudioTrack(id: number): Promise<void>;
/**
* Select an audio track based on its id.
*
* @param id - ID of the audio track to select
*/
selectAudioTrack(id: number): Promise<void>;
/**
* Cycles through the audio track
*/
cycleAudioTracks(): Promise<void>;
/**
* Adjust audio timing
* @param seconds - Delay in seconds
*/
adjustAudioTiming(seconds: number): Promise<void>;
/**
* Set playback speed
* @param factor - 0.1 - 100: percentage of playback speed
*/
speed(factor: number): Promise<void>;
// https://github.com/j-holub/Node-MPV/blob/master/lib/mpv/_controls.js
/**
* Toggle play/pause
*/
togglePause(): Promise<void>;
/**
* Pauses playback
*/
pause(): Promise<void>;
/**
* Resumes playback
*/
resume(): Promise<void>;
/**
* Play the file in playlist
*/
play(): Promise<void>;
/**
* Stop playback immediately
*/
stop(): Promise<void>;
/**
* Set volume
*
* @param volume
*/
volume(volume: number): Promise<void>;
/**
* Increase/Decrease volume
*
* @param volume
*/
adjustVolume(volume: number): Promise<void>;
/**
* Mute
*
* @param set - setMute, if not specified, cycles
*/
mute(set?: boolean): Promise<void>;
/**
* Seek
*
* @param seconds - Seconds
* @param mode - Relative, absolute
* @see for info about seek https://mpv.io/manual/stable/#command-interface-seek-%3Ctarget%3E-[%3Cflags%3E]
*/
seek(seconds: number, mode?: SeekMode): Promise<void>;
/**
* Shorthand for absolute seek
*
* @param seconds - Seconds
*/
goToPosition(seconds: number): Promise<void>;
/**
* Set loop mode for current file
*
* @param times - either a number of loop iterations, 'inf' for infinite loop or 'no' to disable loop.
* If it's not specified, the property will cycle through inf and no.
*/
loop(times?: RepeatMode): Promise<void>;
// https://github.com/j-holub/Node-MPV/blob/master/lib/mpv/_commands.js
// List of mpv properties are available here: https://mpv.io/manual/stable/#property-list
/**
* Retrieve a property
*
* @param property
*/
getProperty(property: string): Promise<string>;
/**
* Set a property
*
* @param property
* @param value
*/
setProperty(property: string, value: any): Promise<void>;
/**
* Set a set of properties
*
* @param properties - {property1: value1, property2: value2}
*/
setMultipleProperties(properties: object): Promise<void>;
/**
* Add value to a property (only on number properties)
*
* @param property
* @param value
*/
addProperty(property: string, value: number): Promise<void>;
/**
* Multiply a property by value (only on number properties)
*
* @param property
* @param value
*/
multiplyProperty(property: string, value: number): Promise<void>;
/**
* Cycle through different modes of a property (boolean, enum)
*
* @param property
*/
cycleProperty(property: string): Promise<void>;
/**
* Send a custom command to mpv
*
* @param command Command name
* @param args Array of arguments
*/
command(command: string, args: string[]): Promise<void>;
/**
* Send a custom payload to mpv
*
* @param command the JSON command to send to mpv
*/
commandJSON(command: object): Promise<void>;
/**
* Send a custom payload to mpv (no JSON encode)
*
* @param command the JSON encoded command to send to mpv
*/
freeCommand(command: string): Promise<void>;
/**
* Observe a property
* You can receive events with the 'status' event
*
* @param property The property to observe
*/
observeProperty(property: string): any;
/**
* Unobserve a property
*
* @param property
*/
unobserveProperty(property: string): any;
// https://github.com/j-holub/Node-MPV/blob/master/lib/mpv/_information.js
/**
* Returns the mute status of mpv
*/
isMuted(): Promise<boolean>;
/**
* Returns the pause status of mpv
*/
isPaused(): Promise<boolean>;
/**
* Returns the seekable property of the loaded media
* Some medias are not seekable (livestream, unbuffered media)
*/
isSeekable(): Promise<boolean>;
/**
* Retrieve the duration of the loaded media
*/
getDuration(): Promise<number>;
/**
* Retrieve the current time position of the loaded media
*/
getTimePosition(): Promise<number>;
/**
* Retrieve the current time position (in percentage) of the loaded media
*/
getPercentPosition(): Promise<number>;
/**
* Retrieve the time remaining of the loaded media
*/
getTimeRemaining(): Promise<number>;
/**
* Retrieve the metadata of the loaded media
*/
getMetadata(): Promise<object>;
/**
* Retrieve the title of the loaded media
*/
getTitle(): Promise<string>;
/**
* Retrieve the artist of the loaded media
*/
getArtist(): Promise<string>;
/**
* Retrieve the album of the loaded media
*/
getAlbum(): Promise<string>;
/**
* Retrieve the year of the loaded media
*/
getYear(): Promise<number>;
/**
* Retrieve the filename of the loaded media
*
* @param format 'stripped' remove the extension, default to 'full'
*/
getFilename(format?: "full" | "stripped"): Promise<string>;
// https://github.com/j-holub/Node-MPV/blob/master/lib/mpv/_playlist.js
/**
* Load a playlist file
*
* @param playlist Path to the playlist file
* @param mode 'append' adds the playlist to the existing one. Defaults to 'replace'
*/
loadPlaylist(playlist: string, mode?: LoadMode): Promise<void>;
/**
* Add a song to the playlist
*
* @param source File path of media
* @param mode
* replace: replace the current media
* append: Append at the end of the playlist
* append-play: Append after the current song
* @param options
*/
append(
source: string,
mode?: MediaLoadMode,
options?: string[]
): Promise<void>;
/**
* Load next element in playlist
*
* @param mode - 'force' may go into an undefined index of the playlist
*/
next(mode?: PlaylistMode): Promise<void>;
/**
* Load previous element in playlist
*
* @param mode - 'force' may go into an undefined index of the playlist
*/
prev(mode?: PlaylistMode): Promise<void>;
/**
* Jump to position in playlist
*
* @param position
*/
jump(position: number): Promise<void>;
/**
* Empty the playlist
*/
clearPlaylist(): Promise<void>;
/**
*
* @param index
*/
playlistRemove(index: number): Promise<void>;
/**
*
* @param index1
* @param index2
*/
playlistMove(index1: number, index2: number): Promise<void>;
/**
*
*/
shuffle(): Promise<void>;
/**
*
*/
getPlaylistSize(): Promise<number>;
/**
*
*/
getPlaylistPosition(): Promise<number>;
/**
*
*/
getPlaylistPosition1(): Promise<number>;
/**
* Set loop mode for playlist
*
* @param times - either a number of loop iterations, 'inf' for infinite loop or 'no' to disable loop.
* If it's not specified, the property will cycle through inf and no.
*/
loopPlaylist(times?: RepeatMode): Promise<void>;
// https://github.com/j-holub/Node-MPV/blob/master/lib/mpv/_startStop.js
/**
* Starts mpv, by spawning a child process or by attaching to existing socket
*/
start(): Promise<void>;
/**
* Closes mpv
*
* [Important!] Calling method `quit` doesn't trigger the event `quit`
*/
quit(): Promise<void>;
/**
* Returns the status of mpv
*/
isRunning(): boolean;
// https://github.com/j-holub/Node-MPV/blob/master/lib/mpv/_subtitle.js
/**
* Loads a subtitle file into the current media file
*
* @param file Path to the subtitle file
* @param flag
* Select: Select the loaded file
* Auto: Let mpv decide
* Cached: Don't select the loaded file
* @param title Title to show in OSD/OSC
* @param lang Language of the subtitles
*/
addSubtitles(
file: string,
flag?: "select" | "auto" | "cached",
title?: string,
lang?: string
): Promise<void>;
/**
* Remove subtitles
*
* @param id Index of subtitles to delete
*/
removeSubtitles(id: number): Promise<void>;
/**
* Cycle through available subtitles
*/
cycleSubtitles(): Promise<void>;
/**
* Select subtitles by its id
*
* @param id
*/
selectSubtitles(id: number): Promise<void>;
/**
* Toggle subtitles visibility
*/
toggleSubtitleVisibility(): Promise<void>;
/**
* Show the subtitles on the screen
*/
showSubtitles(): Promise<void>;
/**
* Hide the subtitles on the screen
*/
hideSubtitles(): Promise<void>;
/**
* Adjust the subtitles offset to seconds
*
* @param seconds Offset to apply in seconds
*/
adjustSubtitleTiming(seconds: number): Promise<void>;
/**
* Seek based on subtitles lines
*
* @param lines
*/
subtitleSeek(lines: number): Promise<void>;
/**
* Scale the font of subtitles based on scale
*
* @param scale
*/
subtitleScale(scale: number): Promise<void>;
/**
* Show a text using ASS renderer
*
* @param ass an ass string
* @param duration duration in seconds
* @param position ASS alignment
*/
displayASS(ass: string, duration: number, position?: number): Promise<void>;
// https://github.com/j-holub/Node-MPV/blob/master/lib/mpv/_video.js
/**
* Enter fullscreen
*/
fullscreen(): Promise<void>;
/**
* Leave fullscreen
*/
leaveFullscreen(): Promise<void>;
/**
* Toggle fullscreen
*/
toggleFullscreen(): Promise<void>;
/**
* Take a screenshot
*
* @param file
* @param option
* Subtitles: show subtitles
* Video: hide subtitles/osd/osc
* Window: Take the screen at the size of the window
*/
screenshot(
file: string,
option: "subtitles" | "video" | "window"
): Promise<void>;
/**
* Rotate the video
*
* @param degrees
*/
rotateVideo(degrees: number): Promise<void>;
/**
* Zoom the video, 0 means no zoom, 1 means x2
*
* @param factor
*/
zoomVideo(factor: number): Promise<void>;
/**
* Set Brightness
*
* @param value
*/
brightness(value: number): Promise<void>;
/**
* Set Contrast
*
* @param value
*/
contrast(value: number): Promise<void>;
/**
* Set saturation
*
* @param value
*/
saturation(value: number): Promise<void>;
/**
* Set gamme on media
*
* @param value
*/
gamma(value: number): Promise<void>;
/**
* Set Hue
*
* @param value
*/
hue(value: number): Promise<void>;
} | the_stack |
import App from "../app";
import {pubsub} from "../helpers/subscriptionManager";
import * as Classes from "../classes";
import {capitalCase} from "change-case";
import uuid from "uuid";
// id always represents the ID of the sensor system
App.on("addSensorsArray", ({simulatorId, domain}) => {
const system = new Classes.Sensors({simulatorId, domain});
App.systems.push(system);
pubsub.publish(
"sensorsUpdate",
App.systems.filter(s => s.type === "Sensors"),
);
});
App.on("removedSensorsArray", ({id}) => {});
App.on("sensorScanRequest", ({id, request}) => {
const system = App.systems.find(sys => sys.id === id);
pubsub.publish("notify", {
id: uuid.v4(),
simulatorId: system.simulatorId,
type: `${capitalCase(system.domain)} Sensors`,
station: "Core",
title: `${capitalCase(system.domain)} Scan`,
body: request,
color: "info",
});
App.handleEvent(
{
simulatorId: system.simulatorId,
component: "SensorsCore",
title: `${capitalCase(system.domain)} Scan`,
body: request,
color: "info",
},
"addCoreFeed",
);
system.scanRequested(request);
pubsub.publish(
"sensorsUpdate",
App.systems.filter(s => s.type === "Sensors"),
);
if (system.training) {
setTimeout(() => {
App.handleEvent(
{id, result: "None Detected (Training Mode)"},
"sensorScanResult",
{clientId: "training", simulatorId: system.simulatorId},
);
}, 5000);
}
});
App.on("sensorScanResult", ({id, simulatorId, domain = "external", result}) => {
const system = App.systems.find(
sys =>
sys.id === id ||
(sys.simulatorId === simulatorId &&
sys.domain === domain &&
sys.class === "Sensors"),
);
if (!system) return;
system.scanResulted(result);
const simulator = App.simulators.find(s => s.id === system.simulatorId);
const stations = simulator.stations.filter(s =>
s.cards.find(
c =>
c.component ===
(system.domain === "external" ? "SensorScans" : "SecurityScans"),
),
);
stations.forEach(s => {
pubsub.publish("notify", {
id: uuid.v4(),
simulatorId: system.simulatorId,
station: s.name,
title: `Sensor Scan Answered`,
body: result,
color: "info",
relevantCards:
system.domain === "external"
? ["SensorScans", "Sensors", "sensors"]
: ["SecurityScans"],
});
});
pubsub.publish(
"sensorsUpdate",
App.systems.filter(s => s.type === "Sensors"),
);
});
App.on(
"processedData",
({id, simulatorId, domain = "external", data = "", flash}) => {
let system;
if (id) {
system = App.systems.find(sys => sys.id === id);
}
if (simulatorId && domain) {
system = App.systems.find(
sys => sys.simulatorId === simulatorId && sys.domain === domain,
);
}
if (!system) {
console.info("Please specify the domain when sending this data: ", data);
return;
}
const simulator = App.simulators.find(s => s.id === system.simulatorId);
system && system.processedDatad(data.replace(/#SIM/gi, simulator.name));
pubsub.publish(
"sensorsUpdate",
App.systems.filter(s => s.type === "Sensors"),
);
const stations = simulator.stations.filter(s =>
s.cards.find(
c => c.component === "Sensors" || c.component === "JrSensors",
),
);
stations.forEach(s => {
if (flash) {
const cardName = s.cards.find(
c => c.component === "Sensors" || c.component === "JrSensors",
).name;
App.handleEvent(
{
action: "changeCard",
message: cardName,
simulatorId: system.simulatorId,
stationId: s.name,
},
"triggerAction",
);
App.handleEvent(
{
action: "flash",
simulatorId: system.simulatorId,
stationId: s.name,
},
"triggerAction",
);
}
pubsub.publish("notify", {
id: uuid.v4(),
simulatorId: system.simulatorId,
station: s.name,
title: `New Processed Data`,
body: data,
color: "info",
relevantCards: ["Sensors", "JrSensors", "sensors"],
});
});
},
);
App.on(
"removeProcessedData",
({id, simulatorId, domain = "external", time}) => {
let system: Classes.Sensors;
if (id) {
system = App.systems.find(sys => sys.id === id);
}
if (simulatorId && domain) {
system = App.systems.find(
sys => sys.simulatorId === simulatorId && sys.domain === domain,
);
}
system && system.removeProcessedData(time);
pubsub.publish(
"sensorsUpdate",
App.systems.filter(s => s.type === "Sensors"),
);
},
);
App.on("sensorScanCancel", ({id}) => {
const system = App.systems.find(sys => sys.id === id);
system.scanCanceled();
pubsub.publish("notify", {
id: uuid.v4(),
simulatorId: system.simulatorId,
type: `${capitalCase(system.domain)} Sensors`,
station: "Core",
title: `${capitalCase(system.domain)} Scan Cancelled`,
body: "",
color: "info",
});
App.handleEvent(
{
simulatorId: system.simulatorId,
title: `${system.domain} Scan Cancelled`,
component: "SensorsCore",
body: null,
color: "warning",
},
"addCoreFeed",
);
pubsub.publish(
"sensorsUpdate",
App.systems.filter(s => s.type === "Sensors"),
);
});
App.on(
"setPresetAnswers",
({simulatorId, domain = "external", presetAnswers = []}) => {
const system = App.systems.find(
sys =>
sys.simulatorId === simulatorId &&
sys.domain === domain &&
sys.class === "Sensors",
);
if (!system) {
console.error(
"Invalid system. You probably forgot to add the domain to the sensors macro",
);
return;
}
const simulator = App.simulators.find(s => s.id === system.simulatorId);
system &&
system.setPresetAnswers(
presetAnswers.map(p => {
return {
label: p.label ? p.label.replace(/#SIM/gi, simulator.name) : "",
value: p.value ? p.value.replace(/#SIM/gi, simulator.name) : "",
};
}),
);
pubsub.publish(
"sensorsUpdate",
App.systems.filter(s => s.type === "Sensors"),
);
},
);
// Contacts
App.on("createSensorContact", ({id, contact}) => {
const system = App.systems.find(sys => sys.id === id);
if (!system) return;
system.createContact(contact);
pubsub.publish("sensorContactUpdate", system);
});
App.on("createSensorContacts", ({id, contacts}) => {
const system = App.systems.find(sys => sys.id === id);
if (!system) return;
contacts.forEach(c => {
system.createContact(c);
});
pubsub.publish("sensorContactUpdate", system);
});
App.on("moveSensorContact", ({id, contact}) => {
const system = App.systems.find(sys => sys.id === id);
if (system?.moveContact) system.moveContact(contact);
pubsub.publish("sensorContactUpdate", system);
});
App.on("updateSensorContactLocation", ({id, contact, cb}) => {
const system = App.systems.find(sys => sys.id === id);
system.updateContact(contact);
pubsub.publish("sensorContactUpdate", system);
cb && cb();
});
App.on("removeSensorContact", ({id, contact, cb}) => {
const system = App.systems.find(sys => sys.id === id);
const classId = contact.id;
if (!system) return;
system.removeContact(contact);
// Get rid of any targeting classes
const targeting = App.systems.find(
s => s.simulatorId === system.simulatorId && s.class === "Targeting",
);
targeting.removeTargetClass(classId);
pubsub.publish(
"targetingUpdate",
App.systems.filter(s => s.type === "Targeting"),
);
pubsub.publish("sensorContactUpdate", system);
cb && cb();
});
App.on("removeAllSensorContacts", ({id, type}) => {
const system = App.systems.find(sys => sys.id === id);
if (!system) return;
let removeContacts = [];
if (type) {
removeContacts = system.contacts.filter(c => type.indexOf(c.type) > -1);
system.contacts = system.contacts.filter(c => type.indexOf(c.type) === -1);
} else {
removeContacts = system.contacts.concat();
system.contacts = [];
}
// Also remove any contacts from targeting
if (removeContacts.length > 0) {
const targeting = App.systems.find(
s => s.simulatorId === system.simulatorId && s.class === "Targeting",
);
removeContacts.forEach(c => {
if (targeting.classes.find(t => t.id === c.id)) {
targeting.removeTargetClass(c.id);
}
});
pubsub.publish(
"targetingUpdate",
App.systems.filter(s => s.type === "Targeting"),
);
}
pubsub.publish("sensorContactUpdate", system);
});
App.on("stopAllSensorContacts", ({id}) => {
const system = App.systems.find(sys => sys.id === id);
system.contacts.concat().forEach(contact => {
system.stopContact(contact);
});
pubsub.publish("sensorContactUpdate", system);
});
App.on("destroySensorContact", ({id, contact, contacts = []}) => {
const system = App.systems.find(sys => sys.id === id);
// Also remove the contact from targeting
const targeting = App.systems.find(
s => s.simulatorId === system.simulatorId && s.class === "Targeting",
);
let update = false;
if (contact) {
system.destroyContact({id: contact});
if (targeting.classes.find(t => t.id === contact)) {
update = true;
setTimeout(() => {
targeting.removeTargetClass(contact);
}, 1000);
}
} else {
contacts.forEach(c => {
system.destroyContact({id: c});
if (targeting.classes.find(t => t.id === c)) {
update = true;
setTimeout(() => {
targeting.removeTargetClass(c);
}, 1000);
}
});
}
pubsub.publish("sensorContactUpdate", system);
if (update)
setTimeout(() => {
pubsub.publish(
"targetingUpdate",
App.systems.filter(s => s.type === "Targeting"),
);
}, 1100);
});
App.on("updateSensorContact", args => {
const {id, simulatorId, contact, cb} = args;
const system = App.systems.find(
sys =>
sys.id === id ||
(sys.simulatorId === simulatorId &&
sys.class === "Sensors" &&
sys.domain === "external"),
);
system.updateContact(contact);
pubsub.publish("sensorContactUpdate", system);
cb && cb();
});
// Army Contacts
App.on(
"setArmyContacts",
({simulatorId, domain = "external", armyContacts}) => {
const system = App.systems.find(
sys => sys.simulatorId === simulatorId && sys.domain === domain,
);
system && system.setArmyContacts(armyContacts);
pubsub.publish(
"sensorsUpdate",
App.systems.filter(s => s.type === "Sensors"),
);
},
);
App.on("createSensorArmyContact", ({id, contact}) => {
const system = App.systems.find(sys => sys.id === id);
system.createArmyContact(contact);
pubsub.publish(
"sensorsUpdate",
App.systems.filter(s => s.type === "Sensors"),
);
});
App.on("removeSensorArmyContact", ({id, contact}) => {
const system = App.systems.find(sys => sys.id === id);
system.removeArmyContact(contact);
pubsub.publish(
"sensorsUpdate",
App.systems.filter(s => s.type === "Sensors"),
);
});
App.on("updateSensorArmyContact", ({id, contact}) => {
const system = App.systems.find(sys => sys.id === id);
system.updateArmyContact(contact);
pubsub.publish(
"sensorsUpdate",
App.systems.filter(s => s.type === "Sensors"),
);
});
App.on("nudgeSensorContacts", ({id, amount, speed, yaw}) => {
const system = App.systems.find(sys => sys.id === id);
system.nudgeContacts(amount, speed, yaw);
pubsub.publish(
"sensorContactUpdate",
Object.assign({}, system, {
contacts: system.contacts.map(c =>
Object.assign({}, c, {forceUpdate: true}),
),
}),
);
// Reset the force update after a second.
setTimeout(() => pubsub.publish("sensorContactUpdate", system), 500);
});
App.on("setSensorPingMode", ({id, mode}) => {
const system = App.systems.find(sys => sys.id === id);
system.setPingMode(mode);
pubsub.publish(
"sensorsUpdate",
App.systems.filter(s => s.type === "Sensors"),
);
});
App.on("pingSensors", ({id}) => {
const system = App.systems.find(sys => sys.id === id);
system.sonarPing();
pubsub.publish("sensorsPing", id);
});
App.on("sensorsSetHasPing", ({id, ping, cb}) => {
const system = App.systems.find(sys => sys.id === id);
system.pings = ping;
pubsub.publish(
"sensorsUpdate",
App.systems.filter(s => s.type === "Sensors"),
);
cb && cb();
});
App.on("setSensorsHistory", ({id, history}) => {
const system = App.systems.find(sys => sys.id === id);
system.history = history;
pubsub.publish(
"sensorsUpdate",
App.systems.filter(s => s.type === "Sensors"),
);
});
App.on("newSensorScan", ({id, scan}) => {
const sensors = App.systems.find(sys => sys.id === id);
App.handleEvent(
{
simulatorId: sensors.simulatorId,
title: `New Sensor Scan`,
component: "SensorsCore",
body: scan.request,
color: "info",
},
"addCoreFeed",
);
sensors.newScan(scan);
pubsub.publish(
"sensorsUpdate",
App.systems.filter(s => s.type === "Sensors"),
);
});
App.on("updateSensorScan", ({id, scan}) => {
const sensors = App.systems.find(sys => sys.id === id);
sensors.updateScan(scan);
pubsub.publish(
"sensorsUpdate",
App.systems.filter(s => s.type === "Sensors"),
);
});
App.on("cancelSensorScan", ({id, scan}) => {
const sensors = App.systems.find(sys => sys.id === id);
sensors.cancelScan(scan);
App.handleEvent(
{
simulatorId: sensors.simulatorId,
title: `Sensor Scan Cancelled`,
component: "SensorsCore",
body: "",
color: "info",
},
"addCoreFeed",
);
pubsub.publish(
"sensorsUpdate",
App.systems.filter(s => s.type === "Sensors"),
);
});
App.on("toggleSensorsAutoTarget", ({id, target}) => {
const sensors = App.systems.find(sys => sys.id === id);
sensors.setAutoTarget(target);
pubsub.publish(
"sensorsUpdate",
App.systems.filter(s => s.type === "Sensors"),
);
});
App.on("setSensorsSegment", ({id, ring, line, state}) => {
const sensors = App.systems.find(sys => sys.id === id);
sensors.setSegment(ring, line, state);
pubsub.publish(
"sensorsUpdate",
App.systems.filter(s => s.type === "Sensors"),
);
});
App.on("toggleSensorsAutoThrusters", ({id, thrusters}) => {
const sensors = App.systems.find(sys => sys.id === id);
sensors.setAutoThrusters(thrusters);
pubsub.publish(
"sensorsUpdate",
App.systems.filter(s => s.type === "Sensors"),
);
});
App.on("setSensorsInterference", ({id, interference}) => {
const sensors = App.systems.find(sys => sys.id === id);
sensors.setInterference(interference);
pubsub.publish(
"sensorsUpdate",
App.systems.filter(s => s.type === "Sensors"),
);
pubsub.publish(
"targetingUpdate",
App.systems.filter(s => s.type === "Targeting"),
);
});
App.on("setAutoMovement", ({id, movement}) => {
const sensors = App.systems.find(sys => sys.id === id);
sensors.setMovement(movement);
pubsub.publish(
"sensorsUpdate",
App.systems.filter(s => s.type === "Sensors"),
);
});
App.on("updateSensorContacts", ({id, contacts, cb}) => {
const system = App.systems.find(sys => sys.id === id);
if (!system) return;
contacts.forEach(contact => {
if (contact.destination) {
system.moveContact(contact);
} else {
system.updateContact(contact);
}
});
pubsub.publish("sensorContactUpdate", system);
cb && cb();
});
App.on("updateSensorGrid", ({simulatorId, contacts, cb}) => {
const system = App.systems.find(
sys =>
sys.simulatorId === simulatorId &&
sys.domain === "external" &&
sys.class === "Sensors",
);
const contactIds = system.contacts.map(c => c.id);
const newContacts = contacts.filter(c => !contactIds.includes(c.id));
const movingContacts = contacts.filter(c => contactIds.includes(c.id));
const deleteContacts = contactIds.filter(
c => !contacts.find(cc => cc.id === c),
);
deleteContacts.forEach(id => {
system.removeContact({id});
// Get rid of any targeting classes
const targeting = App.systems.find(
s => s.simulatorId === system.simulatorId && s.class === "Targeting",
);
targeting.removeTargetClass(id);
pubsub.publish(
"targetingUpdate",
App.systems.filter(s => s.type === "Targeting"),
);
});
newContacts.forEach(contact => {
const {destination, speed = 0.4, ...rest} = contact;
const id = system.createContact({destination, speed, ...rest});
system.moveContact({id, destination, speed});
});
movingContacts.forEach(contact => system.moveContact(contact));
pubsub.publish("sensorContactUpdate", system);
});
const findNewPoint = (angle, r) => ({
x: Math.cos(angle) * r,
y: Math.sin(angle) * r,
});
App.on(
"sensorsFireProjectile",
({simulatorId, contactId, speed, hitpoints, miss}) => {
const system = App.systems.find(
sys =>
sys.simulatorId === simulatorId &&
sys.domain === "external" &&
sys.class === "Sensors",
);
if (!system) return;
const contact = system.contacts.find(c => c.id === contactId);
if (!contact) return;
contact.fireTime = 0;
const {id, ...rest} = contact;
const projectile = new Classes.SensorContact({
...rest,
hitpoints,
autoFire: false,
hostile: false,
type: "projectile",
miss,
});
// Move it to the exact oposite side of the grid
// at a radius of 1.2
const currentAngle = Math.atan2(
projectile.position.y,
projectile.position.x,
);
projectile.move(
{...findNewPoint(currentAngle + Math.PI, 1.5), z: 0},
speed,
);
system.contacts.push(projectile);
pubsub.publish("sensorContactUpdate", system);
},
);
App.on("setSensorsDefaultHitpoints", ({id, simulatorId, hp}) => {
const system = App.systems.find(
sys =>
sys.id === id ||
(sys.simulatorId === simulatorId &&
sys.domain === "external" &&
sys.class === "Sensors"),
);
system.setDefaultHitpoints(hp);
pubsub.publish(
"sensorsUpdate",
App.systems.filter(s => s.type === "Sensors"),
);
});
App.on("setSensorsDefaultSpeed", ({id, simulatorId, speed}) => {
const system = App.systems.find(
sys =>
sys.id === id ||
(sys.simulatorId === simulatorId &&
sys.domain === "external" &&
sys.class === "Sensors"),
);
system.setDefaultSpeed(speed);
pubsub.publish(
"sensorsUpdate",
App.systems.filter(s => s.type === "Sensors"),
);
});
App.on("setSensorsMissPercent", ({id, simulatorId, miss}) => {
const system = App.systems.find(
sys =>
sys.id === id ||
(sys.simulatorId === simulatorId &&
sys.domain === "external" &&
sys.class === "Sensors"),
);
system.setMissPercent(miss);
pubsub.publish(
"sensorsUpdate",
App.systems.filter(s => s.type === "Sensors"),
);
}); | the_stack |
import UtilInternal = require("../util/UtilInternal");
import Typing = require("../util/Typing");
import ProviderRuntimeException = require("../exceptions/ProviderRuntimeException");
type ProviderAttributeConstructor<T = ProviderAttribute> = new (...args: any[]) => T;
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
function Notifiable<TBase extends ProviderAttributeConstructor, T = unknown>(superclass: TBase) {
class Notifiable extends superclass {
public callbacks: ((value: T) => void)[] = [];
public constructor(...args: any[]) {
super(...args);
this.hasNotify = true;
if (this.implementation) {
this.implementation.valueChanged = this.valueChanged.bind(this);
}
}
/**
* If this attribute is changed the application should call this function with the new value,
* whereafter the new value gets published
*
* @param value - the new value of the attribute
*/
public valueChanged(value: T): void {
UtilInternal.fire(this.callbacks, [value]);
}
/**
* Registers an Observer for value changes
*
* @param observer - the callback function with the signature "function(value){..}"
*
* @see ProviderAttribute#valueChanged
* @see ProviderAttribute#unregisterObserver
*/
public registerObserver(observer: (value: T) => void): void {
this.callbacks.push(observer);
}
/**
* Unregisters an Observer for value changes
*
* @param observer - the callback function with the signature "function(value){..}"
*
* @see ProviderAttribute#valueChanged
* @see ProviderAttribute#registerObserver
*/
public unregisterObserver(observer: (value: T) => void): void {
UtilInternal.removeElementFromArray(this.callbacks, observer);
}
}
return Notifiable;
}
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
function Writable<TBase extends ProviderAttributeConstructor, T = unknown>(superclass: TBase) {
return class Writable extends superclass {
public constructor(...args: any[]) {
super(...args);
this.hasWrite = true;
}
/**
* Registers the setter function for this attribute
*
* @param setterFunc - the setter function with the signature
* 'void setterFunc({?}value) {..}'
* @returns fluent interface to call multiple methods
*/
public registerSetter(setterFunc: (value: T) => void): ProviderAttribute {
this.privateSetterFunc = setterFunc;
return this;
}
/**
* Calls through the setter registered with registerSetter with the same arguments as this
* function
*
* @param value - the new value of the attribute
*
* @throws {Error} if no setter function was registered before calling it
*
* @see ProviderAttribute#registerSetter
*/
public async set(value: T): Promise<[]> {
if (!this.privateSetterFunc) {
throw new Error("no setter function registered for provider attribute");
}
if (!this.privateGetterFunc) {
throw new Error("no getter function registered for provider attribute");
}
const setterParams = Typing.augmentTypes(value, this.attributeType);
const originalValue = await this.privateGetterFunc();
await this.privateSetterFunc(setterParams);
if (originalValue !== value && this.hasNotify) {
(this as any).valueChanged(value);
}
return [];
}
};
}
function toArray<T>(returnValue: T): T[] {
return [returnValue];
}
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
function Readable<TBase extends ProviderAttributeConstructor, T = unknown>(superclass: TBase) {
return class Readable extends superclass {
public constructor(...args: any[]) {
super(...args);
this.hasRead = true;
}
public registerGetter(getterFunc: () => T | Promise<T>): void {
this.privateGetterFunc = async () => getterFunc();
}
/**
* Calls through the getter registered with registerGetter with the same arguments as this
* function
*
* @returns a Promise which resolves the attribute value
*
* rejects {Error} if no getter function was registered before calling it
* rejects {Error} if registered getter returns a compound type with incorrect values
*/
public get(): Promise<T[]> {
try {
if (!this.privateGetterFunc) {
return Promise.reject(
new Error(`no getter function registered for provider attribute: ${this.attributeName}`)
);
}
return Promise.resolve(this.privateGetterFunc())
.then(toArray)
.catch(error => {
if (error instanceof ProviderRuntimeException) {
throw error;
}
throw new ProviderRuntimeException({
detailMessage: `getter method for attribute ${this.attributeName} reported an error`
});
});
} catch (e) {
return Promise.reject(e);
}
}
};
}
interface JoynrProvider {
interfaceName: string;
}
export class ProviderAttribute<T = any> {
public hasNotify: boolean = false;
public attributeType: string;
public attributeName: string;
/** protected property, needs to be public for tsc -d */
public implementation: {
get?: (key: string) => any | Promise<any>;
set?: (value: T) => void | Promise<void>;
valueChanged?: (value: T) => void;
};
public parent: JoynrProvider;
public hasRead: boolean = false;
public hasWrite: boolean = false;
/** protected property, needs to be public for tsc -d */
public privateGetterFunc?: Function;
/** protected property, needs to be public for tsc -d */
public privateSetterFunc?: (value: T) => void | Promise<void>;
/**
* Constructor of ProviderAttribute object that is used in the generation of provider attributes
*
* @constructor
*
* @param parent - the provider object that contains this attribute
* @param [implementation] - the definition of attribute implementation
* @param {Function} [implementation.set] - the getter function with the signature "function(value){}" that
* stores the given attribute value
* @param {Function} [implementation.get] the getter function with the signature "function(){}" that returns the
* current attribute value
* @param attributeName - the name of the attribute
* @param attributeType - the type of the attribute
*/
public constructor(
parent: JoynrProvider,
implementation: {
get?: (key: string) => T | Promise<T>;
set?: (value: T) => void | Promise<void>;
},
attributeName: string,
attributeType: string
) {
this.parent = parent;
this.implementation = implementation;
this.attributeName = attributeName;
this.attributeType = attributeType;
// place these functions after the forwarding we don't want them public
if (this.implementation && typeof this.implementation.get === "function") {
this.privateGetterFunc = this.implementation.get;
}
if (this.implementation && typeof this.implementation.set === "function") {
this.privateSetterFunc = this.implementation.set;
}
}
public isNotifiable(): boolean {
return this.hasNotify;
}
/**
* Check Getter and Setter functions.
*/
public check(): boolean {
return (
(!this.hasRead || typeof this.privateGetterFunc === "function") &&
(!this.hasWrite || typeof this.privateSetterFunc === "function")
);
}
}
/*
The empty container classes below are declared for typing purposes.
Unfortunately declarations need to be repeated since it's impossible to give template parameters
to mixin classes. See https://github.com/Microsoft/TypeScript/issues/26154
*/
const ProviderReadAttributeImpl = Readable<ProviderAttributeConstructor>(ProviderAttribute);
export class ProviderReadAttribute<T> extends ProviderReadAttributeImpl {
public get!: () => Promise<T[]>;
public registerGetter!: (getterFunc: () => T | Promise<T>) => void;
}
const ProviderReadWriteAttributeImpl = Writable<ProviderAttributeConstructor>(ProviderReadAttribute);
export class ProviderReadWriteAttribute<T> extends ProviderReadWriteAttributeImpl {
public get!: () => Promise<T[]>;
public registerGetter!: (getterFunc: () => T | Promise<T>) => void;
public registerSetter!: (setterFunc: (value: T) => void) => ProviderReadWriteAttribute<T>;
public set!: (value: T) => Promise<[]>;
}
const ProviderReadWriteNotifyAttributeImpl = Notifiable<ProviderAttributeConstructor>(ProviderReadWriteAttribute);
export class ProviderReadWriteNotifyAttribute<T> extends ProviderReadWriteNotifyAttributeImpl {
public get!: () => Promise<T[]>;
public registerGetter!: (getterFunc: () => T | Promise<T>) => void;
public registerSetter!: (setterFunc: (value: T) => void) => ProviderReadWriteAttribute<T>;
public set!: (value: T) => Promise<[]>;
public registerObserver!: (observer: (value: T) => void) => void;
public unregisterObserver!: (observer: (value: T) => void) => void;
public valueChanged!: (value: T) => void;
}
const ProviderReadNotifyAttributeImpl = Notifiable<ProviderAttributeConstructor>(ProviderReadAttribute);
export class ProviderReadNotifyAttribute<T> extends ProviderReadNotifyAttributeImpl {
public get!: () => Promise<T[]>;
public registerGetter!: (getterFunc: () => T | Promise<T>) => void;
public registerObserver!: (observer: (value: T) => void) => void;
public unregisterObserver!: (observer: (value: T) => void) => void;
public valueChanged!: (value: T) => void;
} | the_stack |
import React, {
useState,
useRef,
useEffect,
useCallback,
useContext,
} from "react";
import ReactFlow, {
ReactFlowProvider,
addEdge,
removeElements,
Controls,
Background,
BackgroundVariant,
ConnectionLineType,
ConnectionMode,
Edge as ReactFlowEdge,
OnConnectStartParams,
} from "react-flow-renderer";
import styles from "./dnd.module.css";
import EditorStateManager, {
EditorOperation,
} from "./editor/EditorStateManager";
import RenderAudienceNode from "./nodes/RenderAudienceNode";
import RenderEdge from "./nodes/RenderEdge";
import RenderEmailNode from "./nodes/RenderEmailNode";
import RenderFilterNode from "./nodes/RenderFilterNode";
import RenderTriggerNode from "./nodes/RenderTriggerNode";
import RenderWaitNode from "./nodes/RenderWaitNode";
import AbstractCampaignNode from "common/campaign/nodes/abstractCampaignNode";
import {
CampaignGraph,
CampaignNodeKind,
canConnect,
Edge,
EdgeKind,
} from "common/campaign";
import AudienceCampaignNode from "common/campaign/nodes/audienceCampaignNode";
import TriggerCampaignNode from "common/campaign/nodes/triggerCampaignNode";
import EmailCampaignNode from "common/campaign/nodes/emailCampaignNode";
import WaitCampaignNode from "common/campaign/nodes/waitCampaignNode";
import FilterCampaignNode from "common/campaign/nodes/filterCampaignNode";
import EditorAlert from "./EditorAlert";
import { useMutation } from "@apollo/client";
import {
CREATE_CAMPAIGN_NODE,
CREATE_CAMPAIGN_NODE_EDGE,
DELETE_CAMAPIGN_NODE,
DELETE_CAMAPIGN_NODE_EDGE,
UPDATE_CAMPAIGN_NODE,
} from "./CampaignQueries";
import {
CreateCampaignNode,
CreateCampaignNodeVariables,
} from "__generated__/CreateCampaignNode";
import {
UpdateCampaignNode,
UpdateCampaignNodeVariables,
} from "__generated__/UpdateCampaignNode";
import {
createEdgeElementType,
createNodeElementType,
} from "./createNodeElementType";
import {
DeleteCampaignNode,
DeleteCampaignNodeVariables,
} from "__generated__/DeleteCampaignNode";
import ConnectionLine from "./ConnectionLine";
import {
ConnectCampaignNodes,
ConnectCampaignNodesVariables,
} from "__generated__/ConnectCampaignNodes";
import CampaignNavbar from "./CampaignNavbar";
import { DashboardContext } from "layout/DashboardLayout";
import useTimeout from "@rooks/use-timeout";
import DebugNodeProvider from "./DebugNodeProvider";
import DebugNodeWindow from "./nodes/DebugNodeWindow";
const NODE_TYPES = {
[CampaignNodeKind.Trigger]: RenderTriggerNode,
[CampaignNodeKind.Audience]: RenderAudienceNode,
[CampaignNodeKind.Filter]: RenderFilterNode,
[CampaignNodeKind.Wait]: RenderWaitNode,
[CampaignNodeKind.Email]: RenderEmailNode,
};
const EDGE_TYPES = {
[EdgeKind.Default]: RenderEdge,
[EdgeKind.Timeout]: RenderEdge,
};
export interface NodeElementType {
id: string;
type: CampaignNodeKind | EdgeKind;
source?: string;
target?: string;
data: Record<string, any>;
position: {
x: number;
y: number;
};
arrowHeadType: string;
selected?: boolean;
}
export interface EdgeElementType {
id: string;
source: string;
target: string;
sourceHandle?: string;
targetHandle?: string;
type: EdgeKind;
}
export type ElementType = NodeElementType | EdgeElementType;
export const EditorContext = React.createContext<EditorStateManager>(null);
interface Props {
editorState: EditorStateManager;
}
const connectionLineStyle = { color: "#7E7E7E", stroke: "#7E7E7E" };
const generateNodeFunction = (kind: CampaignNodeKind): AbstractCampaignNode => {
switch (kind) {
case CampaignNodeKind.Audience:
return AudienceCampaignNode.new();
case CampaignNodeKind.Email:
return EmailCampaignNode.new();
case CampaignNodeKind.Filter:
return FilterCampaignNode.new();
case CampaignNodeKind.Trigger:
return TriggerCampaignNode.new();
case CampaignNodeKind.Wait:
return WaitCampaignNode.new();
}
};
const validateConnection = (
editor: EditorStateManager,
node: ReactFlowEdge
) => {
const from = node.source;
const to = node.target;
const fromNode = editor.graph.getNodeById(from);
const toNode = editor.graph.getNodeById(to);
const existingEdge = editor.graph.getEdge(fromNode, toNode);
if (existingEdge) {
return false;
}
return canConnect(fromNode, toNode);
};
const createElements = (graph: CampaignGraph) => {
const nodes = graph.getNodes().map(createNodeElementType);
const edges = graph.getEdges().map(createEdgeElementType);
return [...nodes, ...edges];
};
const CampaignEditorGrid = (props: Props) => {
const editorStateRef = props.editorState;
const elementsRef = useRef<ElementType[]>();
const [createCampaignNode] = useMutation<
CreateCampaignNode,
CreateCampaignNodeVariables
>(CREATE_CAMPAIGN_NODE);
const [updateCampaignNode] = useMutation<
UpdateCampaignNode,
UpdateCampaignNodeVariables
>(UPDATE_CAMPAIGN_NODE);
const [deleteCampaignNode] = useMutation<
DeleteCampaignNode,
DeleteCampaignNodeVariables
>(DELETE_CAMAPIGN_NODE);
const [connectCampaignNodes] = useMutation<
ConnectCampaignNodes,
ConnectCampaignNodesVariables
>(CREATE_CAMPAIGN_NODE_EDGE);
const [disconnectNodes] = useMutation<
DeleteCampaignNode,
DeleteCampaignNodeVariables
>(DELETE_CAMAPIGN_NODE_EDGE);
const [_, setOperationId] = useState(editorStateRef.operationId);
const reactFlowWrapper = useRef(null);
const [reactFlowInstance, setReactFlowInstance] = useState(null);
const [elements, setElements] = useState<ElementType[]>(
createElements(editorStateRef.graph)
);
const [error, setError] = useState("");
const dashboardContext = useContext(DashboardContext);
elementsRef.current = elements;
const clearError = useTimeout(() => {
setError("");
}, 5000);
useEffect(() => {
if (error) {
clearError.clear();
}
}, [error]);
/**
* Connection between two nodes.
*
* @param params ReactFlowEdge
*/
const onConnect = (params: ReactFlowEdge) => {
if (!validateConnection(editorStateRef, params)) {
setError("These two nodes can't be connected in this way");
clearError.start();
return;
}
const sourceId = params.source;
const targetId = params.target;
const edgeKind = (
params.sourceHandle ? params.sourceHandle : EdgeKind.Default
) as EdgeKind;
const newEdge = Edge.new(sourceId, targetId, edgeKind);
const newEdgeElement: EdgeElementType = {
id: newEdge.getId(),
source: sourceId,
target: targetId,
type: edgeKind,
};
if (params.sourceHandle) {
newEdgeElement.sourceHandle = params.sourceHandle;
}
const nextElements = addEdge(
newEdgeElement,
elementsRef.current
) as NodeElementType[];
const graph = editorStateRef.graph;
graph.addEdge(sourceId, targetId, edgeKind, newEdge.getId());
connectCampaignNodes({
variables: {
id: newEdge.getId(),
fromId: sourceId,
toId: targetId,
edgeKind: edgeKind,
},
});
setElements(nextElements);
};
const onElementsRemove = (elementsToRemove: NodeElementType[]) => {
const nextElements = removeElements(
elementsToRemove,
elements
) as NodeElementType[];
setElements(nextElements);
};
const onStateChange = (editor: EditorStateManager) => {
setOperationId(editor.operationId);
};
const onDeleteCampaignNode = (obj: EditorOperation) => {
const elementsToRemove = [elementsRef.current.find((e) => e.id === obj.id)];
const nextElements = removeElements(
elementsToRemove,
elementsRef.current
) as NodeElementType[];
console.log(nextElements);
setElements(nextElements);
deleteCampaignNode({
variables: {
id: obj.id,
},
});
};
const onDeleteCampaignNodeEdge = (obj: EditorOperation) => {
const elementsToRemove = [elementsRef.current.find((e) => e.id === obj.id)];
const nextElements = removeElements(
elementsToRemove,
elementsRef.current
) as NodeElementType[];
setElements(nextElements);
disconnectNodes({
variables: {
id: obj.id,
},
});
};
/**
* Clicking an element should select it and open the inspector
* @param event Event
* @param element Node
*/
const onSelectCampaignNode = (element: NodeElementType) => {
let copy = [...elementsRef.current].map((curr) => {
if (curr.id == element.id) {
return {
...curr,
selected: true,
};
}
return {
...curr,
selected: false,
};
});
setElements(copy);
};
const onDeselectCampaignNode = () => {
let copy = [...elementsRef.current].map((curr) => ({
...curr,
selected: false,
}));
setElements(copy);
};
useEffect((): any => {
editorStateRef.emitter.on("stateChange", onStateChange);
editorStateRef.emitter.on("campaignNodeDelete", onDeleteCampaignNode);
editorStateRef.emitter.on("campaignNodeSelected", onSelectCampaignNode);
editorStateRef.emitter.on(
"campaignNodeEdgeDelete",
onDeleteCampaignNodeEdge
);
editorStateRef.emitter.on("campaignNodeDeselected", onDeselectCampaignNode);
return () => {
editorStateRef.emitter.removeListener("stateChange", onStateChange);
editorStateRef.emitter.removeListener(
"stateChange",
onDeleteCampaignNode
);
editorStateRef.emitter.removeListener(
"campaignNodeEdgeDelete",
onDeleteCampaignNodeEdge
);
editorStateRef.emitter.removeListener(
"campaignNodeDeselected",
onDeselectCampaignNode
);
};
}, []);
const onLoad = (_reactFlowInstance) => {
setReactFlowInstance(_reactFlowInstance);
editorStateRef.reactFlowInstance = _reactFlowInstance;
};
const onDragOver = (event) => {
event.preventDefault();
event.dataTransfer.dropEffect = "move";
};
const onDrop = (event) => {
event.preventDefault();
const reactFlowBounds = reactFlowWrapper.current.getBoundingClientRect();
const kind = event.dataTransfer.getData(
"application/reactflow"
) as CampaignNodeKind;
const position = reactFlowInstance.project({
x: event.clientX - reactFlowBounds.left - 140,
y: event.clientY - reactFlowBounds.top - 50,
});
let newElement = generateNodeFunction(kind);
// network request here
const newNode = {
id: newElement.id,
type: kind,
position,
data: {},
arrowHeadType: "arrowclosed",
};
editorStateRef.graph.addNode(newElement);
createCampaignNode({
variables: {
id: newElement.id,
kind: kind,
campaignId: editorStateRef.campaignId,
name: kind,
positionX: position.x,
positionY: position.y,
},
});
setElements((es) => es.concat(newNode));
};
/**
* Moving nodes around, event when you drop it.
*/
const onDragNodeStop = useCallback((event: any, node: NodeElementType) => {
const internalNode = props.editorState.graph.getNodeById(node.id);
internalNode.setPositionX(node.position.x);
internalNode.setPositionY(node.position.y);
updateCampaignNode({
variables: {
id: node.id,
positionX: node.position.x,
positionY: node.position.y,
},
});
}, []);
const onPaneClick = useCallback((): void => {
props.editorState.deselectNode();
}, []);
const onMoveEnd = useCallback(() => {
editorStateRef.setDraggingPane(false);
}, [editorStateRef]);
const onMoveStart = useCallback((): void => {
editorStateRef.setDraggingPane(true);
}, [editorStateRef]);
const onConnectStart = useCallback(
(_: any, params: OnConnectStartParams): void => {
editorStateRef.onConnectStart(params);
},
[editorStateRef]
);
const onConnectStop = useCallback((): void => {
editorStateRef.onConnectStop();
}, [editorStateRef]);
return (
<EditorContext.Provider value={editorStateRef}>
<DebugNodeProvider elements={elements}>
<div className={styles.editor_container}>
<CampaignNavbar />
<div className={styles.dndflow}>
<ReactFlowProvider>
<div
className="reactflow-wrapper"
ref={reactFlowWrapper}
style={{
width: "100%",
height: dashboardContext.contentPaneHeight,
minHeight: "500px",
position: "relative",
}}
>
<ReactFlow
elements={elements}
onConnect={onConnect}
onElementsRemove={onElementsRemove}
onLoad={onLoad}
onDrop={onDrop}
onDragOver={onDragOver}
snapToGrid={true}
nodeTypes={NODE_TYPES}
connectionLineComponent={ConnectionLine}
onNodeDragStop={onDragNodeStop}
edgeTypes={EDGE_TYPES}
connectionMode={ConnectionMode.Loose}
selectNodesOnDrag={false}
connectionLineType={ConnectionLineType.SmoothStep}
arrowHeadColor={"#7E7E7E"}
connectionLineStyle={connectionLineStyle}
onPaneClick={onPaneClick}
onMoveStart={onMoveStart}
onMoveEnd={onMoveEnd}
zoomOnDoubleClick={false}
onConnectStart={onConnectStart}
onConnectStop={onConnectStop}
>
<Background
variant={BackgroundVariant.Dots}
color="#949494"
style={{ backgroundColor: "#d8d8d8" }}
/>
<Controls />
</ReactFlow>
</div>
{editorStateRef.renderSidebar()}
</ReactFlowProvider>
<EditorAlert text={error} />
</div>
</div>
<DebugNodeWindow />
</DebugNodeProvider>
</EditorContext.Provider>
);
};
export default CampaignEditorGrid; | the_stack |
import { ApolloQueryResult, gql, InMemoryCache } from '@apollo/client/core';
// Currently do not test against all valid peer dependency versions of apollo
// Would be nice to have, but can't find an elegant way of doing it.
import { createMockClient, MockApolloClient } from './mockClient';
import { createMockSubscription, IMockSubscription } from './mockSubscription';
describe('MockClient integration tests', () => {
let mockClient: MockApolloClient;
beforeEach(() => {
jest.spyOn(console, 'warn')
.mockReset();
jest.spyOn(console, 'error')
.mockReset();
});
describe('Simple queries', () => {
const queryOne = gql`query One {one}`;
const queryTwo = gql`query Two {two}`;
let requestHandlerOne: jest.Mock;
let resolveRequestOne: Function;
beforeEach(() => {
mockClient = createMockClient();
requestHandlerOne = jest.fn(() => new Promise((r) => { resolveRequestOne = r }));
mockClient.setRequestHandler(queryOne, requestHandlerOne);
});
describe('Given request handler is defined', () => {
let promise: Promise<ApolloQueryResult<any>>;
beforeEach(() => {
promise = mockClient.query({ query: queryOne });
});
it('returns a promise which resolves to the correct value', async () => {
expect(promise).toBeInstanceOf(Promise);
resolveRequestOne({ data: { one: 'one' } });
const actual = await promise;
expect(actual).toEqual(expect.objectContaining({ data: { one: 'one' } }));
});
it('throws when a handler is added for the same query', () => {
expect(() => mockClient.setRequestHandler(queryOne, jest.fn())).toThrowError('Request handler already defined ');
});
});
describe('Given request handler is not defined', () => {
it('throws when executing the query', () => {
expect(() => mockClient.query({ query: queryTwo }))
.toThrowError('Request handler not defined for query');
});
});
});
describe('Client directives', () => {
// Note: React apollo 3 no longer passes @client directives down to the link (regardless of whether
// client-side resolvers have been configured).
// See https://github.com/apollographql/apollo-client/blob/master/CHANGELOG.md#apollo-client-300
describe('Given entire query is client-side and client side resolvers exist', () => {
const query = gql` { visibilityFilter @client }`;
let requestHandler: jest.Mock;
beforeEach(() => {
mockClient = createMockClient({
resolvers: {
Query: {
visibilityFilter: () => 'client resolver data',
},
},
});
requestHandler = jest.fn().mockResolvedValue({
data: {
visibilityFilter: 'handler data',
},
});
});
it('warns when request handler is added and does not handle request', async () => {
mockClient.setRequestHandler(query, requestHandler);
expect(console.warn).toBeCalledTimes(1);
expect(console.warn).toBeCalledWith('Warning: mock-apollo-client - The query is entirely client side (using @client directives) so the request handler will not be registered.');
const result = await mockClient.query({ query });
expect(result.data).toEqual({ visibilityFilter: 'client resolver data' });
expect(requestHandler).not.toHaveBeenCalled();
});
});
describe('Given entire query is client-side and client side resolvers do not exist', () => {
const query = gql` { visibilityFilter @client }`;
let requestHandler: jest.Mock;
beforeEach(() => {
mockClient = createMockClient({
resolvers: undefined,
});
requestHandler = jest.fn().mockResolvedValue({
data: {
visibilityFilter: 'handler data',
},
});
});
it('warns when request handler is added and does not handle request', async () => {
mockClient.setRequestHandler(query, requestHandler);
expect(console.warn).toBeCalledTimes(1);
expect(console.warn).toBeCalledWith('Warning: mock-apollo-client - The query is entirely client side (using @client directives) so the request handler will not be registered.');
const result = await mockClient.query({ query });
expect(result.data).toEqual({});
expect(requestHandler).not.toHaveBeenCalled();
});
});
describe('Given part of the query is client-side and client side resolvers exist', () => {
const query = gql`
query User {
user {
id
name
isLoggedIn @client
}
}
`;
let requestHandler: jest.Mock;
beforeEach(() => {
mockClient = createMockClient({
resolvers: {
Query: {
user: () => ({ isLoggedIn: true }),
},
},
});
requestHandler = jest.fn().mockResolvedValue({ data: { user: { id: 1, name: 'bob', isLoggedIn: false } } });
});
it('does not warn when request handler is added and handles request with merging', async () => {
mockClient.setRequestHandler(query, requestHandler);
expect(console.warn).not.toBeCalled();
const result = await mockClient.query({ query });
expect(result.data).toEqual({ user: { id: 1, name: 'bob', isLoggedIn: true } });
expect(requestHandler).toBeCalledTimes(1);
expect(console.warn).not.toBeCalled();
});
});
describe('Given part of the query is client-side and client side resolvers do not exist', () => {
const query = gql`
query User {
user {
id
name
isLoggedIn @client
}
}
`;
let requestHandler: jest.Mock;
beforeEach(() => {
mockClient = createMockClient({
resolvers: undefined,
});
requestHandler = jest.fn().mockResolvedValue({ data: { user: { id: 1, name: 'bob', isLoggedIn: false } } });
});
it('does not warn when request handler is added and handles request', async () => {
mockClient.setRequestHandler(query, requestHandler);
expect(console.warn).not.toBeCalled();
const result = await mockClient.query({ query });
expect(result.data).toEqual({ user: { id: 1, name: 'bob', isLoggedIn: false } });
expect(requestHandler).toBeCalledTimes(1);
});
});
});
describe('Connection directives', () => {
describe('Given query contains @connection directive', () => {
const query = gql`query A { items @connection(key: "foo") { id } }`;
let requestHandler: jest.Mock;
beforeEach(() => {
mockClient = createMockClient();
requestHandler = jest.fn().mockResolvedValue({
data: { items: [{ id: 1 }] },
});
});
it('correctly executes the registered request handler and returns the correct result', async () => {
mockClient.setRequestHandler(query, requestHandler);
const result = await mockClient.query({ query });
expect(result.data).toEqual({ items: [{ id: 1 }] });
expect(console.warn).not.toBeCalled();
});
});
});
describe('Fragments', () => {
describe('Given query contains a fragment spread', () => {
const query = gql`
query User {
user {
...UserDetails
}
}
fragment UserDetails on User {
id
name
}
`;
let requestHandler: jest.Mock;
beforeEach(() => {
mockClient = createMockClient();
requestHandler = jest.fn().mockResolvedValue({ data: { user: { __typename: 'User', id: 1, name: 'Bob' } } });
});
it('does not warn or error when request handler is added and request is handled', async () => {
mockClient.setRequestHandler(query, requestHandler);
expect(console.warn).not.toBeCalled();
expect(console.error).not.toBeCalled();
const result = await mockClient.query({ query });
expect(result.data).toEqual({ user: { id: 1, name: 'Bob' } });
expect(requestHandler).toBeCalledTimes(1);
expect(console.warn).not.toBeCalled();
expect(console.error).not.toBeCalled();
});
});
describe('Given possible types defined and query contains an inline fragment for a union type', () => {
const query = gql`
query Hardware {
hardware {
id
... on Memory {
size
}
... on Cpu {
speed
}
}
}
`;
let requestHandler: jest.Mock;
beforeEach(() => {
mockClient = createMockClient({
cache: new InMemoryCache({
possibleTypes: {
Hardware: ['Memory', 'Cpu'],
},
}),
});
requestHandler = jest.fn().mockResolvedValue({ data: { hardware: { __typename: 'Memory', id: 2, size: '16gb', speed: 'fast', brand: 'Samsung' } } });
});
it('does not warn or error when request handler is added and request is handled', async () => {
mockClient.setRequestHandler(query, requestHandler);
expect(console.warn).not.toBeCalled();
expect(console.error).not.toBeCalled();
const result = await mockClient.query({ query });
expect(result.data).toEqual({ hardware: { __typename: 'Memory', id: 2, size: '16gb' } });
expect(requestHandler).toBeCalledTimes(1);
expect(console.warn).not.toBeCalled();
expect(console.error).not.toBeCalled();
});
});
describe('Given mutation contains a fragment spread', () => {
const mutation = gql`
mutation AddUser($name: String!) {
addUser(name: $name) {
...UserDetails
}
}
fragment UserDetails on User {
id
name
}
`;
let requestHandler: jest.Mock;
beforeEach(() => {
mockClient = createMockClient();
requestHandler = jest.fn().mockResolvedValue({ data: { addUser: { __typename: 'User', id: 7, name: 'Barry' } } });
});
it('does not warn or error when request handler is added and request is handled', async () => {
mockClient.setRequestHandler(mutation, requestHandler);
expect(console.warn).not.toBeCalled();
expect(console.error).not.toBeCalled();
const result = await mockClient.mutate({ mutation, variables: { name: 'Barry' } });
expect(result.data).toEqual({ addUser: { __typename: 'User', id: 7, name: 'Barry' } });
expect(requestHandler).toBeCalledTimes(1);
expect(requestHandler).toBeCalledWith({ name: 'Barry' });
expect(console.warn).not.toBeCalled();
expect(console.error).not.toBeCalled();
});
});
describe('Given possible types are defined and mutation contains an inline fragment for a union type', () => {
const mutation = gql`
mutation UpdateHardware($id: String!, $quantity: Int!) {
updateHardware(id: $id, quantity: $quantity) {
id
quantity
... on Memory {
size
}
... on Cpu {
speed
}
}
}
`;
let requestHandler: jest.Mock;
beforeEach(() => {
mockClient = createMockClient({
cache: new InMemoryCache({
possibleTypes: {
Hardware: ['Memory', 'Cpu'],
},
}),
});
requestHandler = jest.fn().mockResolvedValue({
data: {
updateHardware: {
__typename: 'Memory',
id: 2,
quantity: 7,
size: '16gb',
},
},
});
});
it('does not warn or error when request handler is added and request is handled', async () => {
mockClient.setRequestHandler(mutation, requestHandler);
expect(console.warn).not.toBeCalled();
expect(console.error).not.toBeCalled();
const result = await mockClient.mutate({ mutation, variables: { id: 2, quantity: 7 } });
expect(requestHandler).toBeCalledWith({ id: 2, quantity: 7 });
expect(result.data).toEqual({ updateHardware: { __typename: 'Memory', id: 2, quantity: 7, size: '16gb' } });
expect(requestHandler).toBeCalledTimes(1);
expect(console.warn).not.toBeCalled();
expect(console.error).not.toBeCalled();
});
});
});
describe('Subscriptions', () => {
const queryOne = gql`query One {one}`;
const queryTwo = gql`query Two {two}`;
let mockSubscription: IMockSubscription<{ one: string }>;
let requestHandler: jest.Mock;
beforeEach(() => {
mockClient = createMockClient();
mockSubscription = createMockSubscription();
requestHandler = jest.fn().mockReturnValue(mockSubscription);
mockClient.setRequestHandler(queryOne, requestHandler);
});
describe('Given request handler is defined', () => {
let onNext: jest.Mock;
let onError: jest.Mock;
let onComplete: jest.Mock;
let clearMocks: () => void;
beforeEach(() => {
onNext = jest.fn();
onError = jest.fn();
onComplete = jest.fn();
clearMocks = () => {
onNext.mockClear();
onError.mockClear();
onComplete.mockClear();
};
const observable = mockClient.subscribe({ query: queryOne, variables: { a: 1 } });
observable.subscribe(
onNext,
onError,
onComplete);
});
it('returns an observable which produces the correct values until a GraphQL error is returned', async () => {
expect(onNext).not.toHaveBeenCalled();
expect(onError).not.toHaveBeenCalled();
expect(onComplete).not.toHaveBeenCalled();
clearMocks();
mockSubscription.next({ data: { one: 'A' } });
expect(onNext).toHaveBeenCalledTimes(1);
expect(onNext).toHaveBeenCalledWith({ data: { one: 'A' } });
expect(onError).not.toHaveBeenCalled();
expect(onComplete).not.toHaveBeenCalled();
clearMocks();
mockSubscription.next({ data: { one: 'B' } });
expect(onNext).toHaveBeenCalledTimes(1);
expect(onNext).toHaveBeenCalledWith({ data: { one: 'B' } });
expect(onError).not.toHaveBeenCalled();
expect(onComplete).not.toHaveBeenCalled();
clearMocks();
mockSubscription.next({ data: undefined, errors: [{ message: 'GraphQL Error' }] });
expect(onNext).not.toHaveBeenCalled();
expect(onError).toHaveBeenCalled();
expect(onError).toHaveBeenCalledWith(new Error('GraphQL Error'));
expect(onComplete).not.toHaveBeenCalled();
});
it('returns an observable which produces the correct values until a GraphQL network error is returned', async () => {
expect(onNext).not.toHaveBeenCalled();
expect(onError).not.toHaveBeenCalled();
expect(onComplete).not.toHaveBeenCalled();
clearMocks();
mockSubscription.next({ data: { one: 'A' } });
expect(onNext).toHaveBeenCalledTimes(1);
expect(onNext).toHaveBeenCalledWith({ data: { one: 'A' } });
expect(onError).not.toHaveBeenCalled();
expect(onComplete).not.toHaveBeenCalled();
clearMocks();
mockSubscription.error(new Error('GraphQL Network Error'));
expect(onNext).not.toHaveBeenCalled();
expect(onError).toHaveBeenCalledTimes(1);
expect(onError).toHaveBeenCalledWith(new Error('GraphQL Network Error'));
expect(onComplete).not.toHaveBeenCalled();
expect(console.warn).not.toHaveBeenCalled();
});
it('returns an observable which produces the correct values until the subscription is completed', async () => {
expect(onNext).not.toHaveBeenCalled();
expect(onError).not.toHaveBeenCalled();
expect(onComplete).not.toHaveBeenCalled();
clearMocks();
mockSubscription.next({ data: { one: 'A' } });
expect(onNext).toHaveBeenCalledTimes(1);
expect(onNext).toHaveBeenCalledWith({ data: { one: 'A' } });
expect(onError).not.toHaveBeenCalled();
expect(onComplete).not.toHaveBeenCalled();
clearMocks();
mockSubscription.complete();
expect(onNext).not.toHaveBeenCalled();
expect(onError).not.toHaveBeenCalled();
expect(onComplete).toHaveBeenCalledTimes(1);
expect(onComplete).toHaveBeenCalledWith();
expect(console.warn).not.toHaveBeenCalled();
});
it('throws when a handler is added for the same query', () => {
expect(() => mockClient.setRequestHandler(queryOne, jest.fn())).toThrowError('Request handler already defined ');
});
});
describe('Given request handler is not defined', () => {
it('throws when attempting to subscribe to query', () => {
expect(() => mockClient.subscribe({ query: queryTwo }))
.toThrowError('Request handler not defined for query');
});
});
});
}); | the_stack |
import { Automaton, State, Transition } from './automaton'
/**
* Interface of something that builds an automaton
* @author Arthur Trottier
* @author Charlotte Cogan
* @author Julien Aimonier-Davat
*/
interface AutomatonBuilder<T, P> {
build (): Automaton<T, P>
}
/**
* Perform the union of two sets
* @author Arthur Trottier
* @author Charlotte Cogan
* @author Julien Aimonier-Davat
* @param setA - first set
* @param setB - second set
* @return The union of the two sets
*/
export function union (setA: Set<number>, setB: Set<number>): Set<number> {
let union: Set<number> = new Set(setA)
setB.forEach(value => {
union.add(value)
})
return union
}
/**
* A GlushkovBuilder is responsible for build the automaton used to evaluate a SPARQL property path.
* @author Arthur Trottier
* @author Charlotte Cogan
* @author Julien Aimonier-Davat
*/
export class GlushkovBuilder implements AutomatonBuilder<number, string> {
private syntaxTree: any
private nullable: Map<number, boolean>
private first: Map<number, Set<number>>
private last: Map<number, Set<number>>
private follow: Map<number, Set<number>>
private predicates: Map<number, Array<string>>
private reverse: Map<number, boolean>
private negation: Map<number, boolean>
/**
* Constructor
* @param path - Path object
*/
constructor (path: any) {
this.syntaxTree = path
this.nullable = new Map<number, boolean>()
this.first = new Map<number, Set<number>>()
this.last = new Map<number, Set<number>>()
this.follow = new Map<number, Set<number>>()
this.predicates = new Map<number, Array<string>>()
this.reverse = new Map<number, boolean>()
this.negation = new Map<number, boolean>()
}
/**
* Numbers the nodes in a postorder manner
* @param node - syntactic tree's current node
* @param num - first identifier to be assigned
* @return root node identifier
*/
postfixNumbering (node: any, num: number = 1): number {
if (node.pathType !== 'symbol') {
for (let i = 0; i < node.items.length; i++) {
if (node.items[i].pathType === undefined) { // it's a leaf
node.items[i] = {
pathType: 'symbol',
item: node.items[i]
}
}
num = this.postfixNumbering(node.items[i], num)
}
}
node.id = num++
if (node.pathType === '!') {
num += 2 // to create the two nodes in the negation processing step
}
return num
}
symbolProcessing (node: any) {
this.nullable.set(node.id, false)
this.first.set(node.id, new Set<number>().add(node.id))
this.last.set(node.id, new Set<number>().add(node.id))
this.follow.set(node.id, new Set<number>())
this.predicates.set(node.id, [node.item])
this.reverse.set(node.id, false)
this.negation.set(node.id, false)
}
sequenceProcessing (node: any) {
let index
let nullableChild
let nullableNode = true
for (let i = 0; i < node.items.length; i++) {
nullableChild = this.nullable.get(node.items[i].id) as boolean
nullableNode = nullableNode && nullableChild
}
this.nullable.set(node.id, nullableNode)
let firstNode = new Set<number>()
index = -1
do {
index++
let firstChild = this.first.get(node.items[index].id) as Set<number>
firstNode = union(firstNode, firstChild)
nullableChild = this.nullable.get(node.items[index].id) as boolean
} while (index < node.items.length - 1 && nullableChild)
this.first.set(node.id, firstNode)
let lastNode = new Set<number>()
index = node.items.length
do {
index--
let lastChild = this.last.get(node.items[index].id) as Set<number>
lastNode = union(lastNode, lastChild)
nullableChild = this.nullable.get(node.items[index].id) as boolean
} while (index > 0 && nullableChild)
this.last.set(node.id, lastNode)
let self = this
for (let i = 0; i < node.items.length - 1; i++) {
let lastChild = this.last.get(node.items[i].id) as Set<number>
lastChild.forEach((value: number) => {
let suiv = i
let followChildLast = self.follow.get(value) as Set<number>
let nullableNextChild = false
do {
suiv++
let firstNextChild = self.first.get(node.items[suiv].id) as Set<number>
followChildLast = union(followChildLast, firstNextChild)
nullableNextChild = self.nullable.get(node.items[suiv].id) as boolean
} while (suiv < node.items.length - 1 && nullableNextChild)
self.follow.set(value, followChildLast)
})
}
}
unionProcessing (node: any) {
let nullableNode = false
for (let i = 1; i < node.items.length; i++) {
let nullableChild = this.nullable.get(node.items[i].id) as boolean
nullableNode = nullableNode || nullableChild
}
this.nullable.set(node.id, nullableNode)
let firstNode = new Set<number>()
for (let i = 0; i < node.items.length; i++) {
let firstChild = this.first.get(node.items[i].id) as Set<number>
firstNode = union(firstNode, firstChild)
}
this.first.set(node.id, firstNode)
let lastNode = new Set<number>()
for (let i = 0; i < node.items.length; i++) {
let lastChild = this.last.get(node.items[i].id) as Set<number>
lastNode = union(lastNode, lastChild)
}
this.last.set(node.id, lastNode)
}
oneOrMoreProcessing (node: any) {
let nullableChild = this.nullable.get(node.items[0].id) as boolean
this.nullable.set(node.id, nullableChild)
let firstChild = this.first.get(node.items[0].id) as Set<number>
this.first.set(node.id, firstChild)
let lastChild = this.last.get(node.items[0].id) as Set<number>
this.last.set(node.id, lastChild)
lastChild.forEach((value: number) => {
let followLastChild = this.follow.get(value) as Set<number>
this.follow.set(value, union(followLastChild, firstChild))
})
}
zeroOrOneProcessing (node: any) {
this.nullable.set(node.id, true)
let firstChild = this.first.get(node.items[0].id) as Set<number>
this.first.set(node.id, firstChild)
let lastChild = this.last.get(node.items[0].id) as Set<number>
this.last.set(node.id, lastChild)
}
zeroOrMoreProcessing (node: any) {
this.nullable.set(node.id, true)
let firstChild = this.first.get(node.items[0].id) as Set<number>
this.first.set(node.id, firstChild)
let lastChild = this.last.get(node.items[0].id) as Set<number>
this.last.set(node.id, lastChild)
lastChild.forEach((value: number) => {
let followLastChild = this.follow.get(value) as Set<number>
this.follow.set(value, union(followLastChild, firstChild))
})
}
searchChild (node: any): Set<number> {
return node.items.reduce((acc: any, n: any) => {
if (n.pathType === 'symbol') {
acc.add(n.id)
} else {
acc = union(acc, this.searchChild(n))
}
return acc
}, new Set())
}
negationProcessing (node: any) {
let negForward: Array<string> = new Array<string>()
let negBackward: Array<string> = new Array<string>()
this.searchChild(node).forEach((value: number) => {
let predicatesChild = this.predicates.get(value) as Array<string>
let isReverseChild = this.reverse.get(value) as boolean
if (isReverseChild) {
negBackward.push(...predicatesChild)
} else {
negForward.push(...predicatesChild)
}
})
let firstNode = new Set<number>()
let lastNode = new Set<number>()
if (negForward.length > 0) {
let id = node.id + 1
this.nullable.set(id, false)
this.first.set(id, new Set<number>().add(id))
this.last.set(id, new Set<number>().add(id))
this.follow.set(id, new Set<number>())
this.predicates.set(id, negForward)
this.reverse.set(id, false)
this.negation.set(id, true)
firstNode.add(id)
lastNode.add(id)
}
if (negBackward.length > 0) {
let id = node.id + 2
this.nullable.set(id, false)
this.first.set(id, new Set<number>().add(id))
this.last.set(id, new Set<number>().add(id))
this.follow.set(id, new Set<number>())
this.predicates.set(id, negBackward)
this.reverse.set(id, true)
this.negation.set(id, true)
firstNode.add(id)
lastNode.add(id)
}
this.nullable.set(node.id, false)
this.first.set(node.id, firstNode)
this.last.set(node.id, lastNode)
}
inverseProcessing (node: any) {
let nullableChild = this.nullable.get(node.items[0].id) as boolean
this.nullable.set(node.id, nullableChild)
let firstChild = this.first.get(node.items[0].id) as Set<number>
this.last.set(node.id, firstChild)
let lastChild = this.last.get(node.items[0].id) as Set<number>
this.first.set(node.id, lastChild)
let childInverse = this.searchChild(node)
let followTemp = new Map<number, Set<number>>()
childInverse.forEach((nodeToReverse: number) => {
followTemp.set(nodeToReverse, new Set<number>())
})
childInverse.forEach((nodeToReverse: number) => {
let isReverseNodeToReverse = this.reverse.get(nodeToReverse) as boolean
this.reverse.set(nodeToReverse, !isReverseNodeToReverse)
let followeesNodeToReverse = this.follow.get(nodeToReverse) as Set<number>
followeesNodeToReverse.forEach((followee) => {
if (childInverse.has(followee)) {
(followTemp.get(followee) as Set<number>).add(nodeToReverse)
followeesNodeToReverse.delete(followee)
}
})
})
childInverse.forEach((child) => {
this.follow.set(child, union(
this.follow.get(child) as Set<number>,
followTemp.get(child) as Set<number>
))
})
}
nodeProcessing (node: any) {
switch (node.pathType) {
case 'symbol':
this.symbolProcessing(node)
break
case '/':
this.sequenceProcessing(node)
break
case '|':
this.unionProcessing(node)
break
case '+':
this.oneOrMoreProcessing(node)
break
case '?':
this.zeroOrOneProcessing(node)
break
case '*':
this.zeroOrMoreProcessing(node)
break
case '!':
this.negationProcessing(node)
break
case '^':
this.inverseProcessing(node)
break
}
}
treeProcessing (node: any) {
if (node.pathType !== 'symbol') {
for (let i = 0; i < node.items.length; i++) {
this.treeProcessing(node.items[i])
}
}
this.nodeProcessing(node)
}
/**
* Build a Glushkov automaton to evaluate the SPARQL property path
* @return The Glushkov automaton used to evaluate the SPARQL property path
*/
build (): Automaton<number, string> {
// Assigns an id to each syntax tree's node. These ids will be used to build and name the automaton's states
this.postfixNumbering(this.syntaxTree)
// computation of first, last, follow, nullable, reverse and negation
this.treeProcessing(this.syntaxTree)
let glushkov = new Automaton<number, string>()
let root = this.syntaxTree.id // root node identifier
// Creates and adds the initial state
let nullableRoot = this.nullable.get(root) as boolean
let initialState = new State(0, true, nullableRoot)
glushkov.addState(initialState)
// Creates and adds the other states
let lastRoot = this.last.get(root) as Set<number>
for (let id of Array.from(this.predicates.keys())) {
let isFinal = lastRoot.has(id)
glushkov.addState(new State(id, false, isFinal))
}
// Adds the transitions that start from the initial state
let firstRoot = this.first.get(root) as Set<number>
firstRoot.forEach((value: number) => {
let toState = glushkov.findState(value) as State<number>
let reverse = this.reverse.get(value) as boolean
let negation = this.negation.get(value) as boolean
let predicates = this.predicates.get(value) as Array<string>
let transition = new Transition(initialState, toState, reverse, negation, predicates)
glushkov.addTransition(transition)
})
// Ads the transitions between states
for (let from of Array.from(this.follow.keys())) {
let followFrom = this.follow.get(from) as Set<number>
followFrom.forEach((to: number) => {
let fromState = glushkov.findState(from) as State<number>
let toState = glushkov.findState(to) as State<number>
let reverse = this.reverse.get(to) as boolean
let negation = this.negation.get(to) as boolean
let predicates = this.predicates.get(to) as Array<string>
let transition = new Transition(fromState, toState, reverse, negation, predicates)
glushkov.addTransition(transition)
})
}
return glushkov
}
} | the_stack |
/// <reference path="../typings/tsd.d.ts" />
/// <reference path="./estree-x.d.ts" />
import fs = require("fs");
import path = require("path");
import assert = require("assert");
import util = require("util");
import child_process = require("child_process");
import acorn = require("../js/acorn/acorn_csp");
import StringMap = require("../lib/StringMap");
import hir = require("./hir");
import cxxbackend = require("./cxxbackend");
export interface IErrorReporter
{
error (loc: ESTree.SourceLocation, msg: string) : void;
warning (loc: ESTree.SourceLocation, msg: string) : void;
note (loc: ESTree.SourceLocation, msg: string) : void;
errorCount (): number;
}
export class Options
{
dumpAST = false;
dumpHIR = false;
strictMode = true;
debug = false;
compileOnly = false;
sourceOnly = false;
outputName: string = null;
verbose = false;
moduleDirs: string[] = [];
includeDirs: string[] = [];
libDirs: string[] = [];
libs: string[] = ["pcre2-8", "jsruntime", "dtoa", "uv"];
buildDir: string = ".jsbuild";
}
class NT<T extends ESTree.Node>
{
constructor (public name: string) {}
toString (): string { return this.name; }
isTypeOf (node: ESTree.Node): T
{
return node && node.type === this.name ? <T>node : null;
}
cast (node: ESTree.Node): T
{
if (node && node.type === this.name)
return <T>node;
else
assert(false, `node.type/${node.type}/ === ${this.name}`);
}
eq (node: ESTree.Node): boolean
{
return node && node.type === this.name;
}
static EmptyStatement = new NT<ESTree.EmptyStatement>("EmptyStatement");
static BlockStatement = new NT<ESTree.BlockStatement>("BlockStatement");
static ExpressionStatement = new NT<ESTree.ExpressionStatement>("ExpressionStatement");
static IfStatement = new NT<ESTree.IfStatement>("IfStatement");
static LabeledStatement = new NT<ESTree.LabeledStatement>("LabeledStatement");
static BreakStatement = new NT<ESTree.BreakStatement>("BreakStatement");
static ContinueStatement = new NT<ESTree.ContinueStatement>("ContinueStatement");
static WithStatement = new NT<ESTree.WithStatement>("WithStatement");
static SwitchStatement = new NT<ESTree.SwitchStatement>("SwitchStatement");
static SwitchCase = new NT<ESTree.SwitchCase>("SwitchCase");
static ReturnStatement = new NT<ESTree.ReturnStatement>("ReturnStatement");
static ThrowStatement = new NT<ESTree.ThrowStatement>("ThrowStatement");
static TryStatement = new NT<ESTree.TryStatement>("TryStatement");
static CatchClause = new NT<ESTree.CatchClause>("CatchClause");
static WhileStatement = new NT<ESTree.WhileStatement>("WhileStatement");
static DoWhileStatement = new NT<ESTree.DoWhileStatement>("DoWhileStatement");
static ForStatement = new NT<ESTree.ForStatement>("ForStatement");
static ForInStatement = new NT<ESTree.ForInStatement>("ForInStatement");
static ForOfStatement = new NT<ESTree.ForOfStatement>("ForOfStatement");
static DebuggerStatement = new NT<ESTree.DebuggerStatement>("DebuggerStatement");
static FunctionDeclaration = new NT<ESTree.FunctionDeclaration>("FunctionDeclaration");
static VariableDeclaration = new NT<ESTree.VariableDeclaration>("VariableDeclaration");
static VariableDeclarator = new NT<ESTree.VariableDeclarator>("VariableDeclarator");
static Literal = new NT<ESTree.Literal>("Literal");
static Identifier = new NT<ESTree.Identifier>("Identifier");
static ThisExpression = new NT<ESTree.ThisExpression>("ThisExpression");
static ArrayExpression = new NT<ESTree.ArrayExpression>("ArrayExpression");
static ObjectExpression = new NT<ESTree.ObjectExpression>("ObjectExpression");
static Property = new NT<ESTree.Property>("Property");
static FunctionExpression = new NT<ESTree.FunctionExpression>("FunctionExpression");
static SequenceExpression = new NT<ESTree.SequenceExpression>("SequenceExpression");
static UnaryExpression = new NT<ESTree.UnaryExpression>("UnaryExpression");
static BinaryExpression = new NT<ESTree.BinaryExpression>("BinaryExpression");
static AssignmentExpression = new NT<ESTree.AssignmentExpression>("AssignmentExpression");
static UpdateExpression = new NT<ESTree.UpdateExpression>("UpdateExpression");
static LogicalExpression = new NT<ESTree.LogicalExpression>("LogicalExpression");
static ConditionalExpression = new NT<ESTree.ConditionalExpression>("ConditionalExpression");
static CallExpression = new NT<ESTree.CallExpression>("CallExpression");
static NewExpression = new NT<ESTree.NewExpression>("NewExpression");
static MemberExpression = new NT<ESTree.MemberExpression>("MemberExpression");
}
class Variable
{
ctx: FunctionContext;
name: string;
readOnly: boolean = false;
constantValue: hir.RValue = null;
declared: boolean = false;
initialized: boolean = false; //< function declarations and built-in values like 'this'
assigned: boolean = false;
accessed: boolean = false;
escapes: boolean = false;
/**
* Prevent this variable from being marked as escaping when accessed in 'try' block. We mark all
* variables accessed in a try block as escaping, very conservatively, because we currently lack
* the ability to analyze liveness. However in some specific cases we do know that the variable
* doesn't need to be escaped, and there this flag comes along.
*/
overrideEscapeInTryBlocks: boolean = false;
funcRef: hir.FunctionBuilder = null;
consRef: hir.FunctionBuilder = null;
hvar: hir.Var = null;
constructor (ctx: FunctionContext, name: string)
{
this.ctx = ctx;
this.name = name;
}
setConstant (constantValue: hir.RValue): void
{
this.readOnly = true;
this.constantValue = constantValue;
}
setAccessed (need: boolean, ctx: FunctionContext): void
{
if (need) {
this.accessed = true;
// Note: if we are inside a try block, we mark all variables as escaping
// it pessimizes the code a lot, but for now guarantees correctness
if (ctx !== this.ctx || (ctx.tryStack.length && !this.overrideEscapeInTryBlocks))
this.escapes = true;
}
}
setAssigned (ctx: FunctionContext): void
{
this.assigned = true;
// Note: if we are inside a try block, we mark all variables as escaping
// it pessimizes the code a lot, but for now guarantees correctness
if (ctx !== this.ctx || (ctx.tryStack.length && !this.overrideEscapeInTryBlocks))
this.escapes = true;
}
}
class Scope
{
ctx: FunctionContext;
/**
* A scope where the 'var'-s bubble up to. Normally, in JavaScript only function scopes do
* that (in C every scope is like that), but we would like the ability to designate other
* scopes with such behavior for source transformations.
*/
isVarScope: boolean = false;
parent: Scope;
level: number;
varScope: Scope; // reference to the closest 'var scope'
private vars: StringMap<Variable>;
constructor (ctx: FunctionContext, isVarScope: boolean, parent: Scope)
{
this.ctx = ctx;
this.isVarScope = isVarScope;
this.parent = parent;
this.level = parent ? parent.level + 1 : 0;
this.varScope = isVarScope || !parent ? this : parent.varScope;
this.vars = new StringMap<Variable>();
}
newVariable (name: string, hvar?: hir.Var): Variable
{
var variable = new Variable(this.ctx, name);
variable.hvar = hvar ? hvar : this.ctx.builder.newVar(name);
this.setVar(variable);
return variable;
}
newAnonymousVariable (name: string, hvar?: hir.Var): Variable
{
var variable = new Variable(this.ctx, name);
variable.hvar = hvar ? hvar : this.ctx.builder.newVar(name);
this.setAnonymousVar(variable);
return variable;
}
newConstant (name: string, value: hir.RValue): Variable
{
var variable = new Variable(this.ctx, name);
variable.setConstant(value);
this.setVar(variable);
variable.declared = true;
variable.initialized = true;
return variable;
}
getVar (name: string): Variable
{
return this.vars.get(name);
}
setVar (v: Variable): void
{
this.vars.set(v.name, v);
this.ctx.vars.push(v);
}
setAnonymousVar (v: Variable): void
{
this.ctx.vars.push(v);
}
lookup (name: string, lastScope?: Scope): Variable
{
var v: Variable;
var scope: Scope = this;
do {
if (v = scope.vars.get(name))
return v;
if (scope === lastScope)
break;
} while (scope = scope.parent);
return null;
}
}
const enum LabelKind
{
INTERNAL,
LOOP,
SWITCH,
NAMED,
}
class Label
{
prev: Label = null;
constructor (
public kind: LabelKind,
public name: string, public loc: ESTree.SourceLocation,
public breakLab: hir.Label, public continueLab: hir.Label
)
{}
}
class TryBlock
{
topLabel: Label; //< the top of the label stack at the moment this block was created
controlVar: Variable;
exitHandler: hir.Label;
// Keep track of all jumps crossing a 'try' handler and assign consecutive
// numbers to each
jumpsSet: { [key: number]: number } = Object.create(null);
outgoingJumps: hir.Label[] = [];
constructor(topLabel: Label, controlVar: Variable, exitHandler: hir.Label)
{
this.topLabel = topLabel;
this.controlVar = controlVar;
this.exitHandler = exitHandler;
}
// Adds a jump target and returns the value that should be set in the control variable to
// go there through the finally block
addJump (target: hir.Label): number
{
var n: any;
if ((n = this.jumpsSet[target.id]) !== void 0)
return <number>n;
var index = this.outgoingJumps.length;
this.outgoingJumps.push(target);
this.jumpsSet[target.id] = index;
return index;
}
}
class FunctionContext
{
parent: FunctionContext;
name: string;
strictMode: boolean;
scope: Scope;
thisParam: Variable;
argumentsVar: Variable = null;
labelList: Label = null;
labels = new StringMap<Label>();
/** Used for 'return' from blocks guarded with try/finally */
returnPad: Label = null;
returnValue: Variable = null;
tryStack: TryBlock[] = [];
vars: Variable[] = [];
builder: hir.FunctionBuilder = null;
private tempStack: hir.Local[] = [];
constructor (parent: FunctionContext, parentScope: Scope, name: string, builder: hir.FunctionBuilder)
{
this.parent = parent;
this.name = name || null;
this.builder = builder;
this.strictMode = parent && parent.strictMode;
this.scope = new Scope(this, true, parentScope);
this.thisParam = this.addParam("this");
this.returnPad = new Label(LabelKind.INTERNAL, null, null, this.builder.newLabel(), null);
this.pushLabel(this.returnPad);
}
close (): void
{
this.vars.forEach( (v: Variable) => {
if (v.hvar)
this.builder.setVarAttributes(v.hvar,
v.escapes, v.accessed || v.assigned, v.initialized && !v.assigned, v.funcRef, v.consRef
);
});
this.builder.close();
}
findLabel (name: string): Label
{
return this.labels.get(name);
}
findAnonBreakContinueLabel (isBreak: boolean): Label
{
for ( var label = this.labelList; label; label = label.prev ) {
if (!label.name) {
switch (label.kind) {
case LabelKind.LOOP:
return label;
case LabelKind.SWITCH:
case LabelKind.NAMED:
if (isBreak)
return label;
break;
}
}
}
return null;
}
pushLabel (label: Label): void
{
if (label.name)
this.labels.set(label.name,label);
label.prev = this.labelList;
this.labelList = label;
}
popLabel (): void
{
var label = this.labelList;
if (label.name)
this.labels.remove(label.name);
this.labelList = label.prev;
label.prev = null; // Facilitate GC
}
pushTryBlock (): TryBlock
{
var controlVar = this.scope.newAnonymousVariable("");
controlVar.overrideEscapeInTryBlocks = true;
var tryBlock = new TryBlock(this.labelList, controlVar, this.builder.newLabel());
this.tryStack.push(tryBlock);
return tryBlock;
}
popTryBlock (tryBlock: TryBlock): void
{
var popped = this.tryStack.pop();
assert(popped === tryBlock);
}
/**
* Generate a goto to a label in the label stack. Normally it would be a very simple operation, but it is
* complicated by the presence of try blocks. If our jump crosses such a block, it must execute its exit handler.
* To do that, we must either inline the contents of the exit handler before we do the jump (that is what production
* compilers do, as far as I can tell), or we can apply our strategy (described below), which is simpler to
* implement and hopefully leads to less code bloat, possibly with some performance cost (though I would argue
* that try blocks have never been the paragon of performance). Anyway, our long term plan is to eventually
* do the inlining, which enables more optimization, but for now this is simpler.
*
* The code in each exit handler is generated only once and has a 'control variable' assigned to it. The value
* of the variable determines where to jump after the block executes. Note that 'return' is also just a goto.
*
* Nested try blocks are also handled naturally by this scheme where the inner one jumps to the outer
* one after executing.
*
* Example:
* <pre>
* function () {
* try {
* if (foo)
* return;
* bar;
* } finally {
* baz;
* }
* bla;
* }
* </pre>
* It should produce code (conceptually) looking like:
* <pre>
* var control_var;
* if (setjmp(...) != 0) goto EXC_HANDLER;
* if (foo) {
* control_var = 1;
* goto FIN_HANDLER;
* }
* bar;
* control_var = 2;
* goto FIN_HANDLER;
* EXC_HANDLER:
* control_var = 0;
* goto FIN_HANDLER;
* FIN_HANDLER:
* baz;
* switch (control_var) {
* case 0: rethrow_exception();
* case 1: goto EXIT;
* case 2: goto B1;
* }
* B1:
* bla;
* goto EXIT;
* EXIT:
* return;
* </pre>
*/
genGoto (label: Label, target: hir.Label): void
{
var lowestIndex: number; // lowest index in tryStack
var highestIndex: number = -1; // highest index in tryStack
// Check which try blocks we are crossing with this jump. To accomplish that, we walk backwards
// the label stack until after we find our target label. These are all the active labels we could potentially
// ever cross. In the process, each time we match the current label from the label stack to the top of tryStack,
// we mark it as being crossed and move to the next element in tryStack
var tryIndex: number = this.tryStack.length - 1;
for ( var curLab = this.labelList; curLab && tryIndex >= 0; curLab = curLab.prev ) {
for ( ; tryIndex >= 0 && this.tryStack[tryIndex].topLabel === curLab; --tryIndex ) {
if (highestIndex < 0)
highestIndex = tryIndex;
lowestIndex = tryIndex;
}
if (curLab === label)
break;
}
if (highestIndex < 0) { // A simple jump, not crossing any try/finally blocks
this.builder.genGoto(target);
return;
}
var curTarget = target;
for ( tryIndex = lowestIndex; tryIndex <= highestIndex; ++tryIndex ) {
var block = this.tryStack[tryIndex];
var controlValue = block.addJump(curTarget);
block.controlVar.setAssigned(this);
this.builder.genAssign(block.controlVar.hvar, hir.wrapImmediate(controlValue));
curTarget = block.exitHandler;
}
this.builder.genGoto(curTarget);
}
genReturn (value: hir.RValue): void
{
this.releaseTemp(value);
if (!this.tryStack.length) { // simple case, no exception blocks to worry about
this.builder.genRet(value);
return;
}
if (!this.returnValue) {
this.returnValue = this.scope.newAnonymousVariable("returnValue");
this.returnValue.overrideEscapeInTryBlocks = true;
}
this.returnValue.setAssigned(this);
this.builder.genAssign(this.returnValue.hvar, value);
this.genGoto(this.returnPad, this.returnPad.breakLab);
if (!this.returnPad.breakLab.bb) { // If we haven't generated the return pad yet
this.builder.genLabel(this.returnPad.breakLab);
this.returnValue.setAccessed(true, this);
this.builder.genRet(this.returnValue.hvar);
}
}
genTryBlockSwitch (tryBlock: TryBlock): void
{
// Dispatch every outgoing jump to its actual destination
var values: number[] = new Array<number>(tryBlock.outgoingJumps.length);
for ( var i = 0; i < values.length; ++i )
values[i] = i;
tryBlock.controlVar.setAccessed(true, this);
this.builder.genSwitch(tryBlock.controlVar.hvar, null, values, tryBlock.outgoingJumps);
}
public allocTemp (): hir.Local
{
if (!this.tempStack.length)
{
var t = this.builder.newLocal();
t.isTemp = true;
this.tempStack.push(t );
}
var tmp = this.tempStack.pop();
//console.log(`allocTemp = ${tmp.id}`);
return tmp;
}
public allocSpecific (t: hir.Local): void
{
assert(t.isTemp);
for ( var i = this.tempStack.length - 1; i >= 0; --i )
if (this.tempStack[i] === t) {
//console.log(`allocSpecific = ${t.id}`);
this.tempStack.splice(i, 1);
return;
}
assert(false, "specific temporary is not available");
return null;
}
public releaseTemp (t: hir.RValue ): void
{
var l: hir.Local;
if (l = hir.isTempLocal(t)) {
//console.log(`releaseTemp ${l.id}`);
//for ( var i = this.tempStack.length - 1; i >= 0; --i )
// assert(this.tempStack[i] !== l, `Re-inserting temp ${l.id}`);
this.tempStack.push(l);
}
}
public addClosure (name: string): hir.FunctionBuilder
{
return this.builder.newClosure(name);
}
public addBuiltinClosure (name: string, mangledName: string, runtimeVar: string): hir.FunctionBuilder
{
return this.builder.newBuiltinClosure(name, mangledName, runtimeVar);
}
public addParam (name: string): Variable
{
var param = this.builder.newParam(name);
var v = this.scope.newVariable(name, param.variable);
v.initialized = true;
v.declared = true;
return v;
}
}
class Module
{
id: string;
path: string;
printable: string;
notFound: boolean;
modVar: Variable = null;
constructor (id: string, path: string)
{
this.id = id;
this.path = path;
this.printable = id;
this.notFound = path === null;
}
}
function startsWith (big: string, prefix: string): boolean
{
return big.length >= prefix.length && big.slice(0, prefix.length) === prefix;
}
function checkReadAccess (p: string): boolean
{
try { (<any>fs).accessSync(p, (<any>fs).R_OK); } catch (e) {
return false;
}
return true;
}
class Modules
{
private resolved = new StringMap<Module>();
private queue: Module[] = [];
public paths: string[] = [];
constructor (paths: string[])
{
// Make sure all paths are absolute
for (var i = 0; i < paths.length; ++i ) {
if (paths[i])
this.paths.push(path.isAbsolute(paths[i]) ? paths[i] : path.resolve(paths[i]));
}
}
private resolvePath (trypath: string): string
{
try {
var pkg = JSON.parse(fs.readFileSync(path.join(trypath, "package.json"), "utf-8"));
if (pkg["main"])
trypath = path.resolve(trypath, pkg["main"]);
else
trypath = path.join(trypath, "index.js");
} catch (e) {
}
if (!path.extname(trypath))
trypath += ".js";
return checkReadAccess(trypath) ? trypath : null;
}
private tryResolve (dirname: string, modname: string): Module
{
var trypath = path.resolve(dirname, modname);
var m: Module;
if (m = this.resolved.get(trypath))
return m;
var resolved = this.resolvePath(trypath);
if (resolved) {
m = new Module(trypath, resolved);
this.resolved.set(trypath, m);
this.queue.push(m);
return m;
} else {
return null;
}
}
resolve (dirname: string, modname: string): Module
{
var m: Module;
if (startsWith(modname, "./") || startsWith(modname, "../") || path.isAbsolute(modname)) {
if (m = this.tryResolve(dirname, modname))
return m;
modname = path.resolve(dirname, modname);
} else {
if (m = this.tryResolve(path.join(dirname, "node_modules"), modname))
return m;
for (var i = 0; i < this.paths.length; ++i ) {
if (m = this.tryResolve(this.paths[i], modname))
return m;
}
}
// Register it as failed to resolve
m = new Module(modname, null);
this.resolved.set(modname, m);
this.queue.push(m);
return m;
}
next (): Module
{
return this.queue.length > 0 ? this.queue.shift() : null;
}
}
class Runtime
{
ctx: FunctionContext;
moduleRequire: Variable = null;
defineModule: Variable = null;
_defineAccessor: Variable = null;
regExp: Variable = null;
runtimeInit: Variable = null;
runtimeEventLoop: Variable = null;
constructor (ctx: FunctionContext)
{
this.ctx = ctx;
}
public lookupSymbols (coreScope: Scope): void
{
if (!this.moduleRequire)
this.moduleRequire = coreScope.lookup("moduleRequire");
if (!this.defineModule)
this.defineModule = coreScope.lookup("defineModule");
if (!this._defineAccessor)
this._defineAccessor = coreScope.lookup("_defineAccessor");
if (!this.regExp)
this.regExp = coreScope.lookup("$RegExp");
if (!this.runtimeInit)
this.runtimeInit = coreScope.lookup("runtimeInit");
if (!this.runtimeEventLoop)
this.runtimeEventLoop = coreScope.lookup("runtimeEventLoop");
}
public allSymbolsDefined (): boolean
{
return !!(
this.moduleRequire &&
this.defineModule &&
this._defineAccessor &&
this.regExp &&
this.runtimeInit
);
}
}
class SpecialVars
{
require: Variable = null;
_defineAccessor: Variable = null;
regExp: Variable = null;
constructor (r?: Runtime)
{
if (r) {
this.require = r.moduleRequire;
this._defineAccessor = r._defineAccessor;
this.regExp = r.regExp;
}
}
}
class AsmBinding {
public used: boolean = false;
public hv: hir.RValue = null;
public result: boolean = false;
constructor(public index: number, public name: string, public e: ESTree.Expression) {}
}
/** A property descriptor in an "ObjectExpression" */
class ObjectExprProp
{
public value: ESTree.Expression = null;
public getter: ESTree.FunctionExpression = null;
public setter: ESTree.FunctionExpression = null;
constructor(public name: string)
{}
}
function compileSource (
m_scope: Scope, m_undefinedVarScope: Scope,
m_fileName: string, m_reporter: IErrorReporter,
m_specVars: SpecialVars, m_modules: Modules,
m_options: Options
): boolean
{
var m_absFileName = path.resolve(m_fileName);
var m_dirname = path.dirname(m_absFileName);
var m_input: string;
var m_errors = 0;
if (m_options.verbose)
console.log("Compiling", m_fileName);
compileIt();
return m_errors === 0;
function compileIt (): void
{
function adjustRegexLiteral(key: any, value: any)
{
if (key === 'value' && value instanceof RegExp) {
value = value.toString();
}
return value;
}
var prog: ESTree.Program;
if ((prog = parse(m_fileName))) {
if (m_options.dumpAST) {
// Special handling for regular expression literal since we need to
// convert it to a string literal, otherwise it will be decoded
// as object "{}" and the regular expression would be lost.
console.log(JSON.stringify(prog, adjustRegexLiteral, 4));
}
compileBody(m_scope, prog.body, prog, false);
}
}
function error (loc: ESTree.SourceLocation, msg: string)
{
++m_errors;
m_reporter.error(loc, msg);
}
function warning (loc: ESTree.SourceLocation, msg: string)
{
m_reporter.warning(loc, msg);
}
function note (loc: ESTree.SourceLocation, msg: string)
{
m_reporter.note(loc, msg);
}
function location (node: ESTree.Node): ESTree.SourceLocation
{
if (!node.loc) {
var pos = acorn.getLineInfo(m_input, node.start);
return { source: m_fileName, start: pos, end: pos };
} else {
return node.loc;
}
}
function setSourceLocation (target: hir.SourceLocation, node: ESTree.Node): void
{
var loc = location(node);
hir.setSourceLocation(target, loc.source, loc.start.line, loc.start.column);
}
function parse (fileName: string): ESTree.Program
{
var options: acorn.Options = {
strict: m_options.strictMode,
ecmaVersion: 5,
//sourceType: "module",
allowReserved: false,
allowHashBang: true,
locations: false,
};
try {
m_input = fs.readFileSync(fileName, 'utf-8');
} catch (e) {
error(null, e.message);
return null;
}
try {
return acorn.parse(m_input, options);
} catch (e) {
if (e instanceof SyntaxError)
error({source: fileName, start: e.loc, end: e.loc}, e.message);
else
error(null, e.message);
return null;
}
}
function matchStrictMode (stmt: ESTree.Statement): boolean
{
var es: ESTree.ExpressionStatement;
var lit: ESTree.Literal;
if (es = NT.ExpressionStatement.isTypeOf(stmt))
if (lit = NT.Literal.isTypeOf(es.expression))
if (lit.value === "use strict")
return true;
return false;
}
function compileFunction (parentScope: Scope, ast: ESTree.Function, funcRef: hir.FunctionBuilder): FunctionContext
{
var funcCtx = new FunctionContext(parentScope && parentScope.ctx, parentScope, funcRef.name, funcRef);
var funcScope = funcCtx.scope;
setSourceLocation(funcCtx.builder, ast);
// Declare the parameters
// Create a HIR param+var binding for each of them
ast.params.forEach( (pat: ESTree.Pattern): void => {
var ident = NT.Identifier.cast(pat);
var v: Variable;
if (v = funcScope.getVar(ident.name)) {
(funcCtx.strictMode ? error : warning)(location(ident), `parameter '${ident.name}' already declared`);
// Overwrite the assigned hvar. When we have duplicate parameter names, the last one wins
var param = funcCtx.builder.newParam(ident.name);
v.hvar = param.variable;
} else {
funcCtx.addParam(ident.name);
}
});
var builder = funcCtx.builder;
var entryLabel = builder.newLabel();
var nextLabel = builder.newLabel();
builder.genLabel(entryLabel);
builder.genGoto(nextLabel);
builder.genLabel(nextLabel);
var bodyBlock: ESTree.BlockStatement;
if (bodyBlock = NT.BlockStatement.isTypeOf(ast.body))
compileBody(funcScope, bodyBlock.body, bodyBlock, true);
else
error(location(ast.body), "ES6 not supported");
if (funcCtx.argumentsVar && funcCtx.argumentsVar.accessed) {
var bb = builder.getCurBB();
builder.closeBB();
builder.openLabel(entryLabel);
builder.genCreateArguments(funcCtx.argumentsVar.hvar);
builder.openBB(bb);
}
funcCtx.close();
return funcCtx;
}
/**
*
* @param scope
* @param body
* @param parentNode the parent node of 'body' used only for error location
* @param functionBody is this a function body (whether to generate 'arguments')
*/
function compileBody (scope: Scope, body: ESTree.Statement[], parentNode: ESTree.Node, functionBody: boolean): void
{
var startIndex: number = 0;
if (body.length && matchStrictMode(body[0])) {
startIndex = 1;
if (!scope.ctx.strictMode) {
scope.ctx.strictMode = true;
note(location(body[0]), "strict mode enabled");
}
}
// Scan for declarations
for (var i = startIndex, e = body.length; i < e; ++i)
scanStatementForDeclarations(scope, body[i]);
if (functionBody) {
if (scope.lookup("arguments", scope.ctx.scope)) {
warning(location(parentNode), "'arguments' bound to a local");
} else {
var ctx = scope.ctx;
ctx.argumentsVar = ctx.scope.newVariable("arguments");
ctx.argumentsVar.declared = true;
ctx.argumentsVar.initialized = true;
}
}
// Bind
for (var i = startIndex, e = body.length; i < e; ++i)
compileStatement(scope, body[i], null);
}
function scanStatementForDeclarations (scope: Scope, stmt: ESTree.Statement): void
{
if (!stmt)
return;
switch (stmt.type) {
case "BlockStatement":
var blockStatement: ESTree.BlockStatement = NT.BlockStatement.cast(stmt);
blockStatement.body.forEach((s: ESTree.Statement) => {
scanStatementForDeclarations(scope, s);
});
break;
case "IfStatement":
var ifStatement: ESTree.IfStatement = NT.IfStatement.cast(stmt);
if (ifStatement.consequent)
scanStatementForDeclarations(scope, ifStatement.consequent);
if (ifStatement.alternate)
scanStatementForDeclarations(scope, ifStatement.alternate);
break;
case "LabeledStatement":
var labeledStatement: ESTree.LabeledStatement = NT.LabeledStatement.cast(stmt);
scanStatementForDeclarations(scope, labeledStatement.body);
break;
case "WithStatement":
var withStatement: ESTree.WithStatement = NT.WithStatement.cast(stmt);
scanStatementForDeclarations(scope, withStatement.body);
break;
case "SwitchStatement":
var switchStatement: ESTree.SwitchStatement = NT.SwitchStatement.cast(stmt);
switchStatement.cases.forEach((sc: ESTree.SwitchCase) => {
sc.consequent.forEach((s: ESTree.Statement) => {
scanStatementForDeclarations(scope, s);
});
});
break;
case "TryStatement":
var tryStatement: ESTree.TryStatement = NT.TryStatement.cast(stmt);
scanStatementForDeclarations(scope, tryStatement.block);
if (tryStatement.handler)
scanStatementForDeclarations(scope, tryStatement.handler.body);
if (tryStatement.finalizer)
scanStatementForDeclarations(scope, tryStatement.finalizer);
break;
case "WhileStatement":
var whileStatement: ESTree.WhileStatement = NT.WhileStatement.cast(stmt);
scanStatementForDeclarations(scope, whileStatement.body);
break;
case "DoWhileStatement":
var doWhileStatement: ESTree.DoWhileStatement = NT.DoWhileStatement.cast(stmt);
scanStatementForDeclarations(scope, doWhileStatement.body);
break;
case "ForStatement":
var forStatement: ESTree.ForStatement = NT.ForStatement.cast(stmt);
var forStatementInitDecl: ESTree.VariableDeclaration;
if (forStatement.init)
if (forStatementInitDecl = NT.VariableDeclaration.isTypeOf(forStatement.init))
scanStatementForDeclarations(scope, forStatementInitDecl);
scanStatementForDeclarations(scope, forStatement.body);
break;
case "ForInStatement":
var forInStatement: ESTree.ForInStatement = NT.ForInStatement.cast(stmt);
var forInStatementLeftDecl: ESTree.VariableDeclaration;
if (forInStatementLeftDecl = NT.VariableDeclaration.isTypeOf(forInStatement.left))
scanStatementForDeclarations(scope, forInStatementLeftDecl);
scanStatementForDeclarations(scope, forInStatement.body);
break;
case "ForOfStatement":
var forOfStatement: ESTree.ForOfStatement = NT.ForOfStatement.cast(stmt);
var forOfStatementLeftDecl: ESTree.VariableDeclaration;
if (forOfStatementLeftDecl = NT.VariableDeclaration.isTypeOf(forOfStatement.left))
scanStatementForDeclarations(scope, forOfStatementLeftDecl);
scanStatementForDeclarations(scope, forOfStatement.body);
break;
case "FunctionDeclaration":
scanFunctionDeclaration(scope, NT.FunctionDeclaration.cast(stmt));
break;
case "VariableDeclaration":
scanVariableDeclaration(scope, NT.VariableDeclaration.cast(stmt));
break;
}
}
function scanFunctionDeclaration (scope: Scope, stmt: ESTree.FunctionDeclaration): void
{
var ctx = scope.ctx;
var varScope = scope.varScope;
var name = stmt.id.name;
var variable = varScope.getVar(name);
if (variable && variable.readOnly) {
(scope.ctx.strictMode ? error : warning)(location(stmt), `initializing read-only symbol '${variable.name}'`);
variable = new Variable(ctx, name);
varScope.setAnonymousVar(variable);
} else if (variable) {
if (variable.funcRef)
warning( location(stmt), `hiding previous declaration of function '${variable.name}'` );
} else {
variable = new Variable(ctx, name);
varScope.setVar(variable);
}
variable.declared = true;
variable.funcRef = ctx.addClosure(stmt.id && stmt.id.name);
variable.hvar = variable.funcRef.closureVar;
if (!variable.initialized && !variable.assigned)
variable.initialized = true;
else
variable.setAssigned(ctx)
variable.setAccessed(true, ctx);
stmt.variable = variable;
}
function scanVariableDeclaration (scope: Scope, stmt: ESTree.VariableDeclaration): void
{
var varScope = scope.varScope;
stmt.declarations.forEach((vd: ESTree.VariableDeclarator) => {
var ident = NT.Identifier.isTypeOf(vd.id);
if (ident) {
var v: Variable = varScope.getVar(ident.name);
if (v && vd.init && v.readOnly) {
(scope.ctx.strictMode ? error : warning)(location(vd), `re-declaring read-only symbol '${ident.name}'`);
v = varScope.newAnonymousVariable(ident.name);
} else if (!v) {
v = varScope.newVariable(ident.name);
}
v.declared = true;
if (!v.hvar)
v.hvar = scope.ctx.builder.newVar(v.name);
vd.variable = v;
} else {
error(location(ident), "ES6 pattern not supported");
}
});
}
function compileStatement (scope: Scope, stmt: ESTree.Statement, parent: ESTree.Node): void
{
if (!stmt)
return;
switch (stmt.type) {
case "EmptyStatement":
break;
case "BlockStatement":
var blockStatement: ESTree.BlockStatement = NT.BlockStatement.cast(stmt);
blockStatement.body.forEach((s: ESTree.Statement) => {
compileStatement(scope, s, stmt);
});
break;
case "ExpressionStatement":
var expressionStatement: ESTree.ExpressionStatement = NT.ExpressionStatement.cast(stmt);
compileExpression(scope, expressionStatement.expression, false);
break;
case "IfStatement":
compileIfStatement(scope, NT.IfStatement.cast(stmt));
break;
case "LabeledStatement":
compileLabeledStatement(scope, NT.LabeledStatement.cast(stmt));
break;
case "BreakStatement":
compileBreakStatement(scope, NT.BreakStatement.cast(stmt));
break;
case "ContinueStatement":
compileContinueStatement(scope, NT.ContinueStatement.cast(stmt));
break;
case "WithStatement":
var withStatement: ESTree.WithStatement = NT.WithStatement.cast(stmt);
error(location(withStatement), "'with' is not supported");
break;
case "SwitchStatement":
compileSwitchStatement(scope, NT.SwitchStatement.cast(stmt));
break;
case "ReturnStatement":
compileReturnStatement(scope, NT.ReturnStatement.cast(stmt));
break;
case "ThrowStatement":
compileThrowStatement(scope, NT.ThrowStatement.cast(stmt));
break;
case "TryStatement":
compileTryStatement(scope, NT.TryStatement.cast(stmt));
break;
case "WhileStatement":
compileWhileStatement(scope, NT.WhileStatement.cast(stmt));
break;
case "DoWhileStatement":
compileDoWhileStatement(scope, NT.DoWhileStatement.cast(stmt));
break;
case "ForStatement":
compileForStatement(scope, NT.ForStatement.cast(stmt));
break;
case "ForInStatement":
compileForInStatement(scope, NT.ForInStatement.cast(stmt));
break;
case "ForOfStatement":
error(location(stmt), "'for-of' is not implemented yet");
var forOfStatement: ESTree.ForOfStatement = NT.ForOfStatement.cast(stmt);
var forOfStatementLeftDecl: ESTree.VariableDeclaration;
if (forOfStatementLeftDecl = NT.VariableDeclaration.isTypeOf(forOfStatement.left))
compileStatement(scope, forOfStatementLeftDecl, stmt);
else
compileExpression(scope, forOfStatement.left);
var breakLab: hir.Label = scope.ctx.builder.newLabel();
var continueLab: hir.Label = scope.ctx.builder.newLabel();
scope.ctx.pushLabel(new Label(LabelKind.LOOP, null, location(forOfStatement), breakLab, continueLab));
compileStatement(scope, forOfStatement.body, stmt);
scope.ctx.builder.genLabel(breakLab);
scope.ctx.popLabel();
break;
case "DebuggerStatement":
warning(location(stmt), "'debugger' is not implemented yet");
var debuggerStatement: ESTree.DebuggerStatement = NT.DebuggerStatement.cast(stmt);
break;
case "FunctionDeclaration":
compileFunctionDeclaration(scope, NT.FunctionDeclaration.cast(stmt), parent);
break;
case "VariableDeclaration":
compileVariableDeclaration(scope, NT.VariableDeclaration.cast(stmt));
break;
default:
error(location(stmt), "unsupported statement");
assert(false, `unsupported statement '${stmt.type}'`);
break;
}
}
function compileLabeledStatement (scope: Scope, stmt: ESTree.LabeledStatement): void
{
var prevLabel: Label;
var loc = location(stmt);
var breakLab: hir.Label = null;
if (prevLabel = scope.ctx.findLabel(stmt.label.name)) {
error(loc, `label '${prevLabel.name}' already declared`);
note(prevLabel.loc, `previous declaration of label '${prevLabel.name}'`);
} else {
breakLab = scope.ctx.builder.newLabel();
// Find the target statement by skipping nested labels (if any)
for ( var targetStmt = stmt.body;
NT.LabeledStatement.eq(targetStmt);
targetStmt = NT.LabeledStatement.cast(targetStmt).body )
{}
var label = new Label(LabelKind.NAMED, stmt.label.name, loc, breakLab, null);
scope.ctx.pushLabel(label);
// Add the label to the label set of the statement.
// It is actually only needed by loops to implement 'continue'
if (!targetStmt.labels)
targetStmt.labels = [label];
else
targetStmt.labels.push(label);
}
compileStatement(scope, stmt.body, stmt);
if (breakLab) {
scope.ctx.builder.genLabel(breakLab);
scope.ctx.popLabel();
}
}
function compileBreakStatement (scope: Scope, stmt: ESTree.BreakStatement): void
{
var label: Label = null;
if (stmt.label) {
if (!(label = scope.ctx.findLabel(stmt.label.name))) {
error(location(stmt), `'break' label '${stmt.label.name}:' is not defined`);
return;
}
} else {
if (!(label = scope.ctx.findAnonBreakContinueLabel(true))) {
error(location(stmt), "'break': there is no surrounding loop");
return;
}
}
scope.ctx.genGoto(label, label.breakLab);
}
function compileContinueStatement (scope: Scope, stmt: ESTree.ContinueStatement): void
{
var label: Label = null;
if (stmt.label) {
if (!(label = scope.ctx.findLabel(stmt.label.name))) {
error(location(stmt), `'continue' label '${stmt.label.name}:' is not defined`);
return;
} else if (!label.continueLab) {
error(location(stmt), `'continue' label '${stmt.label.name}:' is not a loop`);
note(label.loc, `label '${stmt.label.name}:' defined here`);
return;
}
} else {
if (!(label = scope.ctx.findAnonBreakContinueLabel(false))) {
error(location(stmt), "'continue': there is no surrounding loop");
return;
}
}
scope.ctx.genGoto(label, label.continueLab);
}
function compileIfStatement (scope: Scope, ifStatement: ESTree.IfStatement): void
{
var thenLabel: hir.Label = scope.ctx.builder.newLabel();
var elseLabel: hir.Label = scope.ctx.builder.newLabel();
var endLabel: hir.Label = null;
if (ifStatement.alternate)
endLabel = scope.ctx.builder.newLabel();
compileExpression(scope, ifStatement.test, true, thenLabel, elseLabel);
scope.ctx.builder.genLabel(thenLabel);
compileStatement(scope, ifStatement.consequent, ifStatement);
if (ifStatement.alternate)
scope.ctx.builder.genGoto(endLabel);
scope.ctx.builder.genLabel(elseLabel);
if (ifStatement.alternate) {
compileStatement(scope, ifStatement.alternate, ifStatement);
scope.ctx.builder.genLabel(endLabel);
}
}
// TODO: check if all expressions are constant integers and generate a SWITCH instruction
function compileSwitchStatement (scope: Scope, stmt: ESTree.SwitchStatement): void
{
if (stmt.cases.length === 0) {
warning(location(stmt), "empty 'switch' statement");
compileExpression(scope, stmt.discriminant, false, null, null);
return;
}
var ctx = scope.ctx;
var breakLab: hir.Label = scope.ctx.builder.newLabel();
var labels: hir.Label[] = new Array<hir.Label>(stmt.cases.length);
// The integer cases
var intCase: boolean[] = new Array<boolean>(stmt.cases.length);
var dupCase: boolean[] = new Array<boolean>(stmt.cases.length);
for ( var i = 0; i < stmt.cases.length; ++i )
labels[i] = ctx.builder.newLabel();
var discr = compileExpression(scope, stmt.discriminant, true, null, null);
if (hir.isImmediate(discr))
warning(location(stmt.discriminant), "'switch' expression is constant");
var intValueSet: { [key: string]: number } = Object.create(null);
var intValues: number[] = [];
var intTargets: hir.Label[] = [];
var nonIntCount = 0; // count of values who are not integer constants
var defaultLabel: hir.Label = null;
var elseLabel: hir.Label = null;
// Find the integer constant cases
for ( var i = 0; i < stmt.cases.length; ++i ) {
if (!stmt.cases[i].test) {
assert(!defaultLabel);
defaultLabel = labels[i];
continue;
}
var rv = tryFoldExpression(scope, stmt.cases[i].test);
if (rv !== null && hir.isImmediateInteger(rv)) {
intCase[i] = true;
var nv = hir.unwrapImmediate(rv) | 0;
var snv = String(nv);
if (!(snv in intValueSet)) {
intValueSet[snv] = nv;
intValues.push(nv);
intTargets.push(labels[i]);
} else {
warning(location(stmt.cases[i].test), `duplicate switch case '${nv}'`);
dupCase[i] = true;
}
} else {
++nonIntCount;
}
}
// Not worth it for just one integer case
if (intValues.length < 2)
intValues.length = 0;
// If we have integer cases, generate a SWITCH table for them
if (intValues.length) {
if (nonIntCount > 0)
elseLabel = ctx.builder.newLabel();
var failLabel = elseLabel || defaultLabel || breakLab;
var goodLabel = ctx.builder.newLabel();
// Check if discr is an integer
var idiscr = ctx.allocTemp();
ctx.builder.genBinop(hir.OpCode.OR_N, idiscr, discr, hir.wrapImmediate(0));
ctx.builder.genIf(hir.OpCode.IF_STRICT_EQ, idiscr, discr, goodLabel, failLabel);
ctx.builder.genLabel(goodLabel);
ctx.releaseTemp(idiscr);
ctx.builder.genSwitch(idiscr, failLabel, intValues, intTargets);
if (elseLabel) {
ctx.builder.genLabel(elseLabel);
elseLabel = null;
}
}
for ( var i = 0; i < stmt.cases.length; ++i ) {
var sc = stmt.cases[i];
if (!sc.test)
continue;
if (dupCase[i]) // skip duplicate cases
continue;
// Skip integer cases, but only if we decided there were enough of them
if (intValues.length && intCase[i])
continue;
if (elseLabel !== null)
ctx.builder.genLabel(elseLabel);
var testval = compileExpression(scope, sc.test, true, null, null);
ctx.releaseTemp(testval);
elseLabel = ctx.builder.newLabel();
ctx.builder.genIf(hir.OpCode.IF_STRICT_EQ, discr, testval, labels[i], elseLabel);
}
if (elseLabel) {
ctx.builder.genLabel(elseLabel);
if (defaultLabel)
ctx.builder.genGoto(defaultLabel);
else
ctx.builder.genGoto(breakLab);
}
ctx.releaseTemp(discr);
scope.ctx.pushLabel(new Label(LabelKind.SWITCH, null, location(stmt), breakLab, null));
for ( var i = 0; i < stmt.cases.length; ++i ) {
ctx.builder.genLabel(labels[i]);
stmt.cases[i].consequent.forEach((s: ESTree.Statement) => {
compileStatement(scope, s, stmt);
});
}
scope.ctx.builder.genLabel(breakLab);
scope.ctx.popLabel();
}
function compileReturnStatement (scope: Scope, stmt: ESTree.ReturnStatement): void
{
var value: hir.RValue;
if (stmt.argument)
value = compileExpression(scope, stmt.argument, true, null, null);
else
value = hir.undefinedValue;
scope.ctx.genReturn(value);
}
function compileThrowStatement (scope: Scope, stmt: ESTree.ThrowStatement): void
{
var value = compileExpression(scope, stmt.argument, true, null, null);
scope.ctx.builder.genThrow(value);
}
function fillContinueInNamedLoopLabels (labels: Label[], continueLab: hir.Label): void
{
if (labels)
for ( var i = 0, e = labels.length; i < e; ++i ) {
assert(labels[i].kind === LabelKind.NAMED);
labels[i].kind = LabelKind.LOOP;
labels[i].continueLab = continueLab;
}
}
function compileTryStatement (scope: Scope, stmt: ESTree.TryStatement): void
{
compileFinally(scope, stmt);
function compileCatch (scope: Scope, stmt: ESTree.TryStatement): void
{
if (!stmt.handler)
return compileStatement(scope, stmt.block, stmt);
var ctx = scope.ctx;
var exitLabel = new Label(LabelKind.INTERNAL, null, null, ctx.builder.newLabel(), null);
ctx.pushLabel(exitLabel);
var onNormal = ctx.builder.newLabel();
var onException = ctx.builder.newLabel();
var tryId = ctx.builder.genBeginTry(onNormal, onException);
var tryBlock = ctx.pushTryBlock();
ctx.builder.genLabel(onNormal);
compileStatement(scope, stmt.block, stmt);
if (!tryBlock.outgoingJumps.length) {
// Fast case when there are no outgoing jumps
ctx.popTryBlock(tryBlock);
ctx.builder.genLabel(tryBlock.exitHandler);
ctx.builder.genEndTry(tryId);
ctx.builder.genGoto(exitLabel.breakLab);
} else {
// Slow case - there are outgoing jumps and the ending of the try block must be treated as one
// Generate an indirect jump to the "normal code" after the block
ctx.genGoto(exitLabel, exitLabel.breakLab);
ctx.popTryBlock(tryBlock);
ctx.builder.genLabel(tryBlock.exitHandler);
ctx.builder.genEndTry(tryId);
// Dispatch every outgoing jump to its actual destination
ctx.genTryBlockSwitch(tryBlock);
}
var catchIdent: ESTree.Identifier = NT.Identifier.cast(stmt.handler.param);
var catchScope = new Scope(scope.ctx, false, scope);
var catchVar = catchScope.newVariable(catchIdent.name);
catchVar.declared = true;
ctx.builder.genLabel(onException);
catchVar.setAssigned(ctx);
ctx.builder.genAssign(catchVar.hvar, hir.lastThrownValueReg);
ctx.builder.genAssign(hir.lastThrownValueReg, hir.undefinedValue);
ctx.builder.genEndTry(tryId);
compileStatement(catchScope, stmt.handler.body, stmt);
ctx.builder.genGoto(exitLabel.breakLab);
ctx.popLabel();
ctx.builder.genLabel(exitLabel.breakLab);
}
function compileFinally (scope: Scope, stmt: ESTree.TryStatement): void
{
if (!stmt.finalizer)
return compileCatch(scope, stmt);
var ctx = scope.ctx;
var exitLabel = new Label(LabelKind.INTERNAL, null, null, ctx.builder.newLabel(), null);
ctx.pushLabel(exitLabel);
var exceptionLabel = new Label(LabelKind.INTERNAL, null, null, ctx.builder.newLabel(), null);
ctx.pushLabel(exceptionLabel);
var onNormal = ctx.builder.newLabel();
var onException = ctx.builder.newLabel();
var tryId = ctx.builder.genBeginTry(onNormal, onException);
var tryBlock = ctx.pushTryBlock();
ctx.builder.genLabel(onNormal);
compileCatch(scope, stmt);
// The ending of the try block must be treated as an outgoing jump
// Generate an indirect jump to the "normal code" after the block. It will go through the exit handler
ctx.genGoto(exitLabel, exitLabel.breakLab);
ctx.builder.genLabel(onException);
var saveLastThrown = ctx.allocTemp();
ctx.builder.genAssign(saveLastThrown, hir.lastThrownValueReg);
ctx.genGoto(exceptionLabel, exceptionLabel.breakLab);
ctx.popTryBlock(tryBlock);
ctx.builder.genLabel(tryBlock.exitHandler);
ctx.builder.genEndTry(tryId);
compileStatement(scope, stmt.finalizer, stmt);
// Dispatch every outgoing jump to its actual destination
ctx.genTryBlockSwitch(tryBlock);
ctx.popLabel();
ctx.builder.genLabel(exceptionLabel.breakLab);
ctx.releaseTemp(saveLastThrown);
ctx.builder.genThrow(saveLastThrown);
ctx.popLabel();
ctx.builder.genLabel(exitLabel.breakLab);
}
}
function compileWhileStatement (scope: Scope, stmt: ESTree.WhileStatement): void
{
var ctx = scope.ctx;
var exitLoop = ctx.builder.newLabel();
var loop = ctx.builder.newLabel();
var body = ctx.builder.newLabel();
fillContinueInNamedLoopLabels(stmt.labels, body);
ctx.builder.genLabel(loop);
compileExpression(scope, stmt.test, true, body, exitLoop);
ctx.builder.genLabel(body);
scope.ctx.pushLabel(new Label(LabelKind.LOOP, null, location(stmt), exitLoop, loop));
compileStatement(scope, stmt.body, stmt);
scope.ctx.popLabel();
ctx.builder.genGoto(loop);
ctx.builder.genLabel(exitLoop);
}
function compileDoWhileStatement (scope: Scope, stmt: ESTree.DoWhileStatement): void
{
var ctx = scope.ctx;
var exitLoop = ctx.builder.newLabel();
var loop = ctx.builder.newLabel();
var body = ctx.builder.newLabel();
fillContinueInNamedLoopLabels(stmt.labels, body);
ctx.builder.genLabel(body);
scope.ctx.pushLabel(new Label(LabelKind.LOOP, null, location(stmt), exitLoop, loop));
compileStatement(scope, stmt.body, stmt);
scope.ctx.popLabel();
ctx.builder.genLabel(loop);
compileExpression(scope, stmt.test, true, body, exitLoop);
ctx.builder.genLabel(exitLoop);
}
function compileForStatement (scope: Scope, stmt: ESTree.ForStatement): void
{
var ctx = scope.ctx;
var exitLoop = ctx.builder.newLabel();
var loopStart = ctx.builder.newLabel();
var loop = ctx.builder.newLabel();
var body = ctx.builder.newLabel();
fillContinueInNamedLoopLabels(stmt.labels, body);
var forStatementInitDecl: ESTree.VariableDeclaration;
if (stmt.init)
if (forStatementInitDecl = NT.VariableDeclaration.isTypeOf(stmt.init))
compileVariableDeclaration(scope, forStatementInitDecl);
else
compileExpression(scope, stmt.init);
ctx.builder.genLabel(loopStart);
if (stmt.test)
compileExpression(scope, stmt.test, true, body, exitLoop);
ctx.builder.genLabel(body);
scope.ctx.pushLabel(new Label(LabelKind.LOOP, null, location(stmt), exitLoop, loop));
compileStatement(scope, stmt.body, stmt);
scope.ctx.popLabel();
ctx.builder.genLabel(loop);
if (stmt.update)
compileExpression(scope, stmt.update);
ctx.builder.genGoto(loopStart);
ctx.builder.genLabel(exitLoop);
}
function compileForInStatement (scope: Scope, stmt: ESTree.ForInStatement): void
{
var ctx = scope.ctx;
var exitLoop = ctx.builder.newLabel();
var loopStart = ctx.builder.newLabel();
var loop = ctx.builder.newLabel();
var body = ctx.builder.newLabel();
fillContinueInNamedLoopLabels(stmt.labels, body);
var target: ESTree.Expression;
var forInStatementLeftDecl: ESTree.VariableDeclaration = NT.VariableDeclaration.isTypeOf(stmt.left);
if (forInStatementLeftDecl) {
compileVariableDeclaration(scope, forInStatementLeftDecl);
target = forInStatementLeftDecl.declarations[0].id;
} else {
target = stmt.left;
}
var experValue = compileExpression(scope, stmt.right, true, null, null);
var notUndef = ctx.builder.newLabel();
var notNull = ctx.builder.newLabel();
ctx.builder.genIf(hir.OpCode.IF_STRICT_EQ, experValue, hir.undefinedValue, exitLoop, notUndef);
ctx.builder.genLabel(notUndef);
ctx.builder.genIf(hir.OpCode.IF_STRICT_EQ, experValue, hir.nullValue, exitLoop, notNull);
ctx.builder.genLabel(notNull);
ctx.releaseTemp(experValue);
var obj = ctx.allocTemp();
ctx.builder.genUnop(hir.OpCode.TO_OBJECT, obj, experValue);
ctx.releaseTemp(obj);
var iter = ctx.allocTemp();
ctx.builder.genMakeForInIterator(iter, obj);
ctx.builder.genLabel(loopStart);
var value = ctx.allocTemp();
var more = ctx.allocTemp();
ctx.builder.genForInIteratorNext(more, value, iter);
ctx.releaseTemp(more);
ctx.builder.genIfTrue(more, body, exitLoop);
ctx.builder.genLabel(body);
toLogical(scope, stmt, _compileAssignment(scope, hir.OpCode.ASSIGN, true, target, value, false), false, null, null);
scope.ctx.pushLabel(new Label(LabelKind.LOOP, null, location(stmt), exitLoop, loop));
compileStatement(scope, stmt.body, stmt);
scope.ctx.popLabel();
ctx.builder.genLabel(loop);
ctx.builder.genGoto(loopStart);
ctx.builder.genLabel(exitLoop);
ctx.releaseTemp(iter);
}
function compileFunctionDeclaration (scope: Scope, stmt: ESTree.FunctionDeclaration, parent: ESTree.Statement): void
{
if (scope.ctx.strictMode && parent)
error(location(stmt), "functions can only be declared at top level in strict mode");
var variable = stmt.variable;
compileFunction(scope, stmt, variable.funcRef);
}
function compileVariableDeclaration (scope: Scope, stmt: ESTree.VariableDeclaration): void
{
stmt.declarations.forEach((vd: ESTree.VariableDeclarator) => {
var variable: Variable = vd.variable;
if (!variable) {
// if not present, there was an error that we already reported
} else if (vd.init) {
variable.setAssigned(scope.ctx);
var value = compileExpression(scope, vd.init, true, null, null);
scope.ctx.releaseTemp(value);
scope.ctx.builder.genAssign(variable.hvar, value);
}
});
}
function compileExpression (
scope: Scope, e: ESTree.Expression, need: boolean=true, onTrue?: hir.Label, onFalse?: hir.Label
): hir.RValue
{
return compileSubExpression(scope, e, need, onTrue, onFalse);
}
function tryFoldExpression (scope: Scope, e: ESTree.Expression): hir.RValue
{
return fold(e);
function foldLiteral (e: ESTree.Literal): hir.RValue
{
if (e.regex)
return null;
switch (typeof e.value) {
case "object":
if (e.value !== null)
return null;
case "number":
case "string":
case "undefined":
return hir.wrapImmediate(e.value);
}
return null;
}
function foldSequence (e: ESTree.SequenceExpression): hir.RValue
{
var i: number;
for ( i = 0; i < e.expressions.length-1; ++i )
if (fold(e.expressions[i]) === null)
return null;
return fold(e.expressions[i]);
}
function foldUnary (e: ESTree.UnaryExpression): hir.RValue
{
// Check for the special case of "typeof undefined identifier"
var ident: ESTree.Identifier;
if (e.operator === "typeof" && (ident = isUndefinedIdentifier(scope, e.argument)) !== null) {
if (!ident.warned) {
ident.warned = true;
warning(location(e.argument), `undefined identifier '${ident.name}'`);
}
return hir.wrapImmediate("undefined");
}
// Try folding the argument
var arg = fold(e.argument);
if (arg === null)
return null;
var op: hir.OpCode;
switch (e.operator) {
case "-": op = hir.OpCode.NEG_N; break;
case "+": op = hir.OpCode.TO_NUMBER; break;
case "~": op = hir.OpCode.BIN_NOT_N; break;
case "delete": return null;
case "!": op = hir.OpCode.LOG_NOT; break;
case "typeof": op = hir.OpCode.TYPEOF; break;
case "void": return hir.undefinedValue;
default:
return null;
}
return hir.foldUnary(op, arg);
}
function foldBinary (e: ESTree.BinaryExpression): hir.RValue
{
var left = fold(e.left);
if (left === null)
return null;
var right = fold(e.right);
if (right === null)
return null;
var op: hir.OpCode;
switch (e.operator) {
case "in":
case "instanceof": return null;
case "==":
if (!e.warned) {
e.warned = true;
warning(location(e), "operator '==' is not recommended");
}
op = hir.OpCode.LOOSE_EQ;
break;
case "!=":
if (!e.warned) {
e.warned = true;
warning(location(e), "operator '!=' is not recommended");
}
op = hir.OpCode.LOOSE_NE;
break;
case "===": op = hir.OpCode.STRICT_EQ; break;
case "!==": op = hir.OpCode.STRICT_NE; break;
case "<": op = hir.OpCode.LT; break;
case "<=": op = hir.OpCode.LE; break;
case ">": op = hir.OpCode.GT; break;
case ">=": op = hir.OpCode.GE; break;
case "<<": op = hir.OpCode.SHL_N; break;
case ">>": op = hir.OpCode.ASR_N; break;
case ">>>": op = hir.OpCode.SHR_N; break;
case "+": op = hir.OpCode.ADD; break;
case "-": op = hir.OpCode.SUB_N; break;
case "*": op = hir.OpCode.MUL_N; break;
case "/": op = hir.OpCode.DIV_N; break;
case "%": op = hir.OpCode.MOD_N; break;
case "|": op = hir.OpCode.OR_N; break;
case "^": op = hir.OpCode.XOR_N; break;
case "&": op = hir.OpCode.AND_N; break;
default:
return null;
}
return hir.foldBinary(op, left, right);
}
function foldLogical (e: ESTree.LogicalExpression): hir.RValue
{
var left = fold(e.left);
if (left === null)
return null;
var right = fold(e.right);
if (right === null)
return null;
switch (e.operator) {
case "||": return hir.isImmediateTrue(left) ? left : right;
case "&&": return !hir.isImmediateTrue(left) ? left : right;
}
return null;
}
function foldConditional (e: ESTree.ConditionalExpression): hir.RValue
{
var test = fold(e.test);
if (test === null)
return null;
var cons = fold(e.consequent);
if (cons === null)
return null;
var alt = fold(e.alternate);
if (alt === null)
return null;
return hir.isImmediateTrue(test) ? cons : alt;
}
// To avoid allocating environments use this for recursion
function fold (e: ESTree.Expression): hir.RValue
{
switch (e.type) {
case "Literal": return foldLiteral(NT.Literal.cast(e));
case "SequenceExpression": return foldSequence(NT.SequenceExpression.cast(e));
case "UnaryExpression": return foldUnary(NT.UnaryExpression.cast(e));
case "BinaryExpression": return foldBinary(NT.BinaryExpression.cast(e));
case "LogicalExpression": return foldLogical(NT.LogicalExpression.cast(e));
case "ConditionalExpression": return foldConditional(NT.ConditionalExpression.cast(e));
}
return null;
}
}
function compileSubExpression (
scope: Scope, e: ESTree.Expression, need: boolean=true, onTrue?: hir.Label, onFalse?: hir.Label
): hir.RValue
{
if (!e)
return;
switch (e.type) {
case "Literal":
return toLogical(scope, e, compileLiteral(scope, NT.Literal.cast(e), need), need, onTrue, onFalse);
case "Identifier":
return toLogical(scope, e, compileIdentifier(scope, NT.Identifier.cast(e), need), need, onTrue, onFalse);
case "ThisExpression":
return toLogical(scope, e, compileThisExpression(scope, NT.ThisExpression.cast(e), need), need, onTrue, onFalse);
case "ArrayExpression":
return compileArrayExpression(scope, NT.ArrayExpression.cast(e), need, onTrue, onFalse);
case "ObjectExpression":
return compileObjectExpression(scope, NT.ObjectExpression.cast(e), need, onTrue, onFalse);
case "FunctionExpression":
return toLogical(
scope, e, compileFunctionExpression(scope, NT.FunctionExpression.cast(e), need),
need, onTrue, onFalse
);
case "SequenceExpression":
return compileSequenceExpression(scope, NT.SequenceExpression.cast(e), need, onTrue, onFalse);
case "UnaryExpression":
return compileUnaryExpression(scope, NT.UnaryExpression.cast(e), need, onTrue, onFalse);
case "BinaryExpression":
return compileBinaryExpression(scope, NT.BinaryExpression.cast(e), need, onTrue, onFalse);
case "AssignmentExpression":
return toLogical(
scope, e,
compileAssignmentExpression(scope, NT.AssignmentExpression.cast(e), need),
need, onTrue, onFalse
);
case "UpdateExpression":
return toLogical(
scope, e,
compileUpdateExpression(scope, NT.UpdateExpression.cast(e), need),
need, onTrue, onFalse
);
case "LogicalExpression":
return compileLogicalExpression(scope, NT.LogicalExpression.cast(e), need, onTrue, onFalse);
case "ConditionalExpression":
return compileConditionalExpression(scope, NT.ConditionalExpression.cast(e), need, onTrue, onFalse);
case "CallExpression":
return toLogical(scope, e, compileCallExpression(scope, NT.CallExpression.cast(e), need), need, onTrue, onFalse);
case "NewExpression":
return toLogical(scope, e, compileNewExpression(scope, NT.NewExpression.cast(e), need), need, onTrue, onFalse);
case "MemberExpression":
return toLogical(
scope, e,
compileMemberExpression(scope, NT.MemberExpression.cast(e), need),
need, onTrue, onFalse
);
default:
error(location(e), "unsupported expression");
assert(false, `unsupported expression '${e.type}'`);
break;
}
}
function toLogical (
scope: Scope, node: ESTree.Node, value: hir.RValue, need: boolean, onTrue: hir.Label, onFalse: hir.Label
): hir.RValue
{
if (need) {
if (onTrue) {
scope.ctx.releaseTemp(value);
if (hir.isImmediate(value)) {
var boolv = hir.isImmediateTrue(value);
warning(location(node), `condition is always ${boolv?'true':'false'}`);
scope.ctx.builder.genGoto(boolv ? onTrue : onFalse);
} else {
scope.ctx.builder.genIfTrue(value, onTrue, onFalse);
}
return null;
} else {
return value;
}
} else {
scope.ctx.releaseTemp(value);
return null;
}
}
function compileLiteral (scope: Scope, literal: ESTree.Literal, need: boolean): hir.RValue
{
if (literal.regex)
return compileRegexLiteral(scope, <ESTree.RegExpLiteral>literal, need);
if (need) {
return hir.wrapImmediate(literal.value);
} else {
return null;
}
}
function compileRegexLiteral (scope: Scope, regexLit: ESTree.RegExpLiteral, need: boolean): hir.RValue
{
if (!m_specVars.regExp) {
error(location(regexLit), "RegExp not initialized yet");
return hir.nullValue;
}
var regex = regexLit.regex;
// Note: it has probably already been validated by the parser, but validate it again
// ourselves as parsers don't do it consistently
try {
new RegExp(regex.pattern, regex.flags);
} catch (e) {
error(location(regexLit), e.message || "invalid RegExp");
return hir.nullValue;
}
if (!need)
return null;
var ctx = scope.ctx;
// Create an anonymous variable in the global scope
var re = m_scope.newAnonymousVariable("$re");
re.declared = true;
var labCreated: hir.Label = ctx.builder.newLabel();
var labNotCreated: hir.Label = ctx.builder.newLabel();
ctx.builder.genIfTrue(re.hvar, labCreated, labNotCreated);
ctx.builder.genLabel(labNotCreated);
re.setAssigned(ctx);
m_specVars.regExp.setAccessed(true, ctx);
var t = ctx.builder.genCall(re.hvar, m_specVars.regExp.hvar, [hir.undefinedValue, regex.pattern, regex.flags]);
setSourceLocation(t, regexLit);
ctx.builder.genGoto(labCreated);
ctx.builder.genLabel(labCreated);
re.setAccessed(true, ctx);
return re.hvar;
}
function compileThisExpression (scope: Scope, thisExp: ESTree.ThisExpression, need: boolean): hir.RValue
{
var variable = scope.ctx.thisParam;
if (need) {
variable.setAccessed(true, scope.ctx);
return variable.hvar;
} else {
return null;
}
}
function compileArrayExpression (
scope: Scope, e: ESTree.ArrayExpression, need: boolean, onTrue: hir.Label, onFalse: hir.Label
): hir.RValue
{
var ctx = scope.ctx;
if (!need || onTrue) {
warning(location(e), onTrue ? "condition is always true" : "unused array expression");
e.elements.forEach((elem) => {
if (elem)
if (elem.type === "SpreadElement")
error(location(elem), "ES6 spread elements not supported");
else
compileSubExpression(scope, elem, false, null, null);
});
if (onTrue)
ctx.builder.genGoto(onTrue);
return null;
}
var objProto = ctx.allocTemp();
ctx.builder.genLoadRuntimeVar(objProto, "arrayPrototype");
ctx.releaseTemp(objProto);
var dest = ctx.allocTemp();
ctx.builder.genCreate(dest, objProto);
if (e.elements.length > 0) {
// Resize the array in advance, but only for more than one element
if (e.elements.length > 1)
ctx.builder.genPropSet(dest, hir.wrapImmediate("length"), hir.wrapImmediate(e.elements.length));
e.elements.forEach((elem, index) => {
if (elem) {
if (elem.type === "SpreadElement")
error(location(elem), "ES6 spread elements not supported");
else {
var val = compileSubExpression(scope, elem, true, null, null);
ctx.releaseTemp(val);
ctx.builder.genPropSet(dest, hir.wrapImmediate(index), val);
}
}
});
}
return dest;
}
function compileObjectExpression (
scope: Scope, e: ESTree.ObjectExpression, need: boolean, onTrue: hir.Label, onFalse: hir.Label
): hir.RValue
{
var ctx = scope.ctx;
var propMap = new StringMap<ObjectExprProp>();
var props: ObjectExprProp[] = [];
var errors = false;
// First accumulate the properties
e.properties.forEach((prop: ESTree.Property) => {
var ident: ESTree.Identifier;
var lit: ESTree.Literal;
var name: string;
if (prop.computed) {
error(location(prop), "computed object expression not supported in ES5");
errors = true;
return;
}
if (ident = NT.Identifier.isTypeOf(prop.key)) {
name = ident.name;
} else if (lit = NT.Literal.isTypeOf(prop.key)) {
name = String(lit.value);
} else {
error(location(prop.key), "unsupported property key");
errors = true;
return;
}
var propDesc: ObjectExprProp = propMap.get(name);
if (propDesc) {
if (prop.kind === "init" && propDesc.value) {
if (scope.ctx.strictMode) {
error(location(prop), `duplicate data property '${name}' in strict mode`);
errors = true;
}
// Disable the old one, so we can overwrite with the new one, but still calculate the old
// expression
propMap.remove(name);
propDesc.name = null;
propDesc = null;
}
else if (prop.kind === "init" && (propDesc.getter || propDesc.setter) ||
(prop.kind === "get" || prop.kind === "set") && propDesc.value)
{
error(location(prop), `data and accessor property with the same name '${name}'`);
errors = true;
}
else if (prop.kind === "get" && propDesc.getter || prop.kind === "set" && propDesc.setter) {
error(location(prop), `multiple getters/setters with the same name '${name}'`);
errors = true;
}
}
if (!propDesc) {
propDesc = new ObjectExprProp(name);
propMap.set(name, propDesc);
props.push(propDesc);
}
switch (prop.kind) {
case "init": propDesc.value = prop.value; break;
case "get": propDesc.getter = NT.FunctionExpression.cast(prop.value); break;
case "set": propDesc.setter = NT.FunctionExpression.cast(prop.value); break;
default:
error(location(prop), "unsupported property kind");
errors = true;
break;
}
});
// If there are errors, compile the init values, only to validate them
// If we don't need the result, same...
if (errors || !need || onTrue) {
if (!need)
warning(location(e), "unused object expression");
else if(onTrue)
warning(location(e), "condition is always true");
props.forEach((propDesc: ObjectExprProp) => {
if (propDesc.value)
compileSubExpression(scope, propDesc.value, false, null, null);
if (propDesc.getter)
compileSubExpression(scope, propDesc.getter, false, null, null);
if (propDesc.setter)
compileSubExpression(scope, propDesc.setter, false, null, null);
});
if (onTrue)
ctx.builder.genGoto(onTrue);
return need ? hir.undefinedValue : null;
}
var objProto = ctx.allocTemp();
ctx.builder.genLoadRuntimeVar(objProto, "objectPrototype");
ctx.releaseTemp(objProto);
var dest = ctx.allocTemp();
ctx.builder.genCreate(dest, objProto);
props.forEach((propDesc: ObjectExprProp) => {
if (propDesc.name === null) { // if this property was overwritten?
// compile and ignore the values
if (propDesc.value)
compileSubExpression(scope, propDesc.value, false, null, null);
if (propDesc.getter)
compileSubExpression(scope, propDesc.getter, false, null, null);
if (propDesc.setter)
compileSubExpression(scope, propDesc.setter, false, null, null);
} else {
var propName = hir.wrapImmediate(propDesc.name);
if (!propDesc.getter && !propDesc.setter) { // is this a data property?
assert(propDesc.value);
var val = compileSubExpression(scope, propDesc.value, true, null, null);
ctx.releaseTemp(val);
ctx.releaseTemp(propName);
ctx.builder.genPropSet(dest, propName, val);
} else {
assert(m_specVars._defineAccessor);
var getter: hir.RValue =
propDesc.getter ? compileSubExpression(scope, propDesc.getter, true, null, null) : hir.undefinedValue;
var setter: hir.RValue =
propDesc.setter ? compileSubExpression(scope, propDesc.setter, true, null, null) : hir.undefinedValue;
ctx.releaseTemp(getter);
ctx.releaseTemp(setter);
m_specVars._defineAccessor.setAccessed(true, ctx);
ctx.builder.genCall(null, m_specVars._defineAccessor.hvar, [
hir.undefinedValue, dest, propName, getter, setter
]);
}
}
});
if (!need) {
ctx.releaseTemp(dest);
return null;
}
else
return dest;
}
function findVariable (scope: Scope, identifier: ESTree.Identifier): Variable
{
var variable: Variable = scope.lookup(identifier.name);
if (!variable) {
if (scope.ctx.strictMode) {
error(location(identifier), `undefined identifier '${identifier.name}'`);
// Declare a dummy variable at 'var-scope' level to decrease noise
variable = scope.varScope.newVariable(identifier.name);
} else {
warning(location(identifier), `undefined identifier '${identifier.name}'`);
variable = m_undefinedVarScope.newVariable(identifier.name);
}
} else if (!scope.ctx.strictMode && !variable.declared) {
// Report all warnings in non-strict mode
warning(location(identifier), `undefined identifier '${identifier.name}'`);
}
return variable;
}
function compileIdentifier (scope: Scope, identifier: ESTree.Identifier, need: boolean): hir.RValue
{
var variable = findVariable(scope, identifier);
if (need) {
variable.setAccessed(true, scope.ctx);
return variable.constantValue !== null ? variable.constantValue : variable.hvar;
} else {
return null;
}
}
function compileFunctionExpression (scope: Scope, e: ESTree.FunctionExpression, need: boolean): hir.RValue
{
if (!need)
warning(location(e), "unused function");
var funcRef = scope.ctx.addClosure(e.id && e.id.name);
var nameScope = new Scope(scope.ctx, false, scope); // A scope for the function name
if (e.id) {
var funcVar = nameScope.newVariable(e.id.name, funcRef.closureVar);
funcVar.funcRef = funcRef;
funcVar.declared = true;
funcVar.initialized = true;
funcVar.setAccessed(need, scope.ctx);
}
compileFunction(nameScope, e, funcRef);
return need ? funcRef.closureVar : null;
}
function compileSequenceExpression (
scope: Scope, e: ESTree.SequenceExpression,
need: boolean, onTrue: hir.Label, onFalse: hir.Label
): hir.RValue
{
var i: number;
for ( i = 0; i < e.expressions.length-1; ++i )
compileSubExpression(scope, e.expressions[i], false, null, null);
return compileSubExpression(scope, e.expressions[i], need, onTrue, onFalse);
}
/** Check if an expression is just an undefined identifier; this is used only by "typeof" */
function isUndefinedIdentifier (scope: Scope, e: ESTree.Expression): ESTree.Identifier
{
var ident = NT.Identifier.isTypeOf(e);
return ident && !scope.lookup(ident.name) ? ident : null;
}
function compileUnaryExpression (
scope: Scope, e: ESTree.UnaryExpression,
need: boolean, onTrue: hir.Label, onFalse: hir.Label
): hir.RValue
{
var ctx = scope.ctx;
switch (e.operator) {
case "-":
return toLogical(scope, e, compileSimpleUnary(scope, hir.OpCode.NEG_N, e.argument, need), need, onTrue, onFalse);
case "+":
return toLogical(scope, e, compileSimpleUnary(scope, hir.OpCode.TO_NUMBER, e.argument, need), need, onTrue, onFalse);
case "~":
return toLogical(scope, e, compileSimpleUnary(scope, hir.OpCode.BIN_NOT_N, e.argument, need), need, onTrue, onFalse);
case "delete":
return toLogical(scope, e, compileDelete(scope, e, need), need, onTrue, onFalse);
case "!":
if (onTrue)
return compileSubExpression(scope, e.argument, need, onFalse, onTrue);
else
return compileSimpleUnary(scope, hir.OpCode.LOG_NOT, e.argument, need);
case "typeof":
// Check for the special case of undefined identifier
var ident: ESTree.Identifier;
if ((ident = isUndefinedIdentifier(scope, e.argument)) !== null) {
if (!ident.warned) {
ident.warned = true;
warning(location(e.argument), `undefined identifier '${ident.name}'`);
}
return toLogical(scope, e, hir.wrapImmediate("undefined"), need, onTrue, onFalse);
} else {
if (onTrue) {
ctx.releaseTemp(compileSubExpression(scope, e.argument, false, null, null));
warning(location(e), "condition is always true");
ctx.builder.genGoto(onTrue);
} else {
return compileSimpleUnary(scope, hir.OpCode.TYPEOF, e.argument, need);
}
}
break;
case "void":
ctx.releaseTemp(compileSubExpression(scope, e.argument, false, null, null));
if (onTrue) {
warning(location(e), "condition is always false");
ctx.builder.genGoto(onFalse);
} else {
return need ? hir.undefinedValue : null;
}
break;
default:
assert(false, `unknown unary operator '${e.operator}'`);
return null;
}
return null;
function compileSimpleUnary (scope: Scope, op: hir.OpCode, e: ESTree.Expression, need: boolean): hir.RValue
{
var v = compileSubExpression(scope, e, need, null, null);
scope.ctx.releaseTemp(v);
if (!need)
return null;
var folded = hir.foldUnary(op, v);
if (folded !== null) {
return folded;
} else {
var dest = scope.ctx.allocTemp();
scope.ctx.builder.genUnop(op, dest, v);
return dest;
}
}
function compileDelete (scope: Scope, e: ESTree.UnaryExpression, need: boolean): hir.RValue
{
var ctx = scope.ctx;
var memb: ESTree.MemberExpression = NT.MemberExpression.isTypeOf(e.argument);
if (!memb) {
warning(location(e), "'delete' of non-member");
compileSubExpression(scope, e.argument, false, null, null);
return need ? hir.wrapImmediate(true) : null;
}
var objExpr: hir.RValue = compileSubExpression(scope, memb.object, true, null, null);
var propName: hir.RValue;
ctx.releaseTemp(objExpr);
var obj = ctx.allocTemp();
ctx.builder.genUnop(hir.OpCode.TO_OBJECT, obj, objExpr);
if (memb.computed)
propName = compileSubExpression(scope, memb.property, true, null, null);
else
propName = hir.wrapImmediate(NT.Identifier.cast(memb.property).name);
ctx.releaseTemp(propName);
ctx.releaseTemp(obj);
var res: hir.LValue = need ? ctx.allocTemp() : hir.nullReg;
ctx.builder.genBinop(hir.OpCode.DELETE, res, obj, propName);
return res;
}
}
// This performs only very primitive constant folding.
// TODO: real constant folding and expression reshaping
function compileBinaryExpression (
scope: Scope, e: ESTree.BinaryExpression,
need: boolean, onTrue: hir.Label, onFalse: hir.Label
): hir.RValue
{
var ctx = scope.ctx;
switch (e.operator) {
case "in": return compileInInstanceOf(ctx, e, hir.OpCode.IN, need, onTrue, onFalse);
case "instanceof": return compileInInstanceOf(ctx, e, hir.OpCode.INSTANCEOF, need, onTrue, onFalse);
}
if (!need) {
ctx.releaseTemp(compileSubExpression(scope, e.left, false, null, null));
ctx.releaseTemp(compileSubExpression(scope, e.right, false, null, null));
return null;
}
var v1 = compileSubExpression(scope, e.left, true);
var v2 = compileSubExpression(scope, e.right, true);
ctx.releaseTemp(v1);
ctx.releaseTemp(v2);
switch (e.operator) {
case "==":
if (!e.warned) {
e.warned = true;
warning(location(e), "operator '==' is not recommended");
}
return compileLogBinary(ctx, e, hir.OpCode.LOOSE_EQ, v1, v2, onTrue, onFalse);
case "!=":
if (!e.warned) {
e.warned = true;
warning(location(e), "operator '!=' is not recommended");
}
return compileLogBinary(ctx, e, hir.OpCode.LOOSE_NE, v1, v2, onTrue, onFalse);
case "===": return compileLogBinary(ctx, e, hir.OpCode.STRICT_EQ, v1, v2, onTrue, onFalse);
case "!==": return compileLogBinary(ctx, e, hir.OpCode.STRICT_NE, v1, v2, onTrue, onFalse);
case "<": return compileLogBinary(ctx, e, hir.OpCode.LT, v1, v2, onTrue, onFalse);
case "<=": return compileLogBinary(ctx, e, hir.OpCode.LE, v1, v2, onTrue, onFalse);
case ">": return compileLogBinary(ctx, e, hir.OpCode.GT, v1, v2, onTrue, onFalse);
case ">=": return compileLogBinary(ctx, e, hir.OpCode.GE, v1, v2, onTrue, onFalse);
case "<<": return toLogical(scope, e, compileArithBinary(ctx, hir.OpCode.SHL_N, v1, v2), true, onTrue, onFalse);
case ">>": return toLogical(scope, e, compileArithBinary(ctx, hir.OpCode.ASR_N, v1, v2), true, onTrue, onFalse);
case ">>>": return toLogical(scope, e, compileArithBinary(ctx, hir.OpCode.SHR_N, v1, v2), true, onTrue, onFalse);
case "+": return toLogical(scope, e, compileGenericBinary(ctx, hir.OpCode.ADD, v1, v2), true, onTrue, onFalse);
case "-": return toLogical(scope, e, compileArithBinary(ctx, hir.OpCode.SUB_N, v1, v2), true, onTrue, onFalse);
case "*": return toLogical(scope, e, compileArithBinary(ctx, hir.OpCode.MUL_N, v1, v2), true, onTrue, onFalse);
case "/": return toLogical(scope, e, compileArithBinary(ctx, hir.OpCode.DIV_N, v1, v2), true, onTrue, onFalse);
case "%": return toLogical(scope, e, compileArithBinary(ctx, hir.OpCode.MOD_N, v1, v2), true, onTrue, onFalse);
case "|": return toLogical(scope, e, compileArithBinary(ctx, hir.OpCode.OR_N, v1, v2), true, onTrue, onFalse);
case "^": return toLogical(scope, e, compileArithBinary(ctx, hir.OpCode.XOR_N, v1, v2), true, onTrue, onFalse);
case "&": return toLogical(scope, e, compileArithBinary(ctx, hir.OpCode.AND_N, v1, v2), true, onTrue, onFalse);
default:
assert(false, `unknown binary operator '${e.operator}'`);
break;
}
return null;
function compileGenericBinary (ctx: FunctionContext, op: hir.OpCode, v1: hir.RValue, v2: hir.RValue): hir.RValue
{
var folded = hir.foldBinary(op, v1, v2);
if (folded !== null)
return folded;
var dest = ctx.allocTemp();
ctx.builder.genBinop(op, dest, v1, v2);
return dest;
}
function compileArithBinary (ctx: FunctionContext, op: hir.OpCode, v1: hir.RValue, v2: hir.RValue): hir.RValue
{
return compileGenericBinary(ctx, op, v1, v2);
}
function compileLogBinary (
ctx: FunctionContext, e: ESTree.Node, op: hir.OpCode,
v1: hir.RValue, v2: hir.RValue, onTrue: hir.Label, onFalse: hir.Label
): hir.RValue
{
if (onTrue) {
var folded = hir.foldBinary(op, v1, v2);
if (folded !== null) {
var boolv = hir.isImmediateTrue(folded);
warning(location(e), `condition is always ${boolv?'true':'false'}`);
ctx.builder.genGoto(boolv ? onTrue : onFalse);
} else {
ctx.builder.genIf(hir.binopToBincond(op), v1, v2, onTrue, onFalse);
}
return null;
} else {
return compileArithBinary(ctx, op, v1, v2);
}
}
function compileInInstanceOf (
ctx: FunctionContext, e: ESTree.BinaryExpression, op: hir.OpCode,
need: boolean, onTrue: hir.Label, onFalse: hir.Label
): hir.RValue
{
var v1 = compileSubExpression(scope, e.left, true);
var v2r = compileSubExpression(scope, e.right, true);
ctx.releaseTemp(v2r);
var v2 = ctx.allocTemp();
if (op === hir.OpCode.IN)
ctx.builder.genBinop(hir.OpCode.ASSERT_OBJECT, v2, v2r,
hir.wrapImmediate("second operand of 'in' is not an object")
);
else
ctx.builder.genBinop(hir.OpCode.ASSERT_FUNC, v2, v2r,
hir.wrapImmediate("second operand of 'instanceof' is not a function")
);
ctx.releaseTemp(v2);
ctx.releaseTemp(v1);
if (!need)
return null;
if (onTrue) {
var folded = hir.foldBinary(op, v1, v2);
if (folded !== null) {
var boolv = hir.isImmediateTrue(folded);
warning(location(e), `condition is always ${boolv?'true':'false'}`);
ctx.builder.genGoto(boolv ? onTrue : onFalse);
} else {
ctx.builder.genIf(hir.binopToBincond(op), v1, v2, onTrue, onFalse);
}
return null;
} else {
var dest = ctx.allocTemp();
ctx.builder.genBinop(op, dest, v1, v2);
return dest;
}
}
}
function compileLogicalExpression (
scope: Scope, e: ESTree.LogicalExpression,
need: boolean, onTrue: hir.Label, onFalse: hir.Label
): hir.RValue
{
switch (e.operator) {
case "||": return compileLogicalOr(scope, e, need, onTrue, onFalse);
case "&&": return compileLogicalAnd(scope, e, need, onTrue, onFalse);
default:
assert(false, `unknown logical operator '${e.operator}'`);
break;
}
return null;
}
function compileLogicalOr (
scope: Scope, e: ESTree.LogicalExpression,
need: boolean, onTrue: hir.Label, onFalse: hir.Label
): hir.RValue
{
var ctx = scope.ctx;
var labLeftFalse: hir.Label;
var labLeftTrue: hir.Label;
var labEnd: hir.Label;
if (need) {
if (onTrue) {
labLeftFalse = ctx.builder.newLabel();
compileSubExpression(scope, e.left, true, onTrue, labLeftFalse);
ctx.builder.genLabel(labLeftFalse);
compileSubExpression(scope, e.right, true, onTrue, onFalse);
} else {
var v1: hir.RValue;
var v2: hir.RValue;
var dest: hir.Local;
labLeftFalse = ctx.builder.newLabel();
labEnd = ctx.builder.newLabel();
v1 = compileSubExpression(scope, e.left, true, null, null);
ctx.releaseTemp(v1);
dest = ctx.allocTemp();
ctx.releaseTemp(dest);
if (dest === v1) {
ctx.builder.genIfTrue(v1, labEnd, labLeftFalse);
} else {
labLeftTrue = ctx.builder.newLabel();
ctx.builder.genIfTrue(v1, labLeftTrue, labLeftFalse);
ctx.builder.genLabel(labLeftTrue);
ctx.builder.genAssign(dest, v1);
ctx.builder.genGoto(labEnd);
}
ctx.builder.genLabel(labLeftFalse);
v2 = compileSubExpression(scope, e.right, true, null, null);
ctx.releaseTemp(v2);
ctx.allocSpecific(dest);
ctx.builder.genAssign(dest, v2);
ctx.builder.genLabel(labEnd);
return dest;
}
} else {
labLeftFalse = ctx.builder.newLabel();
labEnd = ctx.builder.newLabel();
compileSubExpression(scope, e.left, true, labEnd, labLeftFalse);
ctx.builder.genLabel(labLeftFalse);
compileSubExpression(scope, e.right, false, null, null);
ctx.builder.genLabel(labEnd);
}
}
function compileLogicalAnd (
scope: Scope, e: ESTree.LogicalExpression,
need: boolean, onTrue: hir.Label, onFalse: hir.Label
): hir.RValue
{
var ctx = scope.ctx;
var labLeftFalse: hir.Label;
var labLeftTrue: hir.Label;
var labEnd: hir.Label;
if (need) {
if (onTrue) {
labLeftTrue = ctx.builder.newLabel();
compileSubExpression(scope, e.left, true, labLeftTrue, onFalse);
ctx.builder.genLabel(labLeftTrue);
compileSubExpression(scope, e.right, true, onTrue, onFalse);
} else {
var v1: hir.RValue;
var v2: hir.RValue;
var dest: hir.Local;
labLeftTrue = ctx.builder.newLabel();
labEnd = ctx.builder.newLabel();
v1 = compileSubExpression(scope, e.left, true, null, null);
ctx.releaseTemp(v1);
dest = ctx.allocTemp();
ctx.releaseTemp(dest);
if (dest === v1) {
ctx.builder.genIfTrue(v1, labLeftTrue, labEnd);
} else {
labLeftFalse = ctx.builder.newLabel();
ctx.builder.genIfTrue(v1, labLeftTrue, labLeftFalse);
ctx.builder.genLabel(labLeftFalse);
ctx.builder.genAssign(dest, v1);
ctx.builder.genGoto(labEnd);
}
ctx.builder.genLabel(labLeftTrue);
v2 = compileSubExpression(scope, e.right, true, null, null);
ctx.releaseTemp(v2);
ctx.allocSpecific(dest);
ctx.builder.genAssign(dest, v2);
ctx.builder.genLabel(labEnd);
return dest;
}
} else {
labLeftTrue = ctx.builder.newLabel();
labEnd = ctx.builder.newLabel();
compileSubExpression(scope, e.left, true, labLeftTrue, labEnd);
ctx.builder.genLabel(labLeftTrue);
compileSubExpression(scope, e.right, false, null, null);
ctx.builder.genLabel(labEnd);
}
}
function compileAssignmentExpression (scope: Scope, e: ESTree.AssignmentExpression, need: boolean): hir.RValue
{
var opcode: hir.OpCode;
switch (e.operator) {
case "=": opcode = hir.OpCode.ASSIGN; break;
case "+=": opcode = hir.OpCode.ADD; break;
case "-=": opcode = hir.OpCode.SUB_N; break;
case "*=": opcode = hir.OpCode.MUL_N; break;
case "/=": opcode = hir.OpCode.DIV_N; break;
case "%=": opcode = hir.OpCode.MOD_N; break;
case "<<=": opcode = hir.OpCode.SHL_N; break;
case ">>=": opcode = hir.OpCode.ASR_N; break;
case ">>>=": opcode = hir.OpCode.SHR_N; break;
case "|=": opcode = hir.OpCode.OR_N; break;
case "^=": opcode = hir.OpCode.XOR_N; break;
case "&=": opcode = hir.OpCode.AND_N; break;
default:
assert(false, `unrecognized assignment operator '${e.operator}'`);
return null;
}
var rvalue = compileSubExpression(scope, e.right);
return _compileAssignment(scope, opcode, true, e.left, rvalue, need);
}
function _compileAssignment (
scope: Scope, opcode: hir.OpCode, prefix: boolean, left: ESTree.Expression, rvalue: hir.RValue, need: boolean
): hir.RValue
{
var ctx = scope.ctx;
var identifier: ESTree.Identifier;
var memb: ESTree.MemberExpression;
var variable: Variable;
if (identifier = NT.Identifier.isTypeOf(left)) {
variable = findVariable(scope, identifier);
if (!variable.readOnly)
variable.setAssigned(ctx);
else
(scope.ctx.strictMode ? error : warning)(location(left), `modifying read-only symbol ${variable.name}`);
if (opcode === hir.OpCode.ASSIGN) {
if (!variable.readOnly)
ctx.builder.genAssign(variable.hvar, rvalue);
return rvalue;
} else {
variable.setAccessed(true, ctx);
if (!prefix && need) { // Postfix? It only matters if we need the result
var res = ctx.allocTemp();
ctx.builder.genUnop(hir.OpCode.TO_NUMBER, res,
variable.constantValue !== null ? variable.constantValue : variable.hvar
);
ctx.releaseTemp(rvalue);
if (!variable.readOnly)
ctx.builder.genBinop(opcode, variable.hvar, variable.hvar, rvalue);
return res;
} else {
ctx.releaseTemp(rvalue);
if (!variable.readOnly) {
ctx.builder.genBinop(opcode, variable.hvar, variable.hvar, rvalue);
return variable.hvar;
} else {
var res = ctx.allocTemp();
ctx.builder.genBinop(opcode, res,
variable.constantValue !== null ? variable.constantValue : variable.hvar,
rvalue
);
return res;
}
}
}
} else if(memb = NT.MemberExpression.isTypeOf(left)) {
var membObject: hir.RValue;
var membPropName: hir.RValue;
if (memb.computed)
membPropName = compileSubExpression(scope, memb.property, true, null, null);
else
membPropName = hir.wrapImmediate(NT.Identifier.cast(memb.property).name);
membObject = compileSubExpression(scope, memb.object, true, null, null);
if (opcode === hir.OpCode.ASSIGN) {
ctx.builder.genPropSet(membObject, membPropName, rvalue);
ctx.releaseTemp(membObject);
ctx.releaseTemp(membPropName);
return rvalue;
} else {
var val: hir.Local = ctx.allocTemp();
ctx.builder.genPropGet(val, membObject, membPropName);
if (!prefix && need) { // Postfix? It only matters if we need the result
ctx.builder.genUnop(hir.OpCode.TO_NUMBER, val, val);
ctx.releaseTemp(rvalue);
var tmp = ctx.allocTemp();
ctx.builder.genBinop(opcode, tmp, val, rvalue);
ctx.builder.genPropSet(membObject, membPropName, tmp);
ctx.releaseTemp(tmp);
} else {
ctx.releaseTemp(rvalue);
ctx.builder.genBinop(opcode, val, val, rvalue);
ctx.builder.genPropSet(membObject, membPropName, val);
}
ctx.releaseTemp(membObject);
ctx.releaseTemp(membPropName);
return val;
}
} else {
error(location(left), "not an assignable expression");
return hir.undefinedValue;
}
}
function compileUpdateExpression (scope: Scope, e: ESTree.UpdateExpression, need: boolean): hir.RValue
{
var opcode: hir.OpCode = e.operator === "++" ? hir.OpCode.ADD_N : hir.OpCode.SUB_N;
return _compileAssignment(scope, opcode, e.prefix, e.argument, hir.wrapImmediate(1), need);
}
function isStringLiteral (e: ESTree.Expression): string
{
var lit = NT.Literal.isTypeOf(e);
return lit && typeof lit.value === "string" ? <string>lit.value : null;
}
/**
* Used by compiler extensions when an an argument is required to be a constant string. Besides a
* single string literal we also handle addition of literals.
* @param e
* @param reportError
* @returns {string}
*/
function parseConstantString (e: ESTree.Expression, reportError: boolean = true): string
{
var str = isStringLiteral(e);
if (str !== null)
return str;
var bine = NT.BinaryExpression.isTypeOf(e);
if (!bine || bine.operator !== "+") {
if (reportError)
error(location(e), "not a constant string literal");
return null;
}
var a = parseConstantString(bine.left, reportError);
if (a === null)
return null;
var b = parseConstantString(bine.right, reportError);
if (b === null)
return null;
return a + b;
}
function compileAsmExpression (scope: Scope, e: ESTree.CallExpression, need: boolean): hir.RValue
{
// __asm__( options: object, result: [], inputs: [[]*]?, pattern: string )
var resultBinding: AsmBinding = null;
var bindings: AsmBinding[] = [];
var bindingMap = new StringMap<AsmBinding>();
var pattern: hir.AsmPattern = null;
var sysBindings : {[name: string]: hir.SystemReg} = Object.create(null);
sysBindings["%frame"] = hir.frameReg;
sysBindings["%argc"] = hir.argcReg;
sysBindings["%argv"] = hir.argvReg;
function addBinding (name: string, e: ESTree.Expression): AsmBinding
{
var b = new AsmBinding(bindings.length, name, e);
bindings.push(b);
bindingMap.set(name, b);
return b;
}
function parseOptions (e: ESTree.Expression): void
{
var objE = NT.ObjectExpression.isTypeOf(e);
if (!objE) {
error(location(e), "'__asm__' parameter 1 (options) must be an object literal");
} else if (objE.properties.length > 0) {
error(location(e), "'__asm__': no options are currently implemented");
}
}
function parseResult (e: ESTree.Expression): void
{
var arrE = NT.ArrayExpression.isTypeOf(e);
if (!arrE) {
error(location(e), "'__asm__' parameter 2 (result) must be an array literal");
return;
}
if (arrE.elements.length === 0)
return;
var name = isStringLiteral(arrE.elements[0]);
if (!name) {
error(location(arrE.elements[0]), "__asm__ result name must be a string literal");
return;
}
resultBinding = addBinding(name, null);
resultBinding.result = true;
if (arrE.elements.length > 1) {
error(location(arrE.elements[1]), "unsupported __asm__ result options");
return;
}
}
function parseInputDeclaration (e: ESTree.Expression): void
{
var arrE = NT.ArrayExpression.isTypeOf(e);
if (!arrE) {
error(location(e), "'__asm__' every input declaration must be an array literal");
return;
}
var name = isStringLiteral(arrE.elements[0]);
if (!name) {
error(location(e), "'__asm__' every input declaration must begin with a string literal");
return;
}
if (bindingMap.has(name)) {
error(location(e), `'__asm__' binding '${name}' already declared`);
return;
}
if (arrE.elements.length < 2) {
error(location(e), "'__asm__' input declaration needs an initializing expression");
return;
}
addBinding(name, arrE.elements[1]);
if (arrE.elements.length > 2) {
error(location(e), "'__asm__' input declaration options not supported yet");
return;
}
}
function parseInputs (e: ESTree.Expression): void
{
var arrE = NT.ArrayExpression.isTypeOf(e);
if (!arrE) {
error(location(e), "'__asm__' parameter 3 (inputs) must be an array literal");
return;
}
arrE.elements.forEach(parseInputDeclaration);
}
function parseClobberDeclaration (e: ESTree.Expression): void
{
var arrE = NT.ArrayExpression.isTypeOf(e);
if (!arrE) {
error(location(e), "'__asm__' every clobber declaration must be an array literal");
return;
}
var name = isStringLiteral(arrE.elements[0]);
if (!name) {
error(location(e), "'__asm__' every clobber declaration must begin with a string literal");
return;
}
if (bindingMap.has(name)) {
error(location(e), `'__asm__' binding '${name}' already declared`);
return;
}
addBinding(name, null);
if (arrE.elements.length > 1) {
error(location(e), "'__asm__' input declaration options not supported yet");
return;
}
}
function parseClobbers (e: ESTree.Expression): void
{
var arrE = NT.ArrayExpression.isTypeOf(e);
if (!arrE) {
error(location(e), "'__asm__' parameter 4 (clobbers) must be an array literal");
return;
}
arrE.elements.forEach(parseClobberDeclaration);
}
function parsePattern (e: ESTree.Expression): void
{
var patstr = parseConstantString(e);
if (patstr === null)
return;
var lastIndex = 0;
var asmPat: hir.AsmPattern = [];
var re = /(%%)|(%\[([^\]]*)\])/g;
var match : RegExpExecArray;
function pushStr (str: string): void
{
if (asmPat.length && typeof asmPat[asmPat.length-1] === "string")
asmPat[asmPat.length-1] += str;
else
asmPat.push(str);
}
while (match = re.exec(patstr)) {
if (match.index > lastIndex)
pushStr(patstr.slice(lastIndex, match.index));
if (match[1]) { // "%%"?
pushStr("%");
} else {
var name = match[3];
var bnd = bindingMap.get(name);
if (!bnd) {
var sysbnd = sysBindings[name];
if (!sysbnd) {
error(location(e), `undeclared binding '%[${name}]'`);
return;
}
bnd = addBinding(name, null);
bnd.hv = sysbnd;
}
bnd.used = true;
asmPat.push(bnd.index);
}
lastIndex = re.lastIndex;
}
if (lastIndex < patstr.length)
pushStr(patstr.slice(lastIndex, patstr.length));
if (resultBinding && !resultBinding.used) {
error(location(e), `result binding '%[${resultBinding.name}]' wasn't used`);
return;
}
bindingMap.forEach((b) => {
if (!b.used)
warning(location(e), `binding '%[${b.name}]' wasn't used`);
});
pattern = asmPat;
}
if (e.arguments.length !== 5) {
error(location(e), "'__asm__' requires exactly five arguments");
} else {
parseOptions(e.arguments[0]);
parseResult(e.arguments[1]);
parseInputs(e.arguments[2]);
parseClobbers(e.arguments[3]);
parsePattern(e.arguments[4]);
}
if (!pattern) // error?
return need ? hir.nullReg : null;
var hbnd: hir.RValue[] = new Array<hir.RValue>(bindings.length);
var dest: hir.LValue = null;
for ( var i = 0; i < bindings.length; ++i ) {
var b = bindings[i];
if (!b.used)
hbnd[i] = null;
else if (b.hv !== null)
hbnd[i] = b.hv;
else if (b.e)
hbnd[i] = compileSubExpression(scope, b.e, true, null, null);
else {
var temp = scope.ctx.allocTemp();
hbnd[i] = temp;
if (b.result)
dest = temp;
}
}
// Release the temporaries in reverse order, except the result
for ( var i = bindings.length-1; i >= 0; --i )
if (!bindings[i].result) // if not an output
scope.ctx.releaseTemp(hbnd[i]);
scope.ctx.builder.genAsm(dest, hbnd, pattern);
if (need) {
if (dest) {
return dest;
} else {
warning(location(e), "'__asm__': no result value generated");
return hir.undefinedValue;
}
} else {
if (dest)
warning(location(e), "'__asm__': result value ignored");
scope.ctx.releaseTemp(dest);
return null;
}
}
function compileAsmHExpression (scope: Scope, e: ESTree.CallExpression, need: boolean): hir.RValue
{
function parseOptions (e: ESTree.Expression): void
{
var objE = NT.ObjectExpression.isTypeOf(e);
if (!objE) {
error(location(e), "'__asmh__' parameter 1 (options) must be an object literal");
} else if (objE.properties.length > 0) {
error(location(e), "'__asmh__': no options are currently implemented");
}
}
exit:
{
if (e.arguments.length !== 2) {
error(location(e), "'__asmh__' requires exactly two arguments");
break exit;
}
parseOptions(e.arguments[0]);
var str = parseConstantString(e.arguments[1]);
if (str === null)
break exit;
scope.ctx.builder.module.addAsmHeader(str);
}
return need ? hir.undefinedValue : null;
}
function compileRequireExpression (scope: Scope, e: ESTree.CallExpression, need: boolean): hir.RValue
{
var m: Module = null;
if (e.arguments.length > 0) {
var str = parseConstantString(e.arguments[0], false);
if (str !== null) {
var m = m_modules.resolve(m_dirname, str);
if (m.notFound) {
warning(location(e), `cannot resolve module '${str}'`);
} else {
// Replace the argument with the resolved path
var arg: ESTree.Literal = {
type: NT.Literal.name,
value: m.path,
start: e.arguments[0].start,
end: e.arguments[0].end
};
if (e.arguments[0].loc)
arg.loc = e.arguments[0].loc;
if (e.arguments[0].range)
arg.range = e.arguments[0].range;
e.arguments[0] = arg;
}
}
}
if (!m)
warning(location(e), "dynamic 'require' invocation cannot be analyzed at compile time");
return _compileCallExpression(scope, e, need);
}
function compileConditionalExpression (
scope: Scope, e: ESTree.ConditionalExpression, need: boolean, onTrue: hir.Label, onFalse: hir.Label
): hir.RValue
{
var ctx = scope.ctx;
var trueLab = ctx.builder.newLabel();
var falseLab = ctx.builder.newLabel();
var endLab: hir.Label;
var dest: hir.Local = null;
var v1: hir.RValue;
var v2: hir.RValue;
if (!onTrue)
endLab = ctx.builder.newLabel();
compileSubExpression(scope, e.test, true, trueLab, falseLab);
ctx.builder.genLabel(trueLab);
v1 = compileSubExpression(scope, e.consequent, need, onTrue, onFalse);
ctx.releaseTemp(v1);
if (!onTrue) {
if (need) {
dest = ctx.allocTemp();
ctx.builder.genAssign(dest, v1);
ctx.releaseTemp(dest);
}
ctx.builder.genGoto(endLab);
}
ctx.builder.genLabel(falseLab);
v2 = compileSubExpression(scope, e.alternate, need, onTrue, onFalse);
ctx.releaseTemp(v2);
if (!onTrue) {
if (need) {
ctx.allocSpecific(dest);
ctx.builder.genAssign(dest, v2);
}
ctx.builder.genLabel(endLab);
}
return dest;
}
function extractMagicCallIdentifier (scope: Scope, e: ESTree.CallExpression): string
{
var identifierExp: ESTree.Identifier;
if (identifierExp = NT.Identifier.isTypeOf(e.callee)) {
var name = identifierExp.name;
if (name === "__asm__")
return "asm";
else if (name === "__asmh__")
return "asmh";
var v = scope.lookup(name);
if (v) {
if (v === m_specVars.require)
return "require";
}
}
return null;
}
function compileCallExpression (scope: Scope, e: ESTree.CallExpression, need: boolean): hir.RValue
{
// Check for compiler extensions
switch (extractMagicCallIdentifier(scope, e)) {
case "asm": return compileAsmExpression(scope, e, need);
case "asmh": return compileAsmHExpression(scope, e, need);
case "require": return compileRequireExpression(scope, e, need);
}
return _compileCallExpression(scope, e, need);
}
function _compileCallExpression (scope: Scope, e: ESTree.CallExpression, need: boolean): hir.RValue
{
var ctx = scope.ctx;
var args: hir.RValue[] = [];
var fref: hir.FunctionBuilder = null;
var closure: hir.RValue;
var thisArg: hir.RValue;
var memb: ESTree.MemberExpression;
if (memb = NT.MemberExpression.isTypeOf(e.callee)) {
var tmp = compileMemberExpressionHelper(scope, memb, true, true);
closure = tmp.dest;
thisArg = tmp.obj;
} else {
closure = compileSubExpression(scope, e.callee, true, null, null);
thisArg = hir.undefinedValue;
}
args.push(thisArg);
e.arguments.forEach((e: ESTree.Expression) => {
args.push( compileSubExpression(scope, e, true, null, null) );
});
for ( var i = args.length - 1; i >= 1 /*stop at 'thisArg'*/; --i )
ctx.releaseTemp(args[i]);
ctx.releaseTemp(thisArg);
ctx.releaseTemp(closure);
var dest: hir.LValue = null;
if (need)
dest = ctx.allocTemp();
var t = ctx.builder.genCall(dest, closure, args);
setSourceLocation(t, e);
return dest;
}
function compileNewExpression (scope: Scope, e: ESTree.NewExpression, need: boolean): hir.RValue
{
var ctx = scope.ctx;
var objLab = ctx.builder.newLabel();
var notObjLab = ctx.builder.newLabel();
var closure = compileSubExpression(scope, e.callee);
var prototype = ctx.allocTemp();
ctx.builder.genPropGet(prototype, closure, hir.wrapImmediate("prototype"));
ctx.builder.genIfIsObject(prototype, objLab, notObjLab);
ctx.builder.genLabel(notObjLab);
ctx.builder.genLoadRuntimeVar(prototype, "objectPrototype");
ctx.builder.genLabel(objLab);
ctx.releaseTemp(prototype);
var obj = ctx.allocTemp();
ctx.builder.genCreate(obj, prototype);
var args: hir.RValue[] = [];
args.push(obj);
e.arguments.forEach((e: ESTree.Expression) => {
args.push( compileSubExpression(scope, e, true, null, null) );
});
for ( var i = args.length - 1; i > 0; --i )
ctx.releaseTemp(args[i]);
var res = ctx.allocTemp();
var t = ctx.builder.genCallCons(res, closure, args);
setSourceLocation(t, e);
var undLab = ctx.builder.newLabel();
var notUndLab = ctx.builder.newLabel();
ctx.builder.genIf(hir.OpCode.IF_STRICT_EQ, res, hir.undefinedValue, undLab, notUndLab );
ctx.builder.genLabel(notUndLab);
ctx.releaseTemp(res);
ctx.builder.genAssign(obj, res);
ctx.builder.genLabel(undLab);
return obj;
}
function compileMemberExpressionHelper (scope: Scope, e: ESTree.MemberExpression, need: boolean, needObj: boolean)
: { obj: hir.RValue; dest: hir.RValue }
{
var propName: hir.RValue;
if (e.computed)
propName = compileSubExpression(scope, e.property);
else
propName = hir.wrapImmediate(NT.Identifier.cast(e.property).name);
var obj: hir.RValue = compileSubExpression(scope, e.object, true, null, null);
if (!needObj)
scope.ctx.releaseTemp(obj);
scope.ctx.releaseTemp(propName);
var dest: hir.LValue;
if (need)
dest = scope.ctx.allocTemp();
else
dest = hir.nullReg;
scope.ctx.builder.genPropGet(dest, obj, propName);
return { obj: needObj ? obj : null, dest: need ? dest: null };
}
function compileMemberExpression (scope: Scope, e: ESTree.MemberExpression, need: boolean): hir.RValue
{
return compileMemberExpressionHelper(scope, e, need, false).dest;
}
}
// NOTE: since we have a very dumb backend (for now), we have to perform some optimizations
// that wouldn't normally be necessary
export function compile (
m_fileName: string, m_reporter: IErrorReporter, m_options: Options, m_doneCB: () => void
): void
{
var m_globalContext: FunctionContext;
var m_input: string;
var m_moduleBuilder = new hir.ModuleBuilder(m_options.debug);
var m_modules = new Modules(m_options.moduleDirs);
compileProgram();
fireCB();
return;
function error (loc: ESTree.SourceLocation, msg: string)
{
m_reporter.error(loc, msg);
}
function warning (loc: ESTree.SourceLocation, msg: string)
{
m_reporter.warning(loc, msg);
}
function note (loc: ESTree.SourceLocation, msg: string)
{
m_reporter.note(loc, msg);
}
function location (node: ESTree.Node): ESTree.SourceLocation
{
if (!node.loc) {
var pos = acorn.getLineInfo(m_input, node.start);
return { source: m_fileName, start: pos, end: pos };
} else {
return node.loc;
}
}
function fireCB (): void
{
if (!m_doneCB)
return;
var cb = m_doneCB;
m_doneCB = null;
process.nextTick(cb);
}
function compileProgram (): void
{
var topLevelBuilder = m_moduleBuilder.createTopLevel();
m_globalContext = new FunctionContext(null, null, topLevelBuilder.name, topLevelBuilder);
m_globalContext.strictMode = m_options.strictMode;
var runtime = compileRuntime(m_globalContext);
if (!runtime || m_reporter.errorCount() > 0)
return;
// Resolve and compile all system modules
if (!compileResolvedModules(runtime))
return;
callRuntimeFunction(runtime, runtime.runtimeInit);
// Resolve main
var main: Module = m_modules.resolve("", path.resolve(process.cwd(), m_fileName));
main.printable = m_fileName;
if (!compileResolvedModules(runtime))
return;
callModuleRequire(runtime, main);
if (runtime.runtimeEventLoop)
callRuntimeFunction(runtime, runtime.runtimeEventLoop);
runtime.ctx.close();
topLevelBuilder.close();
m_moduleBuilder.prepareForCodegen();
if (m_options.dumpHIR)
runtime.ctx.builder.dump();
if (!m_options.dumpAST && !m_options.dumpHIR)
produceOutput();
}
function compileResolvedModules (runtime: Runtime): boolean
{
var m: Module;
while (m = m_modules.next()) {
if (m.notFound) {
error(null, `cannot find module '${m.printable}'`);
return false;
}
m.modVar = compileModule(runtime, runtime.ctx, m.path);
if (m_reporter.errorCount() > 0)
return false;
callDefineModule(runtime, m);
}
return true;
}
function compileRuntime (parentContext: FunctionContext): Runtime
{
var runtimeFileName = "runtime/js/runtime.js";
var coreFilesDir = "runtime/js/core/";
var runtimeCtx = new FunctionContext(
parentContext, parentContext.scope, runtimeFileName, parentContext.builder.newClosure(runtimeFileName)
);
function declareBuiltinConstructor (name: string, mangled: string, runtimeVar: string): void
{
var fobj = runtimeCtx.addBuiltinClosure(name, mangled+"Function", runtimeVar);
var consobj = runtimeCtx.addBuiltinClosure(name, mangled+"Constructor", runtimeVar);
var vobj = runtimeCtx.scope.newVariable(fobj.name, fobj.closureVar);
vobj.funcRef = fobj;
vobj.consRef = consobj;
vobj.declared = true;
vobj.initialized = true;
}
declareBuiltinConstructor("Object", "js::object", "object");
declareBuiltinConstructor("Function", "js::function", "function");
declareBuiltinConstructor("String", "js::string", "string");
declareBuiltinConstructor("Number", "js::number", "number");
declareBuiltinConstructor("Boolean", "js::boolean", "boolean");
declareBuiltinConstructor("Array", "js::array", "array");
declareBuiltinConstructor("Error", "js::error", "error");
declareBuiltinConstructor("TypeError", "js::typeError", "typeError");
declareBuiltinConstructor("ArrayBuffer", "js::ArrayBuffer::a", "arrayBuffer");
declareBuiltinConstructor("DataView", "js::DataView::a", "dataView");
declareBuiltinConstructor("Int8Array", "js::Int8Array::a", "int8Array");
declareBuiltinConstructor("Uint8Array", "js::Uint8Array::a", "uint8Array");
declareBuiltinConstructor("Uint8ClampedArray", "js::Uint8ClampedArray::a", "uint8ClampedArray");
declareBuiltinConstructor("Int16Array", "js::Int16Array::a", "int16Array");
declareBuiltinConstructor("Uint16Array", "js::Uint16Array::a", "uint16Array");
declareBuiltinConstructor("Int32Array", "js::Int32Array::a", "int32Array");
declareBuiltinConstructor("Uint32Array", "js::Uint32Array::a", "uint32Array");
declareBuiltinConstructor("Float32Array", "js::Float32Array::a", "float32Array");
declareBuiltinConstructor("Float64Array", "js::Float64Array::a", "float64Array");
runtimeCtx.scope.newConstant("NaN", hir.wrapImmediate(NaN));
runtimeCtx.scope.newConstant("Infinity", hir.wrapImmediate(Infinity));
runtimeCtx.scope.newConstant("undefined", hir.undefinedValue);
if (!compileSource(runtimeCtx.scope, runtimeCtx.scope, runtimeFileName, m_reporter, new SpecialVars(), m_modules, m_options))
return null;
var r: Runtime = new Runtime(runtimeCtx);
var coreScope = compileCoreFiles(r, coreFilesDir);
if (!coreScope)
return null;
r.lookupSymbols(coreScope);
if (!r.allSymbolsDefined())
error(null, "internal symbols missing from runtime");
return r;
}
/**
* Compile a core file in a nested scope. We want to achieve visibility separation, but
* we don't want the physical separation of another environment, etc.
*/
function compileInANestedScope (r: Runtime, coreCtx: FunctionContext, fileName: string): Scope
{
var scope = new Scope(coreCtx, true, coreCtx.scope);
if (!compileInAScope(r, scope, fileName))
return null;
return scope;
}
function compileCoreFiles (r: Runtime, coreFilesDir: string): Scope
{
var runtimeCtx: FunctionContext = r.ctx;
var coreScope = new Scope(runtimeCtx, true, runtimeCtx.scope);
var entries: string[];
try {
entries = fs.readdirSync(coreFilesDir);
} catch (e) {
error(null, `cannot access '${coreFilesDir}'`);
return null;
}
entries.sort();
for ( var i = 0, e = entries.length; i < e; ++i ) {
var entry = entries[i];
if (entry[0] !== "." && path.extname(entry) === ".js") {
if (!compileInAScope(r, coreScope, path.join(coreFilesDir,entry)))
return null;
// Update the internal symbols after every new core file
r.lookupSymbols(coreScope);
}
}
return coreScope;
}
/**
* Compile a core file in a pre-defined scope. We want to achieve visibility separation, but
* we don't want the physical separation of another environment, etc.
*/
function compileInAScope (r: Runtime, scope: Scope, fileName: string): boolean
{
var coreCtx: FunctionContext = scope.ctx;
var specialVars = new SpecialVars(r);
definePaths(scope, fileName);
return compileSource(scope, coreCtx.scope, fileName, m_reporter, specialVars, m_modules, m_options);
}
function compileModule (runtime: Runtime, parentContext: FunctionContext, fileName: string): Variable
{
var ctx = new FunctionContext(
parentContext, parentContext.scope, fileName, parentContext.addClosure(fileName)
);
hir.setSourceLocation(ctx.builder, fileName, 1, 0);
var modVar = parentContext.scope.newAnonymousVariable(fileName, ctx.builder.closureVar);
modVar.funcRef = ctx.builder;
var modp = ctx.addParam("module");
var require = ctx.addParam("require");
var specVars = new SpecialVars(runtime);
specVars.require = require;
var tmp = ctx.allocTemp();
modp.setAccessed(true, ctx);
ctx.builder.genPropGet(tmp, modp.hvar, hir.wrapImmediate("exports"));
defineVar(ctx.scope, "exports", tmp);
definePaths(ctx.scope, fileName);
compileSource(ctx.scope, ctx.scope, fileName, m_reporter, specVars, m_modules, m_options);
ctx.close();
return modVar;
}
function callDefineModule (runtime: Runtime, m: Module): void
{
var ctx = runtime.ctx;
ctx.builder.genCall(null, runtime.defineModule.hvar, [
hir.undefinedValue,
hir.wrapImmediate(m.path),
m.modVar.funcRef.closureVar
]);
m.modVar.setAccessed(true, ctx);
runtime.defineModule.setAccessed(true, ctx);
}
function callRuntimeFunction (runtime: Runtime, f: Variable): void
{
var ctx = runtime.ctx;
ctx.builder.genCall(null, f.hvar, [
hir.undefinedValue
]);
f.setAccessed(true, ctx);
}
function callModuleRequire (runtime: Runtime, m: Module, result: hir.LValue = null): void
{
var ctx = runtime.ctx;
ctx.builder.genCall(result, runtime.moduleRequire.hvar, [
hir.undefinedValue,
hir.wrapImmediate(m.path)
]);
runtime.moduleRequire.setAccessed(true, ctx);
}
function definePaths (scope: Scope, fileName: string)
{
if (!path.isAbsolute(fileName))
fileName = path.resolve(fileName);
defineVar(scope, "__filename", hir.wrapImmediate(fileName));
defineVar(scope, "__dirname", hir.wrapImmediate(path.dirname(fileName)));
}
function defineVar (scope: Scope, name: string, value: hir.RValue): Variable
{
var v: Variable;
if (!(v = scope.getVar(name)))
v = scope.newVariable(name);
v.declared = true;
v.setAssigned(scope.ctx);
scope.ctx.releaseTemp(value);
scope.ctx.builder.genAssign(v.hvar, value);
return v;
}
function stripPathAndExtension (fn: string): string
{
var pos = fn.lastIndexOf(".");
if (pos > 0)
fn = fn.slice(0, pos);
pos = fn.lastIndexOf("/");
if (pos > 0)
fn = fn.slice(pos+1, fn.length);
return fn;
}
function generateC (out: NodeJS.WritableStream): void
{
var backend = new cxxbackend.CXXBackend(
m_moduleBuilder.getTopLevel(), m_moduleBuilder.getAsmHeaders(), m_moduleBuilder.isDebugMode()
);
backend.generateC(out, m_options.strictMode);
}
function produceOutput () {
if (m_options.sourceOnly) {
if (m_options.outputName === "-") { // output to pipe?
generateC(process.stdout);
} else {
var ext = ".cxx";
var outName: string = null;
if (m_options.outputName !== null) {
outName = m_options.outputName;
if (outName.lastIndexOf(".") <= 0) // if no extension, add one (note that "." at pos 0 is not an ext)
outName += ext;
} else {
outName = stripPathAndExtension(m_fileName) + ext;
}
try {
var fd = fs.openSync(outName, "w");
var out = fs.createWriteStream(null, {fd: fd});
generateC(out);
out.end();
out.once("error", (e: any) => {
error(null, e.message);
fireCB();
});
out.once("finish", () => fireCB());
} catch (e) {
error(null, e.message);
}
}
} else {
var ext = m_options.compileOnly ? ".o" : "";
var outName: string = null;
if (m_options.outputName !== null) {
outName = m_options.outputName;
if (outName.lastIndexOf(".") <= 0) // if no extension, add one (note that "." at pos 0 is not an ext)
outName += ext;
} else {
outName = stripPathAndExtension(m_fileName) + ext;
}
var cc = "c++";
if (process.env["CC"])
cc = process.env["CC"];
var cflags: string[] = [];
if (process.env["CFLAGS"])
cflags = process.env["CFLAGS"].split(" ");
var args: string[] = [];
m_options.includeDirs.forEach((d) => args.push("-I"+d));
args.push("-xc++", "--std=c++11");
if (cflags.length > 0) {
args = args.concat(cflags);
} else {
if (m_options.debug)
args.push("-g");
else
args.push("-O1");
}
if (m_options.debug)
args.push("-DJS_DEBUG");
if (m_options.compileOnly)
args.push("-c");
args.push("-");
if (!m_options.compileOnly) {
m_options.libDirs.forEach((d) => args.push("-L"+d));
m_options.libs.forEach((d) => args.push("-l"+d));
}
args.push("-o", outName);
if (m_options.verbose)
console.log(cc, args.join(" "));
var child = child_process.spawn(
cc,
args,
{stdio: ['pipe', process.stdout, process.stderr] }
);
child.stdin.once("error", (e: any) => {
error(null, e.message);
});
child.stdin.write(util.format("#line 1 \"%s\"\n", m_fileName));
generateC(child.stdin);
child.stdin.end();
child.once("error", (e: any) => {
error(null, e.message);
fireCB();
});
child.once("exit", (code: number, signal: string) => {
if (code !== 0)
error(null, "child process terminated with code "+ code);
else if (signal)
error(null, "child process terminated with an error");
fireCB();
});
}
}
} | the_stack |
import * as coreClient from "@azure/core-client";
/** The List availabilityStatus operation response. */
export interface AvailabilityStatusListResult {
/** The list of availabilityStatuses. */
value: AvailabilityStatus[];
/** The URI to fetch the next page of availabilityStatuses. Call ListNext() with this URI to fetch the next page of availabilityStatuses. */
nextLink?: string;
}
/** availabilityStatus of a resource. */
export interface AvailabilityStatus {
/** Azure Resource Manager Identity for the availabilityStatuses resource. */
id?: string;
/** current. */
name?: string;
/** Microsoft.ResourceHealth/AvailabilityStatuses. */
type?: string;
/** Azure Resource Manager geo location of the resource. */
location?: string;
/** Properties of availability state. */
properties?: AvailabilityStatusProperties;
}
/** Properties of availability state. */
export interface AvailabilityStatusProperties {
/** Availability status of the resource. When it is null, this availabilityStatus object represents an availability impacting event */
availabilityState?: AvailabilityStateValues;
/** Summary description of the availability status. */
summary?: string;
/** Details of the availability status. */
detailedStatus?: string;
/** When the resource's availabilityState is Unavailable, it describes where the health impacting event was originated. Examples are planned, unplanned, user initiated or an outage etc. */
reasonType?: string;
/** When the resource's availabilityState is Unavailable, it provides the Timestamp for when the health impacting event was received. */
rootCauseAttributionTime?: Date;
/** In case of an availability impacting event, it describes when the health impacting event was originated. Examples are Lifecycle, Downtime, Fault Analysis etc. */
healthEventType?: string;
/** In case of an availability impacting event, it describes where the health impacting event was originated. Examples are PlatformInitiated, UserInitiated etc. */
healthEventCause?: string;
/** In case of an availability impacting event, it describes the category of a PlatformInitiated health impacting event. Examples are Planned, Unplanned etc. */
healthEventCategory?: string;
/** It is a unique Id that identifies the event */
healthEventId?: string;
/** When the resource's availabilityState is Unavailable and the reasonType is not User Initiated, it provides the date and time for when the issue is expected to be resolved. */
resolutionETA?: Date;
/** Timestamp for when last change in health status occurred. */
occuredTime?: Date;
/** Chronicity of the availability transition. */
reasonChronicity?: ReasonChronicityTypes;
/** Timestamp for when the health was last checked. */
reportedTime?: Date;
/** An annotation describing a change in the availabilityState to Available from Unavailable with a reasonType of type Unplanned */
recentlyResolvedState?: AvailabilityStatusPropertiesRecentlyResolvedState;
/** Lists actions the user can take based on the current availabilityState of the resource. */
recommendedActions?: RecommendedAction[];
/** Lists the service impacting events that may be affecting the health of the resource. */
serviceImpactingEvents?: ServiceImpactingEvent[];
}
/** An annotation describing a change in the availabilityState to Available from Unavailable with a reasonType of type Unplanned */
export interface AvailabilityStatusPropertiesRecentlyResolvedState {
/** Timestamp for when the availabilityState changed to Unavailable */
unavailableOccurredTime?: Date;
/** Timestamp when the availabilityState changes to Available. */
resolvedTime?: Date;
/** Brief description of cause of the resource becoming unavailable. */
unavailabilitySummary?: string;
}
/** Lists actions the user can take based on the current availabilityState of the resource. */
export interface RecommendedAction {
/** Recommended action. */
action?: string;
/** Link to the action */
actionUrl?: string;
/** Substring of action, it describes which text should host the action url. */
actionUrlText?: string;
}
/** Lists the service impacting events that may be affecting the health of the resource. */
export interface ServiceImpactingEvent {
/** Timestamp for when the event started. */
eventStartTime?: Date;
/** Timestamp for when event was submitted/detected. */
eventStatusLastModifiedTime?: Date;
/** Correlation id for the event */
correlationId?: string;
/** Status of the service impacting event. */
status?: ServiceImpactingEventStatus;
/** Properties of the service impacting event. */
incidentProperties?: ServiceImpactingEventIncidentProperties;
}
/** Status of the service impacting event. */
export interface ServiceImpactingEventStatus {
/** Current status of the event */
value?: string;
}
/** Properties of the service impacting event. */
export interface ServiceImpactingEventIncidentProperties {
/** Title of the incident. */
title?: string;
/** Service impacted by the event. */
service?: string;
/** Region impacted by the event. */
region?: string;
/** Type of Event. */
incidentType?: string;
}
/** Error details. */
export interface ErrorResponse {
/**
* The error code.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly code?: string;
/**
* The error message.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly message?: string;
/**
* The error details.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly details?: string;
}
/** Lists the operations response. */
export interface OperationListResult {
/** List of operations available in the resourcehealth resource provider. */
value: Operation[];
}
/** Operation available in the resourcehealth resource provider. */
export interface Operation {
/** Name of the operation. */
name?: string;
/** Properties of the operation. */
display?: OperationDisplay;
}
/** Properties of the operation. */
export interface OperationDisplay {
/** Provider name. */
provider?: string;
/** Resource name. */
resource?: string;
/** Operation name. */
operation?: string;
/** Description of the operation. */
description?: string;
}
/** Banner type of emerging issue. */
export interface StatusBanner {
/** The banner title. */
title?: string;
/** The details of banner. */
message?: string;
/** The cloud type of this banner. */
cloud?: string;
/** The last time modified on this banner. */
lastModifiedTime?: Date;
}
/** Active event type of emerging issue. */
export interface StatusActiveEvent {
/** The active event title. */
title?: string;
/** The details of active event. */
description?: string;
/** The tracking id of this active event. */
trackingId?: string;
/** The impact start time on this active event. */
startTime?: Date;
/** The cloud type of this active event. */
cloud?: string;
/** The severity level of this active event. */
severity?: SeverityValues;
/** The stage of this active event. */
stage?: StageValues;
/** The boolean value of this active event if published or not. */
published?: boolean;
/** The last time modified on this banner. */
lastModifiedTime?: Date;
/** The list of emerging issues impacts. */
impacts?: EmergingIssueImpact[];
}
/** Object of the emerging issue impact on services and regions. */
export interface EmergingIssueImpact {
/** The impacted service id. */
id?: string;
/** The impacted service name. */
name?: string;
/** The list of impacted regions for corresponding emerging issues. */
regions?: ImpactedRegion[];
}
/** Object of impacted region. */
export interface ImpactedRegion {
/** The impacted region id. */
id?: string;
/** The impacted region name. */
name?: string;
}
/** Common fields that are returned in the response for all Azure Resource Manager resources */
export interface Resource {
/**
* Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly id?: string;
/**
* The name of the resource
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/**
* The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts"
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly type?: string;
}
/** The list of emerging issues. */
export interface EmergingIssueListResult {
/** The list of emerging issues. */
value?: EmergingIssuesGetResult[];
/** The link used to get the next page of emerging issues. */
nextLink?: string;
}
/** The Get EmergingIssues operation response. */
export type EmergingIssuesGetResult = Resource & {
/** Timestamp for when last time refreshed for ongoing emerging issue. */
refreshTimestamp?: Date;
/** The list of emerging issues of banner type. */
statusBanners?: StatusBanner[];
/** The list of emerging issues of active event type. */
statusActiveEvents?: StatusActiveEvent[];
};
/** Known values of {@link SeverityValues} that the service accepts. */
export enum KnownSeverityValues {
Information = "Information",
Warning = "Warning",
Error = "Error"
}
/**
* Defines values for SeverityValues. \
* {@link KnownSeverityValues} can be used interchangeably with SeverityValues,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Information** \
* **Warning** \
* **Error**
*/
export type SeverityValues = string;
/** Known values of {@link StageValues} that the service accepts. */
export enum KnownStageValues {
Active = "Active",
Resolve = "Resolve",
Archived = "Archived"
}
/**
* Defines values for StageValues. \
* {@link KnownStageValues} can be used interchangeably with StageValues,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Active** \
* **Resolve** \
* **Archived**
*/
export type StageValues = string;
/** Defines values for AvailabilityStateValues. */
export type AvailabilityStateValues = "Available" | "Unavailable" | "Unknown";
/** Defines values for ReasonChronicityTypes. */
export type ReasonChronicityTypes = "Transient" | "Persistent";
/** Optional parameters. */
export interface AvailabilityStatusesListBySubscriptionIdOptionalParams
extends coreClient.OperationOptions {
/** The filter to apply on the operation. For more information please see https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN */
filter?: string;
/** Setting $expand=recommendedactions in url query expands the recommendedactions in the response. */
expand?: string;
}
/** Contains response data for the listBySubscriptionId operation. */
export type AvailabilityStatusesListBySubscriptionIdResponse = AvailabilityStatusListResult;
/** Optional parameters. */
export interface AvailabilityStatusesListByResourceGroupOptionalParams
extends coreClient.OperationOptions {
/** The filter to apply on the operation. For more information please see https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN */
filter?: string;
/** Setting $expand=recommendedactions in url query expands the recommendedactions in the response. */
expand?: string;
}
/** Contains response data for the listByResourceGroup operation. */
export type AvailabilityStatusesListByResourceGroupResponse = AvailabilityStatusListResult;
/** Optional parameters. */
export interface AvailabilityStatusesGetByResourceOptionalParams
extends coreClient.OperationOptions {
/** The filter to apply on the operation. For more information please see https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN */
filter?: string;
/** Setting $expand=recommendedactions in url query expands the recommendedactions in the response. */
expand?: string;
}
/** Contains response data for the getByResource operation. */
export type AvailabilityStatusesGetByResourceResponse = AvailabilityStatus;
/** Optional parameters. */
export interface AvailabilityStatusesListOptionalParams
extends coreClient.OperationOptions {
/** The filter to apply on the operation. For more information please see https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN */
filter?: string;
/** Setting $expand=recommendedactions in url query expands the recommendedactions in the response. */
expand?: string;
}
/** Contains response data for the list operation. */
export type AvailabilityStatusesListResponse = AvailabilityStatusListResult;
/** Optional parameters. */
export interface AvailabilityStatusesListBySubscriptionIdNextOptionalParams
extends coreClient.OperationOptions {
/** The filter to apply on the operation. For more information please see https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN */
filter?: string;
/** Setting $expand=recommendedactions in url query expands the recommendedactions in the response. */
expand?: string;
}
/** Contains response data for the listBySubscriptionIdNext operation. */
export type AvailabilityStatusesListBySubscriptionIdNextResponse = AvailabilityStatusListResult;
/** Optional parameters. */
export interface AvailabilityStatusesListByResourceGroupNextOptionalParams
extends coreClient.OperationOptions {
/** The filter to apply on the operation. For more information please see https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN */
filter?: string;
/** Setting $expand=recommendedactions in url query expands the recommendedactions in the response. */
expand?: string;
}
/** Contains response data for the listByResourceGroupNext operation. */
export type AvailabilityStatusesListByResourceGroupNextResponse = AvailabilityStatusListResult;
/** Optional parameters. */
export interface AvailabilityStatusesListNextOptionalParams
extends coreClient.OperationOptions {
/** The filter to apply on the operation. For more information please see https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN */
filter?: string;
/** Setting $expand=recommendedactions in url query expands the recommendedactions in the response. */
expand?: string;
}
/** Contains response data for the listNext operation. */
export type AvailabilityStatusesListNextResponse = AvailabilityStatusListResult;
/** Optional parameters. */
export interface ChildAvailabilityStatusesGetByResourceOptionalParams
extends coreClient.OperationOptions {
/** The filter to apply on the operation. For more information please see https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN */
filter?: string;
/** Setting $expand=recommendedactions in url query expands the recommendedactions in the response. */
expand?: string;
}
/** Contains response data for the getByResource operation. */
export type ChildAvailabilityStatusesGetByResourceResponse = AvailabilityStatus;
/** Optional parameters. */
export interface ChildAvailabilityStatusesListOptionalParams
extends coreClient.OperationOptions {
/** The filter to apply on the operation. For more information please see https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN */
filter?: string;
/** Setting $expand=recommendedactions in url query expands the recommendedactions in the response. */
expand?: string;
}
/** Contains response data for the list operation. */
export type ChildAvailabilityStatusesListResponse = AvailabilityStatusListResult;
/** Optional parameters. */
export interface ChildAvailabilityStatusesListNextOptionalParams
extends coreClient.OperationOptions {
/** The filter to apply on the operation. For more information please see https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN */
filter?: string;
/** Setting $expand=recommendedactions in url query expands the recommendedactions in the response. */
expand?: string;
}
/** Contains response data for the listNext operation. */
export type ChildAvailabilityStatusesListNextResponse = AvailabilityStatusListResult;
/** Optional parameters. */
export interface ChildResourcesListOptionalParams
extends coreClient.OperationOptions {
/** The filter to apply on the operation. For more information please see https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN */
filter?: string;
/** Setting $expand=recommendedactions in url query expands the recommendedactions in the response. */
expand?: string;
}
/** Contains response data for the list operation. */
export type ChildResourcesListResponse = AvailabilityStatusListResult;
/** Optional parameters. */
export interface ChildResourcesListNextOptionalParams
extends coreClient.OperationOptions {
/** The filter to apply on the operation. For more information please see https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN */
filter?: string;
/** Setting $expand=recommendedactions in url query expands the recommendedactions in the response. */
expand?: string;
}
/** Contains response data for the listNext operation. */
export type ChildResourcesListNextResponse = AvailabilityStatusListResult;
/** Optional parameters. */
export interface OperationsListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type OperationsListResponse = OperationListResult;
/** Optional parameters. */
export interface EmergingIssuesGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type EmergingIssuesGetResponse = EmergingIssuesGetResult;
/** Optional parameters. */
export interface EmergingIssuesListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type EmergingIssuesListResponse = EmergingIssueListResult;
/** Optional parameters. */
export interface EmergingIssuesListNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listNext operation. */
export type EmergingIssuesListNextResponse = EmergingIssueListResult;
/** Optional parameters. */
export interface MicrosoftResourceHealthOptionalParams
extends coreClient.ServiceClientOptions {
/** server parameter */
$host?: string;
/** Api Version */
apiVersion?: string;
/** Overrides client endpoint. */
endpoint?: string;
} | the_stack |
import React from "react";
import ReactReconciler from "react-reconciler";
import { unstable_now as now } from "scheduler";
import {
isFunction,
isNil,
isString,
isArray,
mapKeys,
startsWith,
upperFirst,
size,
keys,
forEach,
isPlainObject,
has,
lowerFirst,
pickBy,
flow,
} from "lodash/fp";
// Imports from the imperative lib
import { Map as OlMap, Object as OlObject } from "ol";
import { ReactOlFiber } from "./types";
import { catalogue, CatalogueKey, CatalogueItem, Catalogue } from "./catalogue";
export interface ObjectHash {
[name: string]: OlObject;
}
export type Detach<
ParentItem extends CatalogueItem,
ChildItem extends CatalogueItem
> = (
parent: Instance<ParentItem>,
child: Instance<ChildItem, ParentItem> // | TextInstance // But not used
) => void;
export type Attach<
ParentItem extends CatalogueItem,
ChildItem extends CatalogueItem
> =
| string
| ((
parent: Omit<Instance<ParentItem>, typeof MetaOlFiber>,
child: Omit<Instance<ChildItem, ParentItem>, typeof MetaOlFiber>,
parentInstance: Instance<ParentItem>,
childInstance: Instance<ChildItem, ParentItem>
) => Detach<ParentItem, ChildItem>);
// export type Attach =
// | string
// | ((
// container: OlObject,
// child: OlObject,
// parentInstance: Instance,
// childInstance: Instance
// ) => Detach);
export type Type = keyof ReactOlFiber.IntrinsicElements;
export type Props = ReactOlFiber.IntrinsicElements[Type];
const MetaOlFiber = Symbol("MetaOlFiber");
export type Instance<
SelfItem extends CatalogueItem = CatalogueItem,
ParentItem extends CatalogueItem = CatalogueItem
> = InstanceType<SelfItem["object"]> & {
[MetaOlFiber]: {
kind: SelfItem["kind"];
type: SelfItem["type"];
parent?: Instance<ParentItem>;
attach?: Attach<ParentItem, SelfItem>;
detach?: Detach<ParentItem, SelfItem>;
};
};
export type Container<Item extends CatalogueItem = CatalogueItem> =
Instance<Item>;
// export type OpaqueHandle = Fiber;
export type OpaqueHandle = any;
export type TextInstance = null;
export type HydratableInstance<
Item extends CatalogueItem = CatalogueItem,
ParentItem extends CatalogueItem = CatalogueItem
> = Instance<Item, ParentItem>;
export type PublicInstance<
Item extends CatalogueItem = CatalogueItem,
ParentItem extends CatalogueItem = CatalogueItem
> = Instance<Item, ParentItem>;
export type SuspenseInstance<
Item extends CatalogueItem = CatalogueItem,
ParentItem extends CatalogueItem = CatalogueItem
> = Instance<Item, ParentItem>;
export type HostContext = {};
export type UpdatePayload = boolean;
export type ChildSet = void;
export type TimeoutHandle = number;
export type NoTimeout = number;
// export type Reconciler = HostConfig<
// Type,
// Props,
// Container,
// Instance,
// TextInstance,
// HydratableInstance,
// PublicInstance,
// HostContext,
// UpdatePayload,
// ChildSet,
// TimeoutHandle,
// NoTimeout
// >;
const instances = new Map<HTMLElement, OlMap>();
const emptyObject = {};
// eslint-disable-next-line @typescript-eslint/no-empty-function
const noOp = () => {};
const error002 = (containerType = "", childType = "") =>
new Error(
`React-Openlayers-Fiber Error: Couldn't add this child to this container. You can specify how to attach this type of child ("${childType}") to this type of container ("${containerType}") using the "attach" props. If you think this should be done automatically, open an issue here https://github.com/labelflow/react-openlayers-fiber/issues/new?title=Support+${childType}+in+${containerType}&body=Support+${childType}+in+${containerType}`
);
const error001 = () =>
new Error(
`React-Openlayers-Fiber Error: Instance is null, is it a TextInstance ?`
);
/// ////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////////
// Util functions
/// ////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////////
const applyProp = (
olObject: OlObject,
olKey: string,
propValue: unknown
): void => {
const setterGeneric = olObject.set;
const keySetter = `set${upperFirst(olKey)}`;
const setterSpecificKey = (olObject as any)[keySetter];
if (isFunction(setterSpecificKey)) {
setterSpecificKey.bind(olObject)(propValue);
} else if (isFunction(setterGeneric)) {
setterGeneric.bind(olObject)(olKey, propValue);
} else if (has(olKey, olObject)) {
console.warn(
`React-Openlayers-Fiber Warning: Setting the property "${olKey}" brutally because there is no setter on the object`
);
console.warn(olObject);
// eslint-disable-next-line no-param-reassign
(olObject as any)[olKey] = propValue;
} else {
console.error(
`React-Openlayers-Fiber Error: Setting the property "${olKey}" very brutally because there is no setter on the object nor the object has this key... This is probably an error`
);
console.error(olObject);
// eslint-disable-next-line no-param-reassign
(olObject as any)[olKey] = propValue;
}
};
/**
*
* This code checks, for every given props,
* if the ol entity has a setter for the prop.
* If it has one, it sets the value to the ol object,
* but it only sets it if it changed from the previous props.
*
* @param olObject The ol object to update
* @param newProps The newProps potentially containing new changes
*/
const applyProps = (
olObject: OlObject,
newProps: Props,
oldProps: Props = {},
isNewInstance = false
): void => {
forEach((key) => {
if (isNewInstance && key.substr(0, 7) === "initial") {
const realKey = lowerFirst(key.substr(7));
const olKey = startsWith("_", realKey) ? realKey.substring(1) : realKey;
applyProp(olObject, olKey, newProps[key]);
} else if (
oldProps[key] !== newProps[key] &&
key.substr(0, 7) !== "initial"
) {
// For special cases (for example ol objects that have an option called "key"), we can add a "_" before.
if (key.substr(0, 2) === "on") {
const eventType = lowerFirst(key.substr(2).replace("_", ":"));
if (isFunction(oldProps[key])) {
olObject.un(
eventType as any, // Not enough typing in ol to be precise enough here
oldProps[key]
);
}
if (isFunction(newProps[key])) {
olObject.on(
eventType as any, // Not enough typing in ol to be precise enough here
newProps[key]
);
}
} else {
const olKey = startsWith("_", key) ? key.substring(1) : key;
applyProp(olObject, olKey, newProps[key]);
}
}
}, keys(newProps));
};
/**
* This function is a no-op, it's just a type guard
* It allows to force an instance to be considered by typescript
* as being of a type from the catalogue
* @param type
* @param instance
* @returns
*/
const getAs = <
A extends CatalogueItem,
B extends CatalogueItem,
K extends CatalogueKey
>(
_type: K,
instance: Instance<A, B>
): Instance<Catalogue[K], B> => {
return instance as unknown as Instance<Catalogue[K], B>;
};
const defaultAttach = <
ParentItem extends CatalogueItem,
ChildItem extends CatalogueItem
>(
parent: Instance<ParentItem>,
child: Instance<ChildItem, ParentItem>
): Detach<ParentItem, ChildItem> => {
if (!child) throw error001();
const { kind: parentKind } = parent[MetaOlFiber];
const { kind: childKind } = child[MetaOlFiber];
switch (parentKind) {
case "Map": {
switch (childKind) {
case "View":
getAs("olMap", parent).setView(getAs("olView", child));
return (newParent) => getAs("olMap", newParent).unset("view"); // Dubious at best
case "Layer":
getAs("olMap", parent).addLayer(getAs("olLayerLayer", child));
return (newParent, newChild) =>
getAs("olMap", newParent).removeLayer(
getAs("olLayerLayer", newChild)
);
case "Control":
getAs("olMap", parent).addControl(getAs("olControlControl", child));
return (newParent, newChild) =>
getAs("olMap", newParent).removeControl(
getAs("olControlControl", newChild)
);
case "Interaction":
getAs("olMap", parent).addInteraction(
getAs("olInteractionInteraction", child)
);
return (newParent, newChild) =>
getAs("olMap", newParent).removeInteraction(
getAs("olInteractionInteraction", newChild)
);
case "Overlay":
getAs("olMap", parent).addOverlay(getAs("olOverlay", child));
return (newParent, newChild) =>
getAs("olMap", newParent).removeOverlay(
getAs("olOverlay", newChild)
);
default:
throw error002(parentKind, childKind);
}
}
case "Layer": {
switch (childKind) {
case "Source":
getAs("olLayerLayer", parent).setSource(
// getAs("olSourceSource", child)
getAs("olSourceVector", child)
);
return (newParent, _newChild) =>
getAs("olLayerLayer", newParent).unset("source"); // Dubious at best
default:
throw error002(parentKind, childKind);
}
}
case "Source": {
switch (childKind) {
case "Feature":
getAs("olSourceVector", parent).addFeature(getAs("olFeature", child));
return (newParent, newChild) =>
getAs("olSourceVector", newParent).removeFeature(
getAs("olFeature", newChild)
); // Dubious at best
case "Source":
getAs("olSourceCluster", parent).setSource(
getAs("olSourceVector", child)
);
return (newParent, _newChild) =>
getAs("olSourceCluster", newParent).unset("source"); // Dubious at best
default:
throw error002(parentKind, childKind);
}
}
case "Feature": {
switch (childKind) {
case "Geom":
getAs("olFeature", parent).setGeometry(
// getAs("olGeomGeometry", child)
getAs("olGeomGeometryCollection", child)
);
return (newParent, _newChild) =>
getAs("olFeature", newParent).unset("geometry"); // Dubious at best
default:
throw error002(parentKind, childKind);
}
}
default:
throw error002(parentKind, childKind);
}
};
/// ////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////////
// Hot Config functions
/// ////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////////
const getPublicInstance = (
instance: Instance | TextInstance
): PublicInstance => {
if (!instance) throw error001();
return instance;
};
// Not used as of today, feel free to implement something cool instead of this
const getRootHostContext = (_rootContainerInstance: Container): HostContext =>
emptyObject;
// Not used as of today, feel free to implement something cool instead of this
const getChildHostContext = (
parentHostContext: HostContext,
type: Type,
_rootContainerInstance: Container
): HostContext => {
return typeof parentHostContext === "string"
? `${parentHostContext}.${type}`
: type;
};
const prepareForCommit = (
_containerInfo: Container
): Record<string, any> | null => {
return null;
};
const resetAfterCommit = (_containerInfo: Container): void => {};
const createInstance = <SelfItem extends CatalogueItem>(
type: SelfItem["type"] | "primitive" | "new",
props: Props,
_rootContainerInstance: Container | null,
_hostContext: HostContext | null,
_internalInstanceHandle: OpaqueHandle
): Instance<SelfItem> => {
let olObject;
let kind;
if (type === "primitive") {
// <primitive/> Elements like in react three fiber
const { object } = props as ReactOlFiber.IntrinsicElements["primitive"];
olObject = object;
kind = null;
} else if (type === "new") {
// <new/> Elements like in react three fiber
const { object: TheObjectClass, args } =
props as ReactOlFiber.IntrinsicElements["new"];
olObject = new TheObjectClass(...args);
kind = null;
} else {
// <olMap/> and all other similar elements from ol
const { args, constructFrom, attach, onUpdate, children, ...otherProps } =
props as ReactOlFiber.IntrinsicElementsArgsObject[keyof ReactOlFiber.IntrinsicElementsArgsObject];
const target = catalogue[type as CatalogueKey];
if (isNil(target)) {
// Not found
throw new Error(
`React-Openlayers-Fiber Error: ${type} is not exported by ol. Use extend to add it if needed.`
);
} else if (isNil(constructFrom)) {
// No constructFrom prop (most common)
const initialProps = flow(
pickBy((_value, propKey) => propKey.substr(0, 7) === "initial"),
mapKeys((propKey: string) => lowerFirst(propKey.substr(7)))
)(otherProps);
const objectProps = {
...initialProps,
...mapKeys(
(propKey: string) =>
startsWith("_", propKey) ? propKey.substring(1) : propKey,
pickBy(
(_value, propKey) => propKey.substr(0, 7) !== "initial",
otherProps
)
),
};
if (isNil(args)) {
// No args, simple ol object with a single options object arg
olObject = new (target.object as new (arg: any) => any)(objectProps);
kind = target.kind;
} else if (isArray(args)) {
// Args array
olObject = new (target.object as new (...args2: any[]) => any)(...args);
kind = target.kind;
} else {
// Single argument
olObject = new (target.object as new (arg: any) => any)({
...objectProps,
...args,
});
kind = target.kind;
}
} else if (isFunction(target.object[constructFrom])) {
// constructFrom prop is present
// The static field exists on the class
olObject = (
target.object[constructFrom] as unknown as (
...t: typeof args
) => Instance
)(...args);
kind = target.kind;
} else {
// Static constructForm does not exist
throw new Error(
`React-Openlayers-Fiber Error: ${constructFrom} is not a constructor for ${target}`
);
}
olObject[MetaOlFiber] = {
kind,
type,
attach,
};
applyProps(olObject, otherProps, {}, true);
}
return olObject;
};
const finalizeInitialChildren = (
_parentInstance: Instance,
_type: Type,
_props: Props,
_rootContainerInstance: Container,
_hostContext: HostContext
): boolean => {
return false;
};
const prepareUpdate = (
_instance: Instance,
_type: Type,
oldProps: Props,
newProps: Props,
_rootContainerInstance: Container,
_hostContext: HostContext
): null | UpdatePayload => {
const oldKeys = keys(oldProps);
const newKeys = keys(newProps);
// keys have same length
if (size(oldKeys) !== size(newKeys)) {
return true;
} // keys are the same
if (oldKeys.some((value, index) => newKeys[index] !== value)) {
return true;
}
return oldKeys
.filter((key) => key !== "children")
.some((key) => oldProps[key] !== newProps[key]);
};
const shouldSetTextContent = (_type: Type, _props: Props): boolean => {
return false;
};
// const shouldDeprioritizeSubtree = (_type: Type, _props: Props): boolean => {
// return false;
// };
const createTextInstance = (
_text: string,
_rootContainerInstance: Container,
_hostContext: HostContext,
_internalInstanceHandle: OpaqueHandle
): TextInstance => {
return null;
};
// const scheduleTimeout:
// | ((handler: TimerHandler, timeout: number) => TimeoutHandle | NoTimeout)
// | null = isFunction(setTimeout) ? setTimeout : null;
// const cancelTimeout: ((handle: TimeoutHandle | NoTimeout) => void) | null =
// isFunction(clearTimeout) ? clearTimeout : null;
const scheduleTimeout = setTimeout;
const cancelTimeout = clearTimeout;
const noTimeout: NoTimeout = -1;
const commitTextUpdate = (
_textInstance: TextInstance,
_oldText: string,
_newText: string
): void => {};
const commitMount = (
_instance: Instance,
_type: Type,
_newProps: Props,
_internalInstanceHandle: OpaqueHandle
): void => {};
const removeChild = <
ParentItem extends CatalogueItem,
ChildItem extends CatalogueItem
>(
parent: Instance<ParentItem>,
child: Instance<ChildItem, ParentItem> // | TextInstance | SuspenseInstance // FIXME one day
): void => {
if (!child) throw error001();
const { attach, detach } = child[MetaOlFiber];
if (isFunction(detach)) {
detach(parent, child);
} else if (isString(attach)) {
// eslint-disable-next-line no-param-reassign
(parent as Record<string, any>)[attach] = undefined;
// eslint-disable-next-line no-param-reassign
delete (parent as Record<string, any>)[attach];
} else {
throw new Error(
`React-Openlayers-Fiber Error: Couldn't remove this child from this container. You can specify how to detach this type of child ("${child.constructor.name}") from this type of container ("${parent.constructor.name}") using the "attach" props.`
);
}
};
const removeChildFromContainer = (
_container: Container,
child: Instance | TextInstance | SuspenseInstance
): void => {
// Probably not neded
// There can only be one map in its parent div
(child as OlMap).setTarget(undefined);
(child as OlMap).unset("target");
};
const appendChild = <
ParentItem extends CatalogueItem,
ChildItem extends CatalogueItem
>(
parent: Instance<ParentItem>,
child: Instance<ChildItem, ParentItem> | TextInstance
): void => {
if (!child) throw error001();
const { attach } = child[MetaOlFiber];
// eslint-disable-next-line no-param-reassign
child[MetaOlFiber].parent = parent;
if (isNil(attach)) {
// eslint-disable-next-line no-param-reassign
child[MetaOlFiber].detach = defaultAttach(parent, child);
} else if (isString(attach)) {
const setterGeneric = (parent as any)?.set;
const setterSpecific = (parent as any)?.[`set${upperFirst(attach)}`];
if (isFunction(setterSpecific)) {
// Example: source.setLayer(x)
setterSpecific.bind(parent)(child);
// eslint-disable-next-line no-param-reassign
child[MetaOlFiber].detach = (newParent, newChild) => {
const unsetterSpecific = (newParent as any)?.[
`unset${upperFirst(attach)}`
];
if (isFunction(unsetterSpecific)) {
unsetterSpecific.bind(newParent)(newChild);
} else {
setterSpecific.bind(newParent)(undefined);
}
};
} else if (isFunction(setterGeneric)) {
// Example: source.set("layer",x)
setterGeneric.bind(parent)(attach, child);
// eslint-disable-next-line no-param-reassign
child[MetaOlFiber].detach = (newParent, newChild) => {
const unsetterGeneric = (newParent as any)?.unset;
if (isFunction(unsetterGeneric)) {
unsetterGeneric.bind(newParent)(attach, newChild);
} else {
setterGeneric.bind(newParent)(attach, undefined);
}
};
} else {
// Example: source["layer"] = x
console.warn(
`React-Openlayers-Fiber Warning: Attaching the child ${attach} brutally because there is no setter on the object`
);
// eslint-disable-next-line no-param-reassign
(parent as Record<string, any>)[attach] = child;
// eslint-disable-next-line no-param-reassign
child[MetaOlFiber].detach = (newParent, _newChild) => {
// eslint-disable-next-line no-param-reassign
(newParent as Record<string, any>)[attach] = undefined;
// eslint-disable-next-line no-param-reassign
delete (newParent as Record<string, any>)[attach];
};
}
} else if (isFunction(attach)) {
// eslint-disable-next-line no-param-reassign
child[MetaOlFiber].detach = attach(parent, child, parent, child);
} else {
throw new Error(`React-Openlayers-Fiber Error: Unsupported "attach" type.`);
}
};
// Code from react-three-fiber : https://github.com/pmndrs/react-three-fiber/blob/master/src/renderer.tsx#L450
function switchInstance<
SelfItem extends CatalogueItem,
ParentItem extends CatalogueItem
>(
instance: Instance<SelfItem, ParentItem>,
type: SelfItem["type"] | "primitive" | "new",
newProps: any,
fiber: ReactReconciler.Fiber
) {
const { parent } = instance[MetaOlFiber];
const newInstance = createInstance(type, newProps, null, null, fiber);
if (isNil(parent)) {
if (type === "olMap") {
console.warn(
`React-Openlayers-Fiber Warning: Trying to switch olMap! This is poorly supported for now, it will only cause problems if you change the args of the olMap between renders.`
);
} else {
throw new Error(
`React-Openlayers-Fiber Error: Trying to switch instance which has no parent!`
);
}
} else {
removeChild(parent, instance);
appendChild(parent, newInstance as Instance<SelfItem, ParentItem>);
}
// This evil hack switches the react-internal fiber node
// https://github.com/facebook/react/issues/14983
// https://github.com/facebook/react/pull/15021
[fiber, fiber.alternate].forEach((theFiber: any) => {
if (theFiber !== null) {
// eslint-disable-next-line no-param-reassign
theFiber.stateNode = newInstance;
if (theFiber.ref) {
if (typeof theFiber.ref === "function") theFiber.ref(newInstance);
// eslint-disable-next-line no-param-reassign
else (theFiber.ref as ReactReconciler.RefObject).current = newInstance;
}
}
});
}
const commitUpdate = (
instance: Instance,
_updatePayload: UpdatePayload,
type: Type,
oldProps: Props,
newProps: Props,
internalInstanceHandle: OpaqueHandle
): void => {
const olObject = instance;
// This is a data object, let's extract critical information about it
const {
args: argsNew = [],
onUpdate,
children,
...restNew
} = newProps as any; // Had to add the "as any" after moving to ol 6.6.0, which uses its own type definitions
const { args: argsOld = [], ...restOld } = oldProps as any; // Had to add the "as any" after moving to ol 6.6.0, which uses its own type definitions;
// If it has new props or arguments, then it needs to be re-instanciated
let hasNewArgs = false;
if (isArray(argsNew)) {
if (!isArray(argsOld)) {
hasNewArgs = true;
} else {
hasNewArgs = argsNew.some((value: any, index: number) =>
isPlainObject(value)
? Object.entries(value).some(
([key, val]) => val !== argsOld[index][key]
)
: value !== argsOld[index]
);
}
} else if (isPlainObject(argsNew)) {
if (Array.isArray(argsOld)) {
hasNewArgs = true;
} else {
hasNewArgs = Object.entries(argsNew).some(
([key, val]) => val !== argsOld[key]
);
}
} else {
throw Error("Args should be an Array or an object");
}
if (hasNewArgs) {
// Next we create a new instance and append it again
switchInstance(instance, type, newProps, internalInstanceHandle);
} else {
// Otherwise just overwrite props
applyProps(olObject as OlObject, restNew, restOld, false);
}
if (typeof onUpdate === "function") {
onUpdate(olObject);
}
};
const insertInContainerBefore = (
container: Container,
child: Instance | TextInstance,
_beforeChild: Instance | TextInstance
): void => {
if (!child) throw error001();
// eslint-disable-next-line no-param-reassign
child[MetaOlFiber].parent = container;
// There can only be one map in its parent div
};
const resetTextContent = (_instance: Instance): void => {};
const insertBefore = (
parentInstance: Instance,
childInstance: Instance | TextInstance,
_beforeChild: Instance | TextInstance
): void => {
appendChild(parentInstance, childInstance);
};
const appendInitialChild = (
parentInstance: Instance,
childInstance: Instance | TextInstance
): void => {
return appendChild(parentInstance, childInstance);
};
const appendChildToContainer = (
_container: Container,
_child: Instance | TextInstance
): void => {
// This would link the map to it's parent div container.
// But this is already done in the Map component anyway so not needed here
};
const hideInstance = (instance: Instance) => {
const { kind } = instance[MetaOlFiber];
switch (kind) {
case "Layer": {
getAs("olLayerLayer", instance).setVisible(false);
break;
}
default: {
throw new Error(
"React-Openlayers-Fiber Error: Can't hide things that are not layers"
);
}
}
};
const unhideInstance = (instance: Instance, _props: Props) => {
const { kind } = instance[MetaOlFiber];
switch (kind) {
case "Layer": {
getAs("olLayerLayer", instance).setVisible(true);
break;
}
default: {
throw new Error(
"React-Openlayers-Fiber Error: Can't unhide things that are not layers"
);
}
}
};
const hideTextInstance = () => {
throw new Error(
"React-Openlayers-Fiber Error: Text is not allowed in the react-openlayers-fiber tree. You may have extraneous whitespace between components."
);
};
const unhideTextInstance = () => {
throw new Error(
"React-Openlayers-Fiber Error: Text is not allowed in the react-openlayers-fiber tree. You may have extraneous whitespace between components."
);
};
const reconciler = ReactReconciler<
Type,
Props,
Container,
Instance,
TextInstance,
SuspenseInstance,
HydratableInstance,
PublicInstance,
HostContext,
UpdatePayload,
ChildSet,
TimeoutHandle,
NoTimeout
>({
// List from ./node_modules/react-reconciler/cjs/react-reconciler-persistent.development.js
// -------------------
getPublicInstance,
getRootHostContext,
getChildHostContext,
prepareForCommit,
resetAfterCommit,
createInstance,
appendInitialChild,
finalizeInitialChildren,
prepareUpdate,
shouldSetTextContent,
// shouldDeprioritizeSubtree,
createTextInstance,
// -------------------
scheduleTimeout,
cancelTimeout,
noTimeout,
now,
// -------------------
isPrimaryRenderer: false,
// warnsIfNotActing: true,
supportsMutation: true,
supportsPersistence: false,
supportsHydration: false,
// -------------------
// DEPRECATED_mountResponderInstance: noOp,
// DEPRECATED_unmountResponderInstance: noOp,
// getFundamentalComponentInstance: noOp,
// mountFundamentalComponent: noOp,
// shouldUpdateFundamentalComponent: noOp,
// getInstanceFromNode: noOp,
// getInstanceFromScope: () => noOp,
// beforeRemoveInstance: noOp,
// -------------------
// Mutation
// (optional)
// -------------------
appendChild,
appendChildToContainer,
commitTextUpdate,
commitMount,
commitUpdate,
insertBefore,
insertInContainerBefore,
removeChild,
removeChildFromContainer,
resetTextContent,
hideInstance,
hideTextInstance,
unhideInstance,
unhideTextInstance,
preparePortalMount: noOp,
queueMicrotask,
// updateFundamentalComponent: noOp,
// unmountFundamentalComponent: noOp,
// // -------------------
// // Persistence
// // (optional)
// // -------------------
// cloneInstance?(
// instance: Instance,
// updatePayload: null | UpdatePayload,
// type: Type,
// oldProps: Props,
// newProps: Props,
// internalInstanceHandle: OpaqueHandle,
// keepChildren: boolean,
// recyclableInstance: Instance,
// ): Instance;
// createContainerChildSet?(container: Container): ChildSet;
// appendChildToContainerChildSet?(childSet: ChildSet, child: Instance | TextInstance): void;
// finalizeContainerChildren?(container: Container, newChildren: ChildSet): void;
// replaceContainerChildren?(container: Container, newChildren: ChildSet): void;
// cloneHiddenInstance,
// cloneHiddenTextInstance,
// cloneFundamentalInstance,
// // -------------------
// // Hydration
// // (optional)
// // -------------------
// canHydrateInstance?(instance: HydratableInstance, type: Type, props: Props): null | Instance;
// canHydrateTextInstance?(instance: HydratableInstance, text: string): null | TextInstance;
// canHydrateSuspenseInstance:noOp,
// isSuspenseInstancePending:noOp,
// isSuspenseInstanceFallback:noOp,
// registerSuspenseInstanceRetry:noOp,
// getNextHydratableSibling?(instance: Instance | TextInstance | HydratableInstance): null | HydratableInstance;
// getFirstHydratableChild?(parentInstance: Instance | Container): null | HydratableInstance;
// hydrateInstance?(
// instance: Instance,
// type: Type,
// props: Props,
// rootContainerInstance: Container,
// hostContext: HostContext,
// internalInstanceHandle: OpaqueHandle,
// ): null | UpdatePayload;
// hydrateTextInstance?(
// textInstance: TextInstance,
// text: string,
// internalInstanceHandle: OpaqueHandle,
// ): boolean;
// hydrateSuspenseInstance:noOp,
// getNextHydratableInstanceAfterSuspenseInstance:noOp,
// commitHydratedContainer:noOp,
// commitHydratedSuspenseInstance:noOp,
// clearSuspenseBoundary:noOp,
// clearSuspenseBoundaryFromContainer:noOp,
// didNotMatchHydratedContainerTextInstance?(
// parentContainer: Container,
// textInstance: TextInstance,
// text: string,
// ): void;
// didNotMatchHydratedTextInstance?(
// parentType: Type,
// parentProps: Props,
// parentInstance: Instance,
// textInstance: TextInstance,
// text: string,
// ): void;
// didNotHydrateContainerInstance?(parentContainer: Container, instance: Instance | TextInstance): void;
// didNotHydrateInstance?(
// parentType: Type,
// parentProps: Props,
// parentInstance: Instance,
// instance: Instance | TextInstance,
// ): void;
// didNotFindHydratableContainerInstance?(
// parentContainer: Container,
// type: Type,
// props: Props,
// ): void;
// didNotFindHydratableContainerTextInstance?(
// parentContainer: Container,
// text: string,
// ): void;
// didNotFindHydratableContainerSuspenseInstance:noOp,
// didNotFindHydratableInstance?(
// parentType: Type,
// parentProps: Props,
// parentInstance: Instance,
// type: Type,
// props: Props,
// ): void;
// didNotFindHydratableTextInstance?(
// parentType: Type,
// parentProps: Props,
// parentInstance: Instance,
// text: string,
// ): void;
// didNotFindHydratableSuspenseInstance:noOp,
// // -------------------
});
export function render(what: React.ReactNode, where: HTMLElement) {
let container;
if (instances.has(where)) {
container = instances.get(where);
} else {
container = reconciler.createContainer(
where as unknown as Container<CatalogueItem>, // FIXME
0,
false,
null
);
instances.set(where, container);
}
reconciler.updateContainer(what, container, null, () => null);
return reconciler.getPublicRootInstance(container);
} | the_stack |
import React from 'react';
import {
Typography,
Box,
Button,
CircularProgress,
} from 'lib-react-components';
import Link from 'next/link';
import clx from 'classnames';
import microFps from 'micro-fps';
import PropTypes from 'prop-types';
import * as gm from 'gammacv';
import LazyUpdate from '../../utils/lazy_update';
import { getMaxAvailableSize } from '../../utils/ratio';
import { getDeviceInfo, IDeviceInfo } from '../../utils/get_device_info';
import ParamsWrapper from './params';
import s from './index.module.sass';
interface IExamplePageProps {
data: {
op?: (input: gm.InputType, params?: {}, context?: any) => gm.Operation,
tick?: (frame: any, params: {}) => void,
init?: Function,
params?: TParams;
};
exampleName: string;
}
interface IExamplePageState {
isPlaying: boolean;
exampleInitialized: boolean,
canvas: {
width: number;
height: number;
};
params: TParamsValue;
error: string;
isCameraAccess: boolean;
isLoading: boolean;
showParams: boolean;
isParamsChanged: boolean;
device: IDeviceInfo;
}
export default class ExamplePage
extends React.Component<IExamplePageProps, IExamplePageState> {
timeout = null;
timeoutRequestAnimation = null;
lazyUpdate: LazyUpdate;
stream: gm.CaptureVideo;
sess: gm.Session;
op: gm.Operation;
imgInput: gm.Tensor;
outputTensor: gm.Tensor<gm.TensorDataView>;
frame: number;
opContext: Function;
loading: boolean;
params: TParamsValue;
canvasRef: React.RefObject<HTMLCanvasElement> = React.createRef();
refFps: React.RefObject<HTMLElement> = React.createRef();
refStopStartButton: React.RefObject<HTMLButtonElement> = React.createRef();
static contextTypes = {
intl: PropTypes.shape({
getText: PropTypes.func,
}),
};
constructor(props: IExamplePageProps) {
super(props);
this.params = this.handlePrepareParams();
const device = getDeviceInfo();
this.state = {
isPlaying: false,
exampleInitialized: false,
canvas: this.getSize(),
params: this.params,
error: '',
isCameraAccess: false,
isLoading: true,
showParams: device.type !== 'mobile',
isParamsChanged: false,
device,
};
this.lazyUpdate = new LazyUpdate(500, this.onResizeEnd);
// prepare params from state to set in gammacv op
this.init(props);
this.frame = 0;
this.loading = false;
const fpsTick = microFps((info) => {
if (this.refFps.current) {
this.refFps.current.innerHTML = info.fps.toFixed(0);
}
}, 3);
const tick = typeof props.data.tick === 'function' ? props.data.tick : this.tick;
this.tick = () => {
fpsTick();
const { exampleInitialized } = this.state;
if (!exampleInitialized) {
this.setState({
exampleInitialized: true,
});
}
// Read current in to the tensor
this.stream.getImageBuffer(this.imgInput);
if (
this.loading
&& !this.checkRerender(this.imgInput.data as Uint8Array)
) {
this.setState({
isLoading: false,
});
this.loading = false;
} else if (!this.loading && this.canvasRef.current) {
try {
tick.apply(this, [this.frame, {
canvas: this.canvasRef.current,
params: this.params,
operation: this.op,
session: this.sess,
input: this.imgInput,
output: this.outputTensor,
context: this.opContext,
}]);
} catch (error) {
this.stop();
this.setState({ error: 'NotSupported' });
}
this.frame += 1;
}
this.timeoutRequestAnimation = window.requestAnimationFrame(this.tick);
};
}
UNSAFE_componentWillMount() {
try {
navigator.mediaDevices.getUserMedia({ video: true })
.then(() => this.setState({ isCameraAccess: true }))
.catch(() => this.setState({ error: 'PermissionDenied' }));
} catch (error) {
this.setState({ error: 'PermissionDenied' });
}
}
componentDidMount() {
window.addEventListener('resize', this.onResize);
const { error } = this.state;
if (!error) {
this.start();
}
}
componentWillUnmount() {
window.removeEventListener('resize', this.onResize);
const { error } = this.state;
if (!error) {
this.stop();
}
}
handlePrepareParams() {
/**
* this method need to prepare incoming params from format
* { nameExample : { nameParam1: { name, type, min, max, step, default }, nameParam2... }}
* to format { nameExample: { nameParam1: value, nameParam2: value...} }
*/
const resultPreference = {};
const { data } = this.props;
const { params } = data;
if (!params) {
return resultPreference;
}
const blockNames = Object.keys(params);
for (let i = 0; i < blockNames.length; i += 1) {
const blockName = blockNames[i];
const paramBlock = params[blockName];
const paramNames = Object.keys(paramBlock);
for (let j = 0; j < paramNames.length; j += 1) {
const paramName = paramNames[j];
const nameBlock = paramBlock[paramName];
if (paramName !== 'name') {
let paramValue: string | number = (nameBlock as ISlideParamProps).default;
if (typeof paramValue !== 'number') {
paramValue = (nameBlock as ISelectParamProps).values[0].value;
}
resultPreference[blockName] = {
...resultPreference[blockName],
[paramName]: paramValue,
};
}
}
}
return resultPreference;
}
onResize = () => {
const { error } = this.state;
const device = getDeviceInfo();
this.setState({
device,
showParams: device.type !== 'mobile',
});
if (!error) {
this.lazyUpdate.activate();
}
};
onResizeEnd = () => {
this.stop(false);
this.setState({ canvas: this.getSize() }, () => {
this.init(this.props);
this.start();
});
};
getSize = () => {
const { type, width, height } = getDeviceInfo();
if (type === 'mobile') {
const res = getMaxAvailableSize(
width / (height - 60),
Math.min(width, 600),
Math.min(height, 600),
);
return {
width: Math.floor(res.width),
height: Math.floor(res.height),
};
}
return {
width: 500,
height: 384,
};
};
init = (props: IExamplePageProps) => {
const { canvas } = this.state;
const { width, height } = canvas;
try {
// initialize WebRTC stream and session for runing operations on GPU
this.imgInput = new gm.Tensor('uint8', [height, width, 4]);
this.sess = new gm.Session();
this.stream = new gm.CaptureVideo(width, height);
if (props.data.init) {
this.opContext = props.data.init(this.op, this.sess, this.params);
}
this.op = props.data.op(this.imgInput, this.params, this.opContext);
if (!(this.op instanceof gm.Operation)) {
throw new Error(`Error in ${props.exampleName} example: function <op> must return Operation`);
}
// initialize graph
this.sess.init(this.op);
this.outputTensor = gm.tensorFrom(this.op);
} catch (err) {
this.setState({ error: 'NotSupported' });
}
};
tick = (frame: number) => {
// final run operation on GPU and then write result in to output tensor
this.sess.runOp(this.op, frame, this.outputTensor);
if (this.canvasRef.current) {
// draw result into canvas
gm.canvasFromTensor(this.canvasRef.current, this.outputTensor);
}
};
start = () => {
// start capturing a camera and run loop
try {
this.stream.start().catch(() => {
this.stop();
this.setState({
error: 'PermissionDenied',
});
});
this.timeoutRequestAnimation = window.requestAnimationFrame(this.tick);
this.setState({
isPlaying: true,
});
if (
!this.loading
&& this.checkRerender(this.stream.getImageBuffer('uint8') as Uint8Array)
) {
this.setState({
isLoading: true,
});
this.loading = true;
}
} catch (error) {
this.stop();
this.setState({
error: 'NotSupported',
});
}
};
stop = (destroy = true) => {
if (this.stream) {
this.stream.stop();
}
const { isPlaying } = this.state;
if (destroy && isPlaying) {
this.sess.destroy();
}
window.cancelAnimationFrame(this.timeoutRequestAnimation);
this.setState({ isPlaying: false });
};
checkRerender = (arr: Uint8Array) => {
let dark = true;
for (let i = 0; i < arr.length; i += 16) {
if (arr[i] !== 0) {
dark = false;
}
}
return dark;
};
onChangeParams = () => {
const { params } = this.state;
this.params = params;
this.stop(false);
this.init(this.props);
this.start();
};
handleStartStop = () => {
const { isPlaying, params } = this.state;
if (isPlaying) {
this.stop(false);
} else {
this.params = params;
this.start();
}
};
trottleUpdate = () => {
clearTimeout(this.timeout);
this.timeout = setTimeout(() => {
this.onChangeParams();
}, 1000);
};
handleChangeState = (paramName: string, key: string, value: string | number) => {
this.setState((prevState) => {
const { params } = prevState;
return {
params: {
...params,
[paramName]: {
...params[paramName],
[key]: value,
},
},
isParamsChanged: true,
};
});
const { data } = this.props;
const { type } = data.params[paramName][key];
// need to run trottle or live update param
if (type === 'constant') {
this.trottleUpdate();
} else {
const { params } = this.state;
const { operation } = this.sess as any;
const sessOperations = Object.keys(operation);
this.params = params;
for (let i = 0; i < sessOperations.length; i += 1) {
const sessOperationName = sessOperations[i];
if (operation[sessOperationName].uniform) {
const sessUniforms = Object.keys(operation[sessOperationName].uniform);
for (let j = 0; j < sessUniforms.length; j += 1) {
const sessUniformName = sessUniforms[j];
if (sessUniformName === key) {
operation[sessOperationName].uniform[sessUniformName].set(value);
}
}
}
}
}
};
handleReset = () => {
this.setState({
params: this.handlePrepareParams(),
isParamsChanged: false,
}, this.onChangeParams);
};
renderStartStopButton() {
const { isPlaying } = this.state;
const icon = isPlaying
? <img src="/static/images/pause_icon.svg" alt="Pause icon" />
: <img src="/static/images/play_icon.svg" alt="Play icon" />;
return (
<span
ref={this.refStopStartButton}
className={s.stop_play_button}
>
<div
className={clx(s.stop_play_icon, {
[s.m_visible]: !isPlaying,
})}
>
{icon}
</div>
</span>
);
}
renderNoAccessCase = () => {
const { device } = this.state;
const { intl } = this.context;
const isMobile = device.type === 'mobile';
return (
<>
<div className={s.error_text}>
<Typography
type={isMobile ? 'h4' : 'h3'}
color="black"
align="center"
>
{intl.getText('example.noAccess')}
</Typography>
</div>
<Button
href={window.location.href}
size="large"
color="primary"
className={s.error_button}
>
{intl.getText('example.tryAgain')}
</Button>
</>
);
};
renderNotSupportedCase = () => {
const { device } = this.state;
const { intl } = this.context;
const isMobile = device.type === 'mobile';
return (
<>
<div className={s.error_text}>
<Typography
type={isMobile ? 'h4' : 'h3'}
color="black"
align="center"
>
{intl.getText('example.dontSupport')}
</Typography>
</div>
<Link href="/examples">
<Button
size="large"
color="primary"
className={s.error_button}
>
{intl.getText('example.tryAnother')}
</Button>
</Link>
</>
);
};
render() {
const { exampleName, data } = this.props;
const {
error,
isCameraAccess,
canvas,
params,
isPlaying,
isLoading,
showParams,
isParamsChanged,
device,
} = this.state;
const { intl } = this.context;
const isMobile = device.type === 'mobile';
if (!error && !isCameraAccess) {
return (
<div className={s.root_example}>
<CircularProgress
size={40}
className={s.loading}
/>
</div>
);
}
if (isMobile && device.height < device.width) {
return (
<Box
fill="primary"
className={s.to_portrait}
>
<Typography
type="h4"
color="light_grey"
>
{intl.getText('example.toPortrait')}
</Typography>
</Box>
);
}
if (error) {
const icon = <img src="/static/images/error_icon.svg" alt="Error icon" />;
return (
<div className={s.root_example}>
<div className={s.error_wrapper}>
<div className={s.error_icon}>
{icon}
</div>
{error === 'NotSupported'
? this.renderNotSupportedCase()
: this.renderNoAccessCase()}
</div>
</div>
);
}
const showFps = isMobile ? !showParams : true;
return (
<div className={s.root_example}>
<div className={s.example_wrapper}>
{showFps && (
<div className={s.top_title_wrapper}>
<Typography
type={isMobile ? 'h4' : 'h3'}
color="black"
className={s.top_title_text}
>
{intl.getText('operations', undefined, exampleName)}
</Typography>
<Typography
type={isMobile ? 'h4' : 'h3'}
color="grey"
className={clx({
[s.top_title_fps]: true,
[s.hidden_fps]: !isPlaying,
})}
>
FPS:
{' '}
<span ref={this.refFps} />
</Typography>
</div>
)}
<div className={s.content_wrapper}>
<Box
borderRadius={isMobile ? 0 : 8}
stroke={isMobile ? '' : 'grey_2'}
fill={isMobile ? '' : 'light_grey'}
className={s.canvas_wrapper}
>
<canvas
ref={this.canvasRef}
width={canvas.width}
height={canvas.height}
className={s.canvas}
/>
<div
className={clx({
[s.loading_wrapper]: true,
[s.show_loading]: isLoading,
})}
>
<CircularProgress
size={40}
className={s.loading}
/>
</div>
<button
type="button"
aria-label="Overlay"
onClick={this.handleStartStop}
onMouseEnter={() => { this.refStopStartButton.current.style.visibility = 'visible'; }}
onMouseLeave={() => { this.refStopStartButton.current.style.visibility = 'hidden'; }}
className={clx(s.canvas_overlay, 'fill_black')}
/>
{this.renderStartStopButton()}
</Box>
{isMobile && data.params && (
<Button
onClick={() => this.setState({ showParams: !showParams })}
bgType="clear"
size="small"
className={s.show_params}
>
<div className={s.show_params_icon}>
{showParams ? (
<img src="/static/images/cross_icon.svg" alt="Cross icon" className={s.cross_icon} />
) : (
<img src="/static/images/params_icon.svg" alt="Params icon" className={s.params_icon} />
)}
</div>
<Typography type="b1" color="light_grey" className={s.show_params_text}>
{showParams
? intl.getText('example.close')
: intl.getText('example.params')}
</Typography>
</Button>
)}
{showParams && (
<ParamsWrapper
params={data.params}
onReset={this.handleReset}
handleChangeState={this.handleChangeState}
paramsValue={{ ...params }}
isMobile={isMobile}
isParamsChanged={isParamsChanged}
/>
)}
</div>
</div>
</div>
);
}
} | the_stack |
import BitmapData from "openfl/display/BitmapData";
import Matrix from "openfl/geom/Matrix";
import Matrix3D from "openfl/geom/Matrix3D";
import Point from "openfl/geom/Point";
import Rectangle from "openfl/geom/Rectangle";
import Vector3D from "openfl/geom/Vector3D";
import FragmentFilter from "./../filters/FragmentFilter";
import Painter from "./../rendering/Painter";
import DisplayObjectContainer from "./DisplayObjectContainer";
import Stage from "./Stage";
import EventDispatcher from "./../events/EventDispatcher";
declare namespace starling.display
{
/** Dispatched when an object is added to a parent. */
// @:meta(Event(name="added", type="starling.events.Event"))
/** Dispatched when an object is connected to the stage (directly or indirectly). */
// @:meta(Event(name="addedToStage", type="starling.events.Event"))
/** Dispatched when an object is removed from its parent. */
// @:meta(Event(name="removed", type="starling.events.Event"))
/** Dispatched when an object is removed from the stage and won't be rendered any longer. */
// @:meta(Event(name="removedFromStage", type="starling.events.Event"))
/** Dispatched once every frame on every object that is connected to the stage. */
// @:meta(Event(name="enterFrame", type="starling.events.EnterFrameEvent"))
/** Dispatched when an object is touched. Bubbles. */
// @:meta(Event(name="touch", type="starling.events.TouchEvent"))
/** Dispatched when a key on the keyboard is released. */
// @:meta(Event(name="keyUp", type="starling.events.KeyboardEvent"))
/** Dispatched when a key on the keyboard is pressed. */
// @:meta(Event(name="keyDown", type="starling.events.KeyboardEvent"))
/**
* The DisplayObject class is the base class for all objects that are rendered on the
* screen.
*
* <p><strong>The Display Tree</strong></p>
*
* <p>In Starling, all displayable objects are organized in a display tree. Only objects that
* are part of the display tree will be displayed (rendered).</p>
*
* <p>The display tree consists of leaf nodes (Image, Quad) that will be rendered directly to
* the screen, and of container nodes (subclasses of "DisplayObjectContainer", like "Sprite").
* A container is simply a display object that has child nodes - which can, again, be either
* leaf nodes or other containers.</p>
*
* <p>At the base of the display tree, there is the Stage, which is a container, too. To create
* a Starling application, you create a custom Sprite subclass, and Starling will add an
* instance of this class to the stage.</p>
*
* <p>A display object has properties that define its position in relation to its parent
* (x, y), as well as its rotation and scaling factors (scaleX, scaleY). Use the
* <code>alpha</code> and <code>visible</code> properties to make an object translucent or
* invisible.</p>
*
* <p>Every display object may be the target of touch events. If you don't want an object to be
* touchable, you can disable the "touchable" property. When it's disabled, neither the object
* nor its children will receive any more touch events.</p>
*
* <strong>Transforming coordinates</strong>
*
* <p>Within the display tree, each object has its own local coordinate system. If you rotate
* a container, you rotate that coordinate system - and thus all the children of the
* container.</p>
*
* <p>Sometimes you need to know where a certain point lies relative to another coordinate
* system. That's the purpose of the method <code>getTransformationMatrix</code>. It will
* create a matrix that represents the transformation of a point in one coordinate system to
* another.</p>
*
* <strong>Customization</strong>
*
* <p>DisplayObject is an abstract class, which means you cannot instantiate it directly,
* but have to use one of its many subclasses instead. For leaf nodes, this is typically
* 'Mesh' or its subclasses 'Quad' and 'Image'. To customize rendering of these objects,
* you can use fragment filters (via the <code>filter</code>-property on 'DisplayObject')
* or mesh styles (via the <code>style</code>-property on 'Mesh'). Look at the respective
* class documentation for more information.</p>
*
* @see DisplayObjectContainer
* @see Sprite
* @see Stage
* @see Mesh
* @see starling.filters.FragmentFilter
* @see starling.styles.MeshStyle
*/
export class DisplayObject extends EventDispatcher
{
/** Disposes all resources of the display object.
* GPU buffers are released, event listeners are removed, filters and masks are disposed. */
public dispose():void;
/** Removes the object from its parent, if it has one, and optionally disposes it. */
public removeFromParent(dispose?:boolean):void;
/** Creates a matrix that represents the transformation from the local coordinate system
* to another. If you pass an <code>out</code>-matrix, the result will be stored in this matrix
* instead of creating a new object. */
public getTransformationMatrix(targetSpace:DisplayObject,
out?:Matrix):Matrix;
/** Returns a rectangle that completely encloses the object as it appears in another
* coordinate system. If you pass an <code>out</code>-rectangle, the result will be stored in this
* rectangle instead of creating a new object. */
public getBounds(targetSpace:DisplayObject, out?:Rectangle):Rectangle;
/** Returns the object that is found topmost beneath a point in local coordinates, or nil
* if the test fails. Untouchable and invisible objects will cause the test to fail. */
public hitTest(localPoint:Point):DisplayObject;
/** Checks if a certain point is inside the display object's mask. If there is no mask,
* this method always returns <code>true</code> (because having no mask is equivalent
* to having one that's infinitely big). */
public hitTestMask(localPoint:Point):boolean;
/** Transforms a point from the local coordinate system to global (stage) coordinates.
* If you pass an <code>out</code>-point, the result will be stored in this point instead of
* creating a new object. */
public localToGlobal(localPoint:Point, out?:Point):Point;
/** Transforms a point from global (stage) coordinates to the local coordinate system.
* If you pass an <code>out</code>-point, the result will be stored in this point instead of
* creating a new object. */
public globalToLocal(globalPoint:Point, out?:Point):Point;
/** Renders the display object with the help of a painter object. Never call this method
* directly, except from within another render method.
*
* @param painter Captures the current render state and provides utility functions
* for rendering.
*/
public render(painter:Painter):void;
/** Moves the pivot point to a certain position within the local coordinate system
* of the object. If you pass no arguments, it will be centered. */
public alignPivot(horizontalAlign?:string,
verticalAlign?:string):void;
/** Draws the object into a BitmapData object.
*
* <p>This is achieved by drawing the object into the back buffer and then copying the
* pixels of the back buffer into a texture. This also means that the returned bitmap
* data cannot be bigger than the current viewPort.</p>
*
* @param out If you pass null, the object will be created for you.
* If you pass a BitmapData object, it should have the size of the
* object bounds, multiplied by the current contentScaleFactor.
* @param color The RGB color value with which the bitmap will be initialized.
* @param alpha The alpha value with which the bitmap will be initialized.
*/
public drawToBitmapData(out?:BitmapData,
color?:number, alpha?:number):BitmapData;
// 3D transformation
/** Creates a matrix that represents the transformation from the local coordinate system
* to another. This method supports three dimensional objects created via 'Sprite3D'.
* If you pass an <code>out</code>-matrix, the result will be stored in this matrix
* instead of creating a new object. */
public getTransformationMatrix3D(targetSpace:DisplayObject,
out?:Matrix3D):Matrix3D;
/** Transforms a 3D point from the local coordinate system to global (stage) coordinates.
* This is achieved by projecting the 3D point onto the (2D) view plane.
*
* <p>If you pass an <code>out</code>-point, the result will be stored in this point instead of
* creating a new object.</p> */
public local3DToGlobal(localPoint:Vector3D, out?:Point):Point;
/** Transforms a point from global (stage) coordinates to the 3D local coordinate system.
* If you pass an <code>out</code>-vector, the result will be stored in this point instead of
* creating a new object. */
public globalToLocal3D(globalPoint:Point, out?:Vector3D):Vector3D;
// render cache
/** Forces the object to be redrawn in the next frame.
* This will prevent the object to be drawn from the render cache.
*
* <p>This method is called every time the object changes in any way. When creating
* custom mesh styles or any other custom rendering code, call this method if the object
* needs to be redrawn.</p>
*
* <p>If the object needs to be redrawn just because it does not support the render cache,
* call <code>painter.excludeFromCache()</code> in the object's render method instead.
* That way, Starling's <code>skipUnchangedFrames</code> policy won't be disrupted.</p>
*/
public setRequiresRedraw():void;
/** Indicates if the object needs to be redrawn in the upcoming frame, i.e. if it has
* changed its location relative to the stage or some other aspect of its appearance
* since it was last rendered. */
public readonly requiresRedraw:boolean;
protected get_requiresRedraw():boolean;
// stage event handling
/** @protected */
// public /*override*/ dispatchEvent(event:Event):void;
// enter frame event optimization
// To avoid looping through the complete display tree each frame to find out who's
// listening to ENTER_FRAME events, we manage a list of them manually in the Stage class.
// We need to take care that (a) it must be dispatched only when the object is
// part of the stage, (b) it must not cause memory leaks when the user forgets to call
// dispose and (c) there might be multiple listeners for this event.
/** @inheritDoc */
public /*override*/ addEventListener(type:string, listener:Function):void;
/** @inheritDoc */
public /*override*/ removeEventListener(type:string, listener:Function):void;
/** @inheritDoc */
public /*override*/ removeEventListeners(type?:string):void;
// properties
/** The transformation matrix of the object relative to its parent.
*
* <p>If you assign a custom transformation matrix, Starling will try to figure out
* suitable values for <code>x, y, scaleX, scaleY,</code> and <code>rotation</code>.
* However, if the matrix was created in a different way, this might not be possible.
* In that case, Starling will apply the matrix, but not update the corresponding
* properties.</p>
*
* <p>CAUTION: not a copy, but the actual object!</p> */
public transformationMatrix:Matrix;
protected get_transformationMatrix():Matrix;
protected set_transformationMatrix(matrix:Matrix):Matrix;
/** The 3D transformation matrix of the object relative to its parent.
*
* <p>For 2D objects, this property returns just a 3D version of the 2D transformation
* matrix. Only the 'Sprite3D' class supports real 3D transformations.</p>
*
* <p>CAUTION: not a copy, but the actual object!</p> */
public readonly transformationMatrix3D:Matrix3D;
protected get_transformationMatrix3D():Matrix3D;
/** Indicates if this object or any of its parents is a 'Sprite3D' object. */
public readonly is3D:boolean;
protected get_is3D():boolean;
/** Indicates if the mouse cursor should transform into a hand while it's over the sprite.
* @default false */
public useHandCursor:boolean;
protected get_useHandCursor():boolean;
protected set_useHandCursor(value:boolean):boolean;
/** The bounds of the object relative to the local coordinates of the parent. */
public readonly bounds:Rectangle;
protected get_bounds():Rectangle;
/** The width of the object in pixels.
* Note that for objects in a 3D space (connected to a Sprite3D), this value might not
* be accurate until the object is part of the display list. */
public width:number;
protected get_width():number;
protected set_width(value:number):number;
/** The height of the object in pixels.
* Note that for objects in a 3D space (connected to a Sprite3D), this value might not
* be accurate until the object is part of the display list. */
public height:number;
protected get_height():number;
protected set_height(value:number):number;
/** The x coordinate of the object relative to the local coordinates of the parent. */
public x:number;
protected get_x():number;
protected set_x(value:number):number;
/** The y coordinate of the object relative to the local coordinates of the parent. */
public y:number;
protected get_y():number;
protected set_y(value:number):number;
/** The x coordinate of the object's origin in its own coordinate space (default: 0). */
public pivotX:number;
protected get_pivotX():number;
protected set_pivotX(value:number):number;
/** The y coordinate of the object's origin in its own coordinate space (default: 0). */
public pivotY:number;
protected get_pivotY():number;
protected set_pivotY(value:number):number;
/** The horizontal scale factor. '1' means no scale, negative values flip the object.
* @default 1 */
public scaleX:number;
protected get_scaleX():number;
protected set_scaleX(value:number):number;
/** The vertical scale factor. '1' means no scale, negative values flip the object.
* @default 1 */
public scaleY:number;
protected get_scaleY():number;
protected set_scaleY(value:number):number;
/** Sets both 'scaleX' and 'scaleY' to the same value. The getter simply returns the
* value of 'scaleX' (even if the scaling values are different). @default 1 */
public scale:number;
protected get_scale():number;
protected set_scale(value:number):number;
/** The horizontal skew angle in radians. */
public skewX:number;
protected get_skewX():number;
protected set_skewX(value:number):number;
/** The vertical skew angle in radians. */
public skewY:number;
protected get_skewY():number;
protected set_skewY(value:number):number;
/** The rotation of the object in radians. (In Starling, all angles are measured
* in radians.) */
public rotation:number;
protected get_rotation():number;
protected set_rotation(value:number):number;
/** The opacity of the object. 0 = transparent, 1 = opaque. @default 1 */
public alpha:number;
protected get_alpha():number;
protected set_alpha(value:number):number;
/** The visibility of the object. An invisible object will be untouchable. */
public visible:boolean;
protected get_visible():boolean;
protected set_visible(value:boolean):boolean;
/** Indicates if this object (and its children) will receive touch events. */
public touchable:boolean;
protected get_touchable():boolean;
protected set_touchable(value:boolean):boolean;
/** The blend mode determines how the object is blended with the objects underneath.
* @default auto
* @see starling.display.BlendMode */
public blendMode:string;
protected get_blendMode():string;
protected set_blendMode(value:string):string;
/** The name of the display object (default: null). Used by 'getChildByName()' of
* display object containers. */
public name:string;
protected get_name():string;
protected set_name(value:string):string;
/** The filter that is attached to the display object. The <code>starling.filters</code>
* package contains several classes that define specific filters you can use. To combine
* several filters, assign an instance of the <code>FilterChain</code> class; to remove
* all filters, assign <code>null</code>.
*
* <p>Beware that a filter instance may only be used on one object at a time! Furthermore,
* when you remove or replace a filter, it is NOT disposed automatically (since you might
* want to reuse it on a different object).</p>
*
* @default null
* @see starling.filters.FragmentFilter
* @see starling.filters.FilterChain
*/
public filter:FragmentFilter;
protected get_filter():FragmentFilter;
protected set_filter(value:FragmentFilter):FragmentFilter;
/** The display object that acts as a mask for the current object.
* Assign <code>null</code> to remove it.
*
* <p>A pixel of the masked display object will only be drawn if it is within one of the
* mask's polygons. Texture pixels and alpha values of the mask are not taken into
* account. The mask object itself is never visible.</p>
*
* <p>If the mask is part of the display list, masking will occur at exactly the
* location it occupies on the stage. If it is not, the mask will be placed in the local
* coordinate system of the target object (as if it was one of its children).</p>
*
* <p>For rectangular masks, you can use simple quads; for other forms (like circles
* or arbitrary shapes) it is recommended to use a 'Canvas' instance.</p>
*
* <p><strong>Note:</strong> a mask will typically cause at least two additional draw
* calls: one to draw the mask to the stencil buffer and one to erase it. However, if the
* mask object is an instance of <code>starling.display.Quad</code> and is aligned
* parallel to the stage axes, rendering will be optimized: instead of using the
* stencil buffer, the object will be clipped using the scissor rectangle. That's
* faster and reduces the number of draw calls, so make use of this when possible.</p>
*
* <p><strong>Note:</strong> AIR apps require the <code>depthAndStencil</code> node
* in the application descriptor XMLs to be enabled! Otherwise, stencil masking won't
* work.</p>
*
* @see Canvas
* @default null
*/
public mask:DisplayObject;
protected get_mask():DisplayObject;
protected set_mask(value:DisplayObject):DisplayObject;
/** Indicates if the masked region of this object is set to be inverted.*/
public maskInverted:boolean;
protected get_maskInverted():boolean;
protected set_maskInverted(value:boolean):boolean;
/** The display object container that contains this display object. */
public readonly parent:DisplayObjectContainer;
protected get_parent():DisplayObjectContainer;
/** The topmost object in the display tree the object is part of. */
public readonly base:DisplayObject;
protected get_base():DisplayObject;
/** The root object the display object is connected to (i.e. an instance of the class
* that was passed to the Starling constructor), or null if the object is not connected
* to the stage. */
public readonly root:DisplayObject;
protected get_root():DisplayObject;
/** The stage the display object is connected to, or null if it is not connected
* to the stage. */
public readonly stage:Stage;
protected get_stage():Stage;
}
}
export default starling.display.DisplayObject; | the_stack |
import { Button, Dropdown, Popconfirm } from 'antd'
import { mount } from 'enzyme'
import { createBrowserHistory } from 'history'
import mockAxios from 'jest-mock-axios'
import _ from 'lodash'
import queryString from 'query-string'
import React from 'react'
import HtModalForm from '~/components/ModalForm'
import HtTable, {
tableRowModalFormAlias,
tableSelectionRowKeysAlias,
transformParams,
} from '~/components/Table'
import {
TableColumn,
TableComponentProps,
TableComponentState,
} from '~/components/Table/interfacce'
import { Hetu } from '~/Hetu'
import { _resolveAction } from '~/utils/actions'
jest.mock('~/utils/actions')
const history = createBrowserHistory()
const alias = '$$HtListTestTable'
const url = '/api/list/asdfasdf'
const method = 'get'
const fields: any[] = []
const pageSize = 2
const columns = [
{
title: 'id',
dataIndex: 'id',
width: 50,
},
{
title: 'banner',
dataIndex: 'imageUrl',
width: 60,
renderType: 'img',
},
{
title: '预览链接',
dataIndex: 'preview',
width: 80,
renderType: 'a',
},
{
title: '标签',
dataIndex: 'tags',
width: 100,
},
]
const cols = 2
const labelCol = { span: 12 }
const wrapperCol = { span: 12 }
const buttons = ['submit', 'reset']
const isAutoSubmit = true
const columnsSetting = true
const actionColumn = {
width: 120,
renderType: 'operations',
operations: [
{
text: '查看',
actionType: 'open',
url: 'http://test-hetu.company.com',
},
{
text: '删除',
actionType: 'xhr',
url: '/api/xxx/delete',
},
],
operations2: [
{
text: '编辑',
url: '/api/form/update',
width: 600,
fields: [
{
field: 'imageUrl',
title: 'banner',
},
{
field: 'tags',
title: '标签',
},
],
},
],
}
const scroll = {
x: 2000,
}
const uniqueKey = 'idddd'
const selections = [
{
type: 'HtButton',
props: {
href: "${ '/api/list/download?ids=' + $$tableSelectionRowKeys.join() }",
text: '批量下载',
},
children: [],
},
{
type: 'HtModalForm',
props: {
url: '/api/form/update',
fields: [
{
field: 'ids',
title: '批量id',
defaultValue: '${ $$tableSelectionRowKeys }',
required: true,
disabled: true,
},
{
field: 'name',
title: '姓名',
},
{
field: 'age',
title: '年龄',
type: 'InputNumber',
},
],
title: '弹框表单',
triggerButtonText: '批量编辑',
},
},
]
const elementConfig = {
type: 'HtList',
props: {
alias,
url,
method,
fields,
cols,
labelCol,
wrapperCol,
buttons,
isAutoSubmit,
pageSize,
columns,
actionColumn,
scroll,
uniqueKey,
selections,
columnsSetting,
},
children: [],
}
const wrapper = mount(<Hetu elementConfig={elementConfig} history={history} />)
const WrapperTable = wrapper
.find<React.Component<TableComponentProps, TableComponentState>>(HtTable)
.at(0)
const WrapperTableInstance = WrapperTable.instance()
describe('正确的props', () => {
it('props正确传递给HtTable', () => {
expect(WrapperTable.prop('uniqueKey')).toEqual(uniqueKey)
expect(WrapperTable.prop('pagination')).toHaveProperty('pageSize', pageSize)
expect(WrapperTable.prop('dataSource')).toEqual([])
expect(WrapperTable.prop('selections')).toHaveLength(selections.length)
expect(WrapperTable.prop('scroll')).toEqual(scroll)
expect(WrapperTable.prop('columns')).toEqual(columns)
expect(WrapperTable.prop('actionColumn')).toEqual(actionColumn)
expect(WrapperTable.prop('columnsSetting')).toEqual(columnsSetting)
})
})
describe('正确的方法', () => {
const selectedBtnPath = 'actionColumn.operations2[0]'
// @ts-ignore
WrapperTableInstance.selectedBtnPath = selectedBtnPath
const {
pagestate,
uniqueKey,
onDataSourceChange,
} = WrapperTableInstance.props
// @ts-ignore
WrapperTableInstance.renderModalForm(pagestate, uniqueKey, onDataSourceChange)
test('setPageLoading', () => {
expect(WrapperTableInstance.state.isPageLoading).toEqual(false)
// @ts-ignore
WrapperTableInstance.setPageLoading(true)
expect(WrapperTableInstance.state.isPageLoading).toEqual(true)
// @ts-ignore
WrapperTableInstance.setPageLoading(false)
expect(WrapperTableInstance.state.isPageLoading).toEqual(false)
})
test('onTableBtnClick actionType=jump', () => {
const item1 = {
text: '跳转',
url: 'testjumpsadkfhaskjdf',
transform: (v: any) => ({ ...v, xyz: 1235 }),
}
const row1 = {
id: 'test111',
name: 'xxxsdafs',
}
// @ts-ignore
WrapperTableInstance.onTableBtnClick(item1, row1)
const query = transformParams(uniqueKey, item1.transform, row1)
let search = queryString.stringify(query)
const jumpUrl = `${item1.url}?${search}`
expect(_resolveAction).toBeCalledWith(
'redirectTo',
jumpUrl,
WrapperTableInstance.props.pagestate
)
})
test('onTableBtnClick actionType=xhr', () => {
jest.spyOn(history, 'push')
const item1 = {
text: '删除',
actionType: 'xhr',
url: 'xhrasdfjasdflsadfjdsafjsdalkfjasdl',
transform: (v: any) => ({ ...v, xyz: 1235 }),
}
const row1 = {
id: 'test111',
name: 'xxxsdafs',
}
// @ts-ignore
WrapperTableInstance.onTableBtnClick(item1, row1)
const params = transformParams(uniqueKey, item1.transform, row1)
const requestInfo = mockAxios.getReqByUrl(item1.url)
expect(requestInfo.config.data).toEqual(params)
})
test('onTableBtnClick actionType=modalForm', () => {
// @ts-ignore
WrapperTableInstance.selectedBtnPath = selectedBtnPath
const {
pagestate,
uniqueKey,
onDataSourceChange,
} = WrapperTableInstance.props
// @ts-ignore
WrapperTableInstance.renderModalForm(
pagestate,
uniqueKey,
onDataSourceChange
)
const item1 = actionColumn.operations2[0]
// @ts-ignore
item1.__path__ = `actionColumn.operations2[0]`
// @ts-ignore
item1.actionType = `modalForm`
const row1 = {
id: 'test111',
name: 'xxxsdafs',
}
// @ts-ignore
WrapperTableInstance.onTableBtnClick(item1, row1)
expect(
// @ts-ignore
WrapperTableInstance.props.pagestate[tableRowModalFormAlias]
).toEqual(row1)
})
test('onTableSelectChange', () => {
const setStoreStateMock = jest.spyOn(
WrapperTableInstance.props.pagestate,
'setStoreState'
)
const selectedRowKeys = ['asdf', 'asdfsdf']
// @ts-ignore
WrapperTableInstance.onTableSelectChange(selectedRowKeys)
expect(setStoreStateMock).toHaveBeenCalledWith({
[tableSelectionRowKeysAlias]: selectedRowKeys,
})
setStoreStateMock.mockRestore()
})
test('toggleModalFormVisible', () => {
// @ts-ignore
const toggleModalVisibleMock = jest.spyOn(
// @ts-ignore
WrapperTableInstance.$HtModalForm,
'toggleModalVisible'
)
// @ts-ignore
WrapperTableInstance.toggleModalFormVisible(true)
expect(toggleModalVisibleMock).toBeCalledWith(true)
// @ts-ignore
WrapperTableInstance.toggleModalFormVisible(false)
expect(toggleModalVisibleMock).toBeCalledWith(false)
toggleModalVisibleMock.mockRestore()
})
describe('renderSelections', () => {
const children = [<div key="1">1234</div>]
const selectedRowKeys = ['asdf']
const dataPagestatePath = 'sadjkfhaksjdfhjkds'
test('children is not an array', () => {
// @ts-ignore
const result = WrapperTableInstance.renderSelections(
{},
selectedRowKeys,
dataPagestatePath
)
expect(result).toBeNull()
})
test(`children is an array`, () => {
// @ts-ignore
const result = WrapperTableInstance.renderSelections(
children,
selectedRowKeys,
dataPagestatePath
)
expect(result).toHaveLength(children.length)
for (let i = 0; i < result.length; i++) {
const item = result[i]
expect(item.props).toHaveProperty(
'disabled',
selectedRowKeys.length === 0
)
expect(item.props).toHaveProperty(
'data-pageconfig-path',
`${dataPagestatePath}[${i}]`
)
}
})
})
test('renderTableColumnMore', () => {
const renderTableColumnButtonMock = jest.spyOn(
WrapperTableInstance,
// @ts-ignore
'renderTableColumnButton'
)
const menus = [
{
text: '编辑',
url: 'xxxasdf',
},
{
text: '详情',
url: 'detail',
},
]
const row = {
id: 'testidadsfsdf',
name: 'sadfsdf',
}
// @ts-ignore
const result = WrapperTableInstance.renderTableColumnMore(menus, row)
const _Wrapper = mount(result)
const WrapperDropdown0 = _Wrapper.find(Dropdown).at(0)
const WrapperDropdown0Overlay = WrapperDropdown0.prop('overlay')
// @ts-ignore
expect(WrapperDropdown0Overlay.props.children).toHaveLength(menus.length)
const WrapperDropdown0Children = WrapperDropdown0.prop('children')
// @ts-ignore
expect(WrapperDropdown0Children.props.className).toEqual(
'ant-dropdown-link'
)
expect(renderTableColumnButtonMock).toHaveBeenCalledTimes(2)
renderTableColumnButtonMock.mockRestore()
})
test('renderTableColumnButton', () => {
const item = {
text: 'testButton',
url: 'asdfasd',
}
const row = {
id: 1235,
}
// @ts-ignore
const result = WrapperTableInstance.renderTableColumnButton(item, row)
expect(result.type).toEqual(Button)
expect(result.props).toMatchObject({
type: 'link',
className: 'table-row-link',
onClick: expect.any(Function),
'data-item': JSON.stringify(item),
})
const item1 = {
text: 'test2',
actionType: 'xhr',
url: 'sakdfjkhsdhf',
}
// @ts-ignore
const result1 = WrapperTableInstance.renderTableColumnButton(item1, row)
expect(result1.type).toEqual(Popconfirm)
expect(result1.props).toMatchObject({
onConfirm: expect.any(Function),
})
expect(result1.props.children.type).toEqual(Button)
expect(result1.props.children.props).toMatchObject({
className: expect.stringMatching('table-row-link'),
})
})
describe('renderColumns', () => {
const columns: TableColumn[] = [
{
'v-if': false,
title: '第1列',
dataIndex: 'v-if',
},
{
title: '第2列',
dataIndex: 'dataIndex2',
width: 100,
},
{
title: '第3列',
dataIndex: 'operations',
width: 200,
max: 5,
operations: [
{
'v-if': false,
text: 'test-operations',
url: 'test-operations-url',
},
{
text: 'test-operations1',
url: 'test-operations-url1',
},
{
text: 'test-operations2',
url: 'test-operations-url2',
actionType: 'xhr',
transform: (v: any) => ({ ...v, xx: 'testtransform' }),
},
],
},
{
title: '第4列',
dataIndex: 'operations2',
width: 200,
operations2: [
{
'v-if': false,
text: 'test-operations2',
url: 'test-operations2-url',
fields: [],
},
{
text: 'test-operations21',
url: 'test-operations-url21',
width: 600,
fields: [
{
field: 'testfield',
title: 'testfield',
},
],
},
{
text: 'test-operations22',
url: 'test-operations-url22',
fields: [
{
field: 'testfield2',
title: 'testfield2',
},
],
transform: (v: any) => ({ ...v, iddd: 'testtransform' }),
},
],
},
{
title: '第5.1列',
dataIndex: 'renderType.default',
renderType: 'default',
},
{
title: '第5.2列',
dataIndex: 'renderType.a',
renderType: 'a',
},
{
title: '第5.3列',
dataIndex: 'renderType.img',
renderType: 'img',
},
{
title: '第5.4列',
dataIndex: 'renderType.time',
renderType: 'time',
},
{
title: '第5.5列',
dataIndex: 'renderType.data',
renderType: 'date',
},
{
title: '第5.6列',
dataIndex: 'renderType.boolean',
renderType: 'boolean',
},
{
title: '第6列',
dataIndex: 'showOverflowTooltip',
showOverflowTooltip: true,
},
{
title: '第7列',
dataIndex: 'tooltip',
tooltip: '提示信息',
},
]
const dataPageConfigPath = 'elementConfig'
// @ts-ignore
const result = WrapperTableInstance.renderColumns(
columns,
dataPageConfigPath
)
const columnsMap = getMap(result, 'dataIndex')
for (let i = 0; i < columns.length; i++) {
let item: any = columns[i]
let parsedItem = columnsMap[item.dataIndex]
let path = `${dataPageConfigPath}[${i}]`
let dataIndex = item.dataIndex
const shouldNotRender = item['v-if'] === false
if (shouldNotRender) {
test(`[v-if] ${dataIndex}`, () => {
// @ts-ignore
expect(parsedItem).toBeUndefined()
})
continue
}
if (!item.onHeaderCell) {
test(`[onHeaderCell] ${dataIndex}`, () => {
// @ts-ignore
expect(parsedItem.onHeaderCell()).toEqual({
'data-component-type': 'HtList.column',
'data-pageconfig-path': path,
})
})
}
if (item.render) {
if (!_.isFunction(item.render)) {
test(`[render] ${dataIndex}`, () => {
expect(parsedItem.render).toBeUndefined()
})
}
continue
}
if (item.operations) {
const _render = parsedItem.render
if (_.isArray(item.operations)) {
test(`[operations] ${dataIndex}`, () => {
expect(_render).toBeInstanceOf(Function)
})
const recordMock = {
id: 'asdfdsf',
}
const filterOperates = item.operations.filter((o: any) => {
// v-if 后面接收一个function
if (_.isFunction(o['v-if'])) {
return o['v-if'](recordMock)
}
// v-if 后面接收一个bool值
return o['v-if'] !== false
})
const max = item.max
test(`[operations v-if & max] ${dataIndex}`, () => {
const renderTableColumnButtonMock = jest.spyOn(
WrapperTableInstance,
// @ts-ignore
'renderTableColumnButton'
)
const renderTableColumnMoreMock = jest.spyOn(
WrapperTableInstance,
// @ts-ignore
'renderTableColumnMore'
)
_render(null, recordMock)
expect(renderTableColumnButtonMock).toHaveBeenCalledTimes(
filterOperates.slice(0, max).length
)
expect(renderTableColumnMoreMock).toHaveBeenCalledWith(
filterOperates.slice(max),
recordMock
)
renderTableColumnButtonMock.mockRestore()
renderTableColumnMoreMock.mockRestore()
})
continue
}
}
}
})
test('renderModalForm', () => {
// @ts-ignore
WrapperTableInstance.selectedBtnPath = selectedBtnPath
const {
pagestate,
uniqueKey,
onDataSourceChange,
} = WrapperTableInstance.props
// @ts-ignore
const result3 = WrapperTableInstance.renderModalForm(
pagestate,
uniqueKey,
onDataSourceChange
)
const wrapper = mount(result3)
const WrapperModalForm = wrapper.find(HtModalForm).at(0)
const origin = _.get(elementConfig.props, selectedBtnPath)
const { title, text, method = 'post', fields = [], transform } = origin
expect(WrapperModalForm.props()).toMatchObject({
method,
fields,
title: title || text,
alias: tableRowModalFormAlias,
pagestate,
onSuccess: WrapperTableInstance.props.onDataSourceChange,
onSuccessAction: 'trigger:HtList.search',
})
const getRef = WrapperModalForm.prop('getRef')
expect(getRef).toEqual(expect.any(Function))
if (_.isFunction(getRef)) {
const HtModalForm = {
toggleModalVisible: jest.fn(),
}
getRef(HtModalForm)
// @ts-ignore
expect(WrapperTableInstance.$HtModalForm).toEqual(HtModalForm)
}
const rowData = _.get(pagestate, tableRowModalFormAlias)
const _transform = WrapperModalForm.prop('transform')
const expectTrasform = (data: any) => {
return transformParams(uniqueKey, transform, rowData, data)
}
const mockData = { a: 1 }
if (_.isFunction(_transform)) {
expect(_transform(mockData)).toEqual(expectTrasform(mockData))
}
})
})
function getMap(arr: any[], key: string) {
let map: any = {}
for (let item of arr) {
if (_.isString(item[key])) {
map[item[key]] = item
}
}
return map
} | the_stack |
import { Nes } from "./nes";
declare var toastr;
export class SaveState {
//CPU
A: number = 0; // Accumulator Register
X: number = 0; // X Register
Y: number = 0; // Y Register
STACK: number = 0; // Stack Pointer (points to location on bus)
PC: number = 0x8000; // Program Counter (16 bit), hardcoded to start at 0x8000?
STATUS: number = 0; // Status Register
address: number = 0; // address to get data based on addressing mode
cycles: number = 0; // number of cpu cycles left for the current operation
nmi_requested = false;
irq_requested = false;
//MEMORY
ram: Uint8Array;
saveRam: Uint8Array;
//CARTRIDGE
chrData:Uint8Array;
//PPU
vram: Uint8Array;
scanline = -1; //y coordinate of scanline
tick = 0; //x coordinate of scanline
nametable_x = 0; //which nametable gets drawn first
nametable_y = 0; //which nametable gets drawn first
increment_mode = 0; //ppu to increment address by 1 or 32
pattern_sprite = 0; //tells you whether to read sprite tiles from chr page 1 or 2
pattern_background = 0; //tells you whether to read background tiles from chr page 1 or 2
sprite_size = 0;
slave_mode = 0; // unused
enable_nmi = 0;
greyscale = 0;
show_background_leftmost = 0;
show_sprites_leftmost = 0;
show_background = 0;
show_sprites = 0;
emphasize_red = 0;
emphasize_green = 0;
emphasize_blue = 0;
sprite_overflow = 0;
sprite_zero_hit = 0;
vertical_blank = 0; //period when tv laser is off screen
scroll_x = 0; //ScrollX offset
scroll_y = 0; //scrollY offset
scroll_last = 0; //for address latch alternation
marioHack = false;
isMMC3 = false;
ppu_data: number = 0;
ppu_data_delay: number = 0; //reading from the ppu by the cpu is delayed by one cycle
ppu_address: number = 0;
ppu_address_lo_high = 0;
oam: Uint8Array;
oamAddress = 0;
//MAPPERS
prgBanksCount = 0;
chrBanksCount = 0;
mapper = 0;
prgMode = 0;
prgBankSwitchable = 0; //index of prg bank that is switchable
prgBank0offset = 0; //used to calculate offset into prg data based on current bank
prgBank1offset = 0;
prgBank2offset = 0; //used in mmc3 mapper
prgBank3offset = 0;
chrMode = 0;
chrBank0 = 0; //which chr bank 0 is using
chrBank1 = 0; //which chr bank 1 is using
mapperShiftRegister = 0; //it takes 5 writes for MMC1, each right loads into this shift register
mapperWriteCount = 0; //keeps track to know when the 5th write has occurred
mmc3BankSelect = 0;
mmc3PrgMode = 0;
mmc3ChrA12 = 0;
irqEnabled = false;
irqCounter = 0;
irqCounterReset = 0;
irqReloadRequested = false;
static save(nes: Nes, name: string) {
let saveState = new SaveState();
//ram (16kb)
saveState.ram = new Uint8Array(0x4020);
for (let i = 0; i < saveState.ram.length; i++)
saveState.ram[i] = nes.memory.ram[i];
//vram (16kb)
saveState.vram = new Uint8Array(0x4000);
for (let i = 0; i < saveState.vram.length; i++)
saveState.vram[i] = nes.ppu.vram[i];
//chr (8kb)
saveState.chrData = new Uint8Array(8192);
for (let i = 0; i < saveState.chrData.length; i++)
saveState.chrData[i] = nes.cartridge.chrData[i];
//sram (16kb) - only save 0x4000-0x8000
saveState.saveRam = new Uint8Array(0x4000);
for (let i = 0; i < 0x4000; i++)
saveState.saveRam[i] = nes.memory.saveRam[i+0x4000];
//CPU
saveState.A = nes.cpu.A;
saveState.X = nes.cpu.X;
saveState.Y = nes.cpu.Y;
saveState.STACK = nes.cpu.STACK;
saveState.PC = nes.cpu.PC;
saveState.STATUS = nes.cpu.STATUS;
saveState.address = nes.cpu.address;
saveState.cycles = nes.cpu.cycles;
saveState.nmi_requested = nes.cpu.nmi_requested;
saveState.irq_requested = nes.cpu.irq_requested;
//PPU
saveState.scanline = nes.ppu.scanline;
saveState.tick = nes.ppu.tick;
saveState.nametable_x = nes.ppu.nametable_x;
saveState.nametable_y = nes.ppu.nametable_y;
saveState.increment_mode = nes.ppu.increment_mode;
saveState.pattern_sprite = nes.ppu.pattern_sprite;
saveState.pattern_background = nes.ppu.pattern_background;
saveState.sprite_size = nes.ppu.sprite_size;
saveState.slave_mode = nes.ppu.slave_mode;
saveState.enable_nmi = nes.ppu.enable_nmi;
saveState.greyscale = nes.ppu.greyscale;
saveState.show_background_leftmost = nes.ppu.show_background_leftmost;
saveState.show_sprites_leftmost = nes.ppu.show_sprites_leftmost;
saveState.show_background = nes.ppu.show_background;
saveState.show_sprites = nes.ppu.show_sprites;
saveState.emphasize_red = nes.ppu.emphasize_red;
saveState.emphasize_green = nes.ppu.emphasize_green;
saveState.emphasize_blue = nes.ppu.emphasize_blue;
saveState.sprite_overflow = nes.ppu.sprite_overflow;
saveState.sprite_zero_hit = nes.ppu.sprite_zero_hit;
saveState.vertical_blank = nes.ppu.vertical_blank;
saveState.scroll_x = nes.ppu.scroll_x;
saveState.scroll_y = nes.ppu.scroll_y;
saveState.scroll_last = nes.ppu.scroll_last;
saveState.marioHack = nes.ppu.marioHack;
saveState.isMMC3 = nes.ppu.isMMC3;
saveState.ppu_data = nes.ppu.ppu_data;
saveState.ppu_data_delay = nes.ppu.ppu_data_delay;
saveState.ppu_address = nes.ppu.ppu_address;
saveState.ppu_address_lo_high = nes.ppu.ppu_address_lo_high;
saveState.scroll_y = nes.ppu.scroll_y;
saveState.oam = nes.ppu.oam;
saveState.oamAddress = nes.ppu.oamAddress;
//MAPPERS
saveState.prgBanksCount = nes.memory.prgBanksCount;
saveState.chrBanksCount = nes.memory.chrBanksCount;
saveState.mapper = nes.memory.mapper;
saveState.prgMode = nes.memory.prgMode;
saveState.prgBankSwitchable = nes.memory.prgBankSwitchable;
saveState.prgBank0offset = nes.memory.prgBank0offset;
saveState.prgBank1offset = nes.memory.prgBank1offset;
saveState.prgBank2offset = nes.memory.prgBank2offset;
saveState.prgBank3offset = nes.memory.prgBank3offset;
saveState.chrMode = nes.memory.chrMode;
saveState.chrBank0 = nes.memory.chrBank0;
saveState.chrBank1 = nes.memory.chrBank1;
saveState.mapperShiftRegister = nes.memory.mapperShiftRegister;
saveState.mapperWriteCount = nes.memory.mapperWriteCount;
saveState.mmc3BankSelect = nes.memory.mmc3BankSelect;
saveState.mmc3PrgMode = nes.memory.mmc3PrgMode;
saveState.mmc3ChrA12 = nes.memory.mmc3ChrA12;
saveState.irqEnabled = nes.memory.irqEnabled;
saveState.irqCounter = nes.memory.irqCounter;
saveState.irqCounterReset = nes.memory.irqCounterReset;
saveState.irqReloadRequested = nes.memory.irqReloadRequested;
var request = indexedDB.open('NeilNESDB');
request.onsuccess = function (ev: any) {
var db = ev.target.result as IDBDatabase;
var romStore = db.transaction("NESROMS", "readwrite").objectStore("NESROMS");
var addRequest = romStore.put(saveState, name + '.sav');
addRequest.onsuccess = function (event) {
console.log('data added');
window["saveState"] = saveState;
};
addRequest.onerror = function (event) {
console.log('error adding data');
console.log(event);
};
}
}
static load(nes: Nes, name: string) {
var request = indexedDB.open('NeilNESDB');
request.onsuccess = function (ev: any) {
var db = ev.target.result as IDBDatabase;
var romStore = db.transaction("NESROMS", "readwrite").objectStore("NESROMS");
var rom = romStore.get(name + '.sav');
rom.onsuccess = function (event) {
if (rom.result==null || rom.result==undefined)
{
toastr.error("No Save Found");
}
else
{
let saveStateData = rom.result as SaveState;
nes.loadStateData = saveStateData;
console.log('data pulled from db');
window["saveState"] = saveStateData;
}
};
rom.onerror = function (event) {
console.log('error getting save state data from store');
}
}
request.onerror = function (ev: any) {
console.log('error loading db');
}
}
static parseLoad(nes: Nes,saveState:SaveState){
for (let i = 0; i < 0x4020; i++)
nes.memory.ram[i] = saveState.ram[i];
for (let i = 0; i < 0x4000; i++)
nes.ppu.vram[i] = saveState.vram[i];
for (let i = 0; i < 8192; i++)
nes.cartridge.chrData[i] = saveState.chrData[i];
for (let i = 0; i < 0x4000; i++)
nes.memory.saveRam[i+0x4000] = saveState.saveRam[i];
//CPU
nes.cpu.A = saveState.A;
nes.cpu.X = saveState.X;
nes.cpu.Y = saveState.Y;
nes.cpu.STACK = saveState.STACK;
nes.cpu.PC = saveState.PC;
nes.cpu.STATUS = saveState.STATUS;
nes.cpu.address = saveState.address;
nes.cpu.cycles = saveState.cycles;
nes.cpu.nmi_requested = saveState.nmi_requested;
nes.cpu.irq_requested = saveState.irq_requested;
//PPU
nes.ppu.scanline = saveState.scanline;
nes.ppu.tick = saveState.tick;
nes.ppu.nametable_x = saveState.nametable_x;
nes.ppu.nametable_y = saveState.nametable_y;
nes.ppu.increment_mode = saveState.increment_mode;
nes.ppu.pattern_sprite = saveState.pattern_sprite;
nes.ppu.pattern_background = saveState.pattern_background;
nes.ppu.sprite_size = saveState.sprite_size;
nes.ppu.slave_mode = saveState.slave_mode;
nes.ppu.enable_nmi = saveState.enable_nmi;
nes.ppu.greyscale = saveState.greyscale;
nes.ppu.show_background_leftmost = saveState.show_background_leftmost;
nes.ppu.show_sprites_leftmost = saveState.show_sprites_leftmost;
nes.ppu.show_background = saveState.show_background;
nes.ppu.show_sprites = saveState.show_sprites;
nes.ppu.emphasize_red = saveState.emphasize_red;
nes.ppu.emphasize_green = saveState.emphasize_green;
nes.ppu.emphasize_blue = saveState.emphasize_blue;
nes.ppu.sprite_overflow = saveState.sprite_overflow;
nes.ppu.sprite_zero_hit = saveState.sprite_zero_hit;
nes.ppu.vertical_blank = saveState.vertical_blank;
nes.ppu.scroll_x = saveState.scroll_x;
nes.ppu.scroll_y = saveState.scroll_y;
nes.ppu.scroll_last = saveState.scroll_last;
nes.ppu.marioHack = saveState.marioHack;
nes.ppu.isMMC3 = saveState.isMMC3;
nes.ppu.ppu_data = saveState.ppu_data;
nes.ppu.ppu_data_delay = saveState.ppu_data_delay;
nes.ppu.ppu_address = saveState.ppu_address;
nes.ppu.ppu_address_lo_high = saveState.ppu_address_lo_high;
nes.ppu.scroll_y = saveState.scroll_y;
nes.ppu.oam = saveState.oam;
nes.ppu.oamAddress = saveState.oamAddress;
//MAPPERS
nes.memory.prgBanksCount = saveState.prgBanksCount;
nes.memory.chrBanksCount = saveState.chrBanksCount;
nes.memory.mapper = saveState.mapper;
nes.memory.prgMode = saveState.prgMode;
nes.memory.prgBankSwitchable = saveState.prgBankSwitchable;
nes.memory.prgBank0offset = saveState.prgBank0offset;
nes.memory.prgBank1offset = saveState.prgBank1offset;
nes.memory.prgBank2offset = saveState.prgBank2offset;
nes.memory.prgBank3offset = saveState.prgBank3offset;
nes.memory.chrMode = saveState.chrMode;
nes.memory.chrBank0 = saveState.chrBank0;
nes.memory.chrBank1 = saveState.chrBank1;
nes.memory.mapperShiftRegister = saveState.mapperShiftRegister;
nes.memory.mapperWriteCount = saveState.mapperWriteCount;
nes.memory.mmc3BankSelect = saveState.mmc3BankSelect;
nes.memory.mmc3PrgMode = saveState.mmc3PrgMode;
nes.memory.mmc3ChrA12 = saveState.mmc3ChrA12;
nes.memory.irqEnabled = saveState.irqEnabled;
nes.memory.irqCounter = saveState.irqCounter;
nes.memory.irqCounterReset = saveState.irqCounterReset;
nes.memory.irqReloadRequested = saveState.irqReloadRequested;
//for backwards compatibility with
//older savestates before i switched
//to single ppu.clock() cycle vs 3
if (nes.ppu.tick%3!=0)
{
nes.ppu.tick -= nes.ppu.tick%3;
}
console.log('data loaded');
}
static reset(nes: Nes){
for (let i = 0; i < 0x4020; i++)
nes.memory.ram[i] = 0;
for (let i = 0; i < 0x4000; i++)
nes.ppu.vram[i] = 0;
for (let i = 0; i < 8192; i++)
nes.cartridge.chrData[i] = 0;
for (let i = 0; i < 0x4000; i++)
nes.memory.saveRam[i+0x4000] = 0;
for (let i = 0; i < nes.ppu.oam.length; i++)
nes.ppu.oam[i] = 0x00;
//CPU
nes.cpu.A = 0;
nes.cpu.X = 0;
nes.cpu.Y = 0;
nes.cpu.STACK = 0;
nes.cpu.PC = 0;
nes.cpu.STATUS = 0;
nes.cpu.address = 0;
nes.cpu.cycles =0;
nes.cpu.nmi_requested = false;
nes.cpu.irq_requested = false;
//PPU
nes.ppu.scanline = -1;
nes.ppu.tick = 0;
nes.ppu.nametable_x = 0;
nes.ppu.nametable_y = 0;
nes.ppu.increment_mode = 0;
nes.ppu.pattern_sprite = 0;
nes.ppu.pattern_background = 0;
nes.ppu.sprite_size = 0;
nes.ppu.slave_mode = 0;
nes.ppu.enable_nmi = 0;
nes.ppu.greyscale = 0;
nes.ppu.show_background_leftmost = 0;
nes.ppu.show_sprites_leftmost = 0;
nes.ppu.show_background = 0;
nes.ppu.show_sprites = 0;
nes.ppu.emphasize_red = 0;
nes.ppu.emphasize_green = 0;
nes.ppu.emphasize_blue = 0;
nes.ppu.sprite_overflow = 0;
nes.ppu.sprite_zero_hit = 0;
nes.ppu.vertical_blank = 0;
nes.ppu.scroll_x = 0;
nes.ppu.scroll_y = 0;
nes.ppu.scroll_last = 0;
nes.ppu.ppu_data = 0;
nes.ppu.ppu_data_delay = 0;
nes.ppu.ppu_address = 0;
nes.ppu.ppu_address_lo_high = 0;
nes.ppu.scroll_y = 0;
nes.ppu.oamAddress = 0;
}
} | the_stack |
import * as Modal from "boron/FadeModal";
import { autobind } from "core-decorators";
import * as React from "react";
// tslint:disable-next-line:max-line-length
import { Button, Divider, Dropdown, Form, Grid, Header, Icon, Image, Input, Message, Popup, Segment } from "semantic-ui-react";
import { IPodcast } from "../../../lib/interfaces";
import { colors, globalStyles } from "../../../lib/styles";
interface IPodcastFormProps {
onSubmit: (formState: IPodcastDesignFields) => Promise<void>;
onPreview: (item: IPodcastDesignFields) => Promise<void>;
currentPodcast: IPodcast;
}
export interface IPodcastDesignFields {
theme: "light" | "dark" | "sky" | "silver" | "sand";
layout: "classic" | "minimalistic";
}
export interface IPodcastFormState {
fields: IPodcastDesignFields;
previewDevice?: string;
}
function getIconProps(value: string) {
switch (value) {
case "dark":
return {
size: "large", name: "square", style: {
color: "#000000",
border: "1px solid #EEE",
background: "#000000",
},
};
case "silver":
return {
size: "large", name: "square", style: {
color: "#CDC9C9",
border: "1px solid #EEE",
background: "#CDC9C9",
},
};
case "sky":
return {
size: "large", name: "square", style: {
color: "#B2D3FD",
border: "1px solid #EEE",
background: "#B2D3FD",
},
};
case "light":
return {
size: "large", name: "square", style: {
color: "#FFFFFF",
border: "1px solid #EEE",
background: "white",
},
};
case "sand":
return {
size: "large", name: "square", style: {
color: "#EDECE7",
border: "1px solid #EEE",
background: "#EDECE7",
},
};
}
return { size: "large", name: "square", style: { color: "#FFFFFF" } };
}
const selectThemeOptions = [
{ key: "darkk", value: "dark", text: "Dark", icon: getIconProps("dark") },
{ key: "silver", value: "silver", text: "Silver", icon: getIconProps("silver") },
{ key: "sky", value: "sky", text: "Sky", icon: getIconProps("sky") },
{ key: "light", value: "light", text: "Light", icon: getIconProps("light") },
{ key: "sand", value: "sand", text: "Sand", icon: getIconProps("sand") },
];
export default class PodcastForm extends React.Component<IPodcastFormProps, IPodcastFormState> {
constructor(props: IPodcastFormProps) {
super();
if (props.currentPodcast) {
const theme = props.currentPodcast.theme ? props.currentPodcast.theme : "light";
const layout = props.currentPodcast.layout ? props.currentPodcast.layout : "classic";
this.state = {
fields: { theme, layout },
previewDevice: "desktop",
};
}
}
public render() {
return (
<Segment style={{ width: "75%", paddingLeft: 0 }} basic>
<Form>
<Header as="h2" style={globalStyles.title}>
Design
</Header>
<Form.Field inline required>
<label style={style.formLabel}>Theme</label>
<Dropdown
placeholder="theme"
name="theme"
value={this.state.fields.theme}
options={selectThemeOptions}
onChange={this.onChangeInputField}
style={style.formInput}
trigger={(
<div>
<Icon
style={getIconProps(this.state.fields.theme).style}
name={getIconProps(this.state.fields.theme).name} />
<span style={{ color: colors.mainDark }}>{this.state.fields.theme}</span>
</div>
)}
selection />
</Form.Field>
{/*
<Grid style={{ marginTop: 30 }}>
<Grid.Row columns={2}>
<Grid.Column width={8}>
<div
onClick={() => {
this.setState({ fields: { ...this.state.fields, layout: "classic" } });
}}
style={{
backgroundColor: "#EDECE7",
width: "23vw",
height: "17vw",
cursor: "pointer",
// tslint:disable-next-line:max-line-length
border: this.state.fields.layout === "classic" ? "3px solid #68C3EF" : "3px solid #E1ECF1",
}}>
<Image
style={{ width: "100%", height: "100%" }}
src="/assets/design/classic-design.png" />
</div>
<Header style={style.layoutHeader} textAlign="center">
Classic
</Header>
</Grid.Column>
<Grid.Column width={8}>
<div
onClick={() => {
this.setState({ fields: { ...this.state.fields, layout: "minimalistic" } });
}}
style={{
cursor: "pointer",
backgroundColor: "#EDECE7",
width: "23vw",
height: "17vw",
// tslint:disable-next-line:max-line-length
border: this.state.fields.layout === "minimalistic" ? "3px solid #68C3EF" : "3px solid #E1ECF1",
}}>
<Image
style={{ width: "100%", height: "100%" }}
src="/assets/design/minimalistic-design.png" />
</div>
<Header style={style.layoutHeader} textAlign="center">
Minimalistic
</Header>
</Grid.Column>
</Grid.Row>
</Grid>
*/}
<Button
onClick={(e) => this.onPreview(this.state.fields, e)}
style={{ marginTop: "1em", fontWeight: 550, fontSize: "120%", color: "white", backgroundColor: "#6D75DD"}}>
Preview
</Button>
<Button
onClick={(e) => this.onSubmit(e)}
style={{ marginTop: "1em", fontWeight: 550, fontSize: "120%", color: "black", backgroundColor: "#F4CB10"}}>
Save
</Button>
</Form>
<Modal modalStyle={style.previewModal} ref="modal" keyboard={(e: any) => this.callback(e)}>
<div style={style.previewHeader}>
<div style={style.deviceIcons}>
<Button
onClick={() => this.setState({ previewDevice: "desktop" })} style={style.deviceIcon}>
<Icon style={this.getPreviewIconColor("desktop")} name="desktop" size="big" />
</Button>
<Button onClick={() => this.setState({ previewDevice: "tablet" })} style={style.deviceIcon}>
<Icon style={this.getPreviewIconColor("tablet")} name="tablet" size="big" />
</Button>
<Button onClick={() => this.setState({ previewDevice: "mobile" })} style={style.deviceIcon}>
<Icon style={this.getPreviewIconColor("mobile")} name="mobile" size="big" />
</Button>
</div>
<Button onClick={() => this.hidePreview()} style={style.previewCloseIcon}>
<Icon name="delete" size="large" />
</Button>
</div>
<div style={style.iframeContainer}>
<iframe
style={this.getPreviewStyle()}
src={`/p/${this.props.currentPodcast.slug}/design-preview/#/`}>
</iframe>
</div>
</Modal>
</Segment>
);
}
protected getPreviewIconColor(device: string) {
return this.state.previewDevice === device ? { color: "black" } : { color: "gray" };
}
protected getPreviewStyle() {
switch (this.state.previewDevice) {
case "desktop":
return style.previewIframeDesktop;
case "tablet":
return style.previewIframeTablet;
case "mobile":
return style.previewIframeMobile;
}
return style.previewIframeDesktop;
}
protected showPreview() {
(this.refs.modal as any).show();
this.setState({ previewDevice: "desktop" });
}
protected hidePreview() {
(this.refs.modal as any).hide();
}
protected callback(event: any) {
// console.warn(event);
}
@autobind
protected async onPreview(item: IPodcastDesignFields, e: React.MouseEvent<HTMLButtonElement>) {
e.preventDefault();
await this.props.onPreview(item);
this.showPreview();
}
@autobind
protected onChangeInputField(e: React.ChangeEvent<HTMLInputElement>, input: any) {
if (input && input.name) {
const fields = { ...this.state.fields, [input.name]: input.value };
this.setState({ fields });
}
}
@autobind
protected async onSubmit(e: any) {
e.preventDefault();
await this.props.onSubmit(this.state.fields);
}
}
const style = {
formInput: {
},
formLabel: {
color: colors.mainDark,
},
actionContainer: {
flex: 1,
display: "flex",
flexDirection: "row" as "row",
justifyContent: "center" as "center",
},
tooltip: {
...globalStyles.tooltip,
margin: 0,
marginBottom: 0,
marginLeft: 15,
},
actionIcon: {
fontSize: "80%",
backgroundColor: "transparent",
paddingLeft: 0,
paddingRight: 0,
marginRight: 15,
alignSelf: "flex-end",
},
previewModal: {
width: "90%",
height: "90%",
},
previewIframeDesktop: {
display: "block",
width: "90vw",
height: "83vh",
},
previewIframeTablet: {
display: "block",
width: (window.innerHeight * 0.9) * 0.75, // iPad aspect ratio
height: "83vh",
},
previewIframeMobile: {
display: "block",
width: (window.innerHeight * 0.9) * 0.5625, // iPhone apsect ratio
height: "83vh",
},
previewHeader: {
display: "block",
height: "7vh",
width: "90vw",
},
previewCloseIcon: {
backgroundColor: "transparent",
position: "absolute",
top: 0,
right: 0,
width: "1vh",
height: "1vh",
display: "flex",
justifyContent: "center" as "center",
},
deviceIcon: {
backgroundColor: "transparent",
},
deviceIcons: {
display: "flex",
flex: 1,
height: "7vh",
justifyContent: "center" as "center",
fontSize: "140%",
},
iframeContainer: {
display: "flex",
flexDirection: "row" as "row",
justifyContent: "center" as "center",
backgroundColor: "#333",
},
layoutHeader: {
width: "23vw",
marginTop: 15,
color: colors.mainDark,
},
}; | the_stack |
import * as vscode from "vscode";
import BaseCommandHandler from "./shared/command-handler";
import * as diff from "./shared/diff";
const ignoreParser: any = require("gitignore-globs");
export default class CommandHandler extends BaseCommandHandler {
private activeEditor?: vscode.TextEditor;
private errorColor: string = "255, 99, 71";
private openFileList: any[] = [];
private successColor: string = "43, 161, 67";
private languageToExtension: { [key: string]: string[] } = {
c: ["c", "h"],
cpp: ["cpp", "cc", "cxx", "c++", "hpp", "hh", "hxx", "h++"],
csharp: ["cs"],
css: ["css", "scss"],
dart: ["dart"],
go: ["go"],
html: ["html", "vue", "svelte"],
java: ["java"],
javascript: ["js", "jsx"],
javascriptreact: ["jsx", "js"],
jsx: ["jsx", "js"],
kotlin: ["kt"],
python: ["py"],
ruby: ["rb"],
rust: ["rs"],
scss: ["scss"],
shellscript: ["sh", "bash"],
typescript: ["ts", "tsx"],
typescriptreact: ["tsx", "ts"],
vue: ["vue", "html"],
};
async focus(): Promise<any> {
this.updateActiveEditor();
if (!this.activeEditor) {
return;
}
await vscode.window.showTextDocument(this.activeEditor!.document);
await this.uiDelay();
}
getActiveEditorText(): string | undefined {
if (!this.activeEditor) {
return undefined;
}
return this.activeEditor!.document.getText();
}
highlightRanges(ranges: diff.DiffRange[]): number {
const duration = 300;
const steps = [1, 2, 1];
const step = duration / steps.length;
const editor = vscode.window.activeTextEditor;
if (!editor || ranges.length == 0) {
return 0;
}
for (const range of ranges) {
const decorations = steps.map((e) =>
vscode.window.createTextEditorDecorationType({
backgroundColor: `rgba(${
range.diffRangeType == diff.DiffRangeType.Delete ? this.errorColor : this.successColor
}, 0.${e})`,
isWholeLine: range.diffHighlightType == diff.DiffHighlightType.Line,
})
);
// atom and vs code use different types of ranges
if (range.diffHighlightType == diff.DiffHighlightType.Line) {
range.stop.row--;
}
for (let i = 0; i < steps.length; i++) {
setTimeout(() => {
this.activeEditor!.setDecorations(decorations[i], [
new vscode.Range(
range.start.row,
range.start.column,
range.stop.row,
range.stop.column
),
]);
setTimeout(() => {
decorations[i].dispose();
}, step);
}, i * step);
}
}
return 400;
}
pollActiveEditor() {
setInterval(() => {
this.updateActiveEditor();
}, 1000);
}
async scrollToCursor(): Promise<any> {
if (!this.activeEditor) {
return;
}
const cursor = this.activeEditor!.selection.start.line;
if (this.activeEditor!.visibleRanges.length > 0) {
const range = this.activeEditor!.visibleRanges[0];
const buffer = 5;
if (cursor < range.start.line + buffer || cursor > range.end.line - buffer) {
await vscode.commands.executeCommand("revealLine", {
lineNumber: cursor,
at: "center",
});
}
}
}
select(startRow: number, startColumn: number, endRow: number, endColumn: number) {
if (!this.activeEditor) {
return;
}
this.activeEditor!.selections = [
new vscode.Selection(startRow, startColumn, endRow, endColumn),
];
}
setSourceAndCursor(before: string, source: string, row: number, column: number) {
if (!this.activeEditor) {
return;
}
if (before != source) {
this.activeEditor!.edit((edit) => {
const firstLine = this.activeEditor!.document.lineAt(0);
const lastLine = this.activeEditor!.document.lineAt(
this.activeEditor!.document.lineCount - 1
);
const textRange = new vscode.Range(
0,
firstLine.range.start.character,
this.activeEditor!.document.lineCount - 1,
lastLine.range.end.character
);
edit.replace(textRange, source);
});
}
this.activeEditor!.selections = [new vscode.Selection(row, column, row, column)];
}
updateActiveEditor() {
const editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
this.activeEditor = editor;
}
getCursorPosition(position: any, text: string) {
const row = position.line;
const column = position.character;
// iterate through text, incrementing rows when newlines are found, and counting columns when row is right
let cursor = 0;
let currentRow = 0;
let currentColumn = 0;
for (let i = 0; i < text.length; i++) {
if (currentRow === row) {
if (currentColumn === column) {
break;
}
currentColumn++;
}
if (text[i] === "\n") {
currentRow++;
}
cursor++;
}
return cursor;
}
async COMMAND_TYPE_CLOSE_TAB(_data: any): Promise<any> {
await this.focus();
await vscode.commands.executeCommand("workbench.action.closeActiveEditor");
await this.uiDelay();
this.updateActiveEditor();
}
async COMMAND_TYPE_CLOSE_WINDOW(_data: any): Promise<any> {
await this.focus();
await vscode.commands.executeCommand("workbench.action.closeActiveEditor");
await this.uiDelay();
this.updateActiveEditor();
}
async COMMAND_TYPE_COPY(data: any): Promise<any> {
if (data && data.text) {
vscode.env.clipboard.writeText(data.text);
}
await this.uiDelay();
}
async COMMAND_TYPE_CREATE_TAB(_data: any): Promise<any> {
await this.focus();
await vscode.commands.executeCommand("workbench.action.files.newUntitledFile");
await this.uiDelay();
this.updateActiveEditor();
}
async COMMAND_TYPE_DUPLICATE_TAB(_data: any): Promise<any> {}
async COMMAND_TYPE_GET_EDITOR_STATE(data: any): Promise<any> {
let result = {
message: "editorState",
data: {
source: "",
cursor: 0,
selectionStart: 0,
selectionEnd: 0,
filename: "",
files: this.openFileList.map((e: any) => e.path),
roots: vscode.workspace.workspaceFolders
? vscode.workspace.workspaceFolders.map((e: any) => e.uri.path)
: [],
},
};
if (!this.activeEditor) {
return result;
}
result.data.filename = this.filenameFromLanguage(
this.activeEditor!.document.fileName,
this.activeEditor!.document.languageId,
this.languageToExtension
);
if (data.limited) {
return result;
}
const position = this.activeEditor!.selection.active;
const anchorPosition = this.activeEditor!.selection.anchor;
const text = this.activeEditor!.document.getText();
const cursor = this.getCursorPosition(position, text);
const anchor = this.getCursorPosition(anchorPosition, text);
if (cursor != anchor) {
result.data.selectionStart = cursor > anchor ? anchor : cursor;
result.data.selectionEnd = cursor < anchor ? anchor : cursor;
}
result.data.source = text;
result.data.cursor = this.getCursorPosition(position, text);
return result;
}
async COMMAND_TYPE_DEBUGGER_CONTINUE(_data: any): Promise<any> {
vscode.commands.executeCommand("workbench.action.debug.continue");
}
async COMMAND_TYPE_DEBUGGER_INLINE_BREAKPOINT(_data: any): Promise<any> {
await vscode.commands.executeCommand("editor.debug.action.toggleInlineBreakpoint");
}
async COMMAND_TYPE_DEBUGGER_PAUSE(_data: any): Promise<any> {
vscode.commands.executeCommand("workbench.action.debug.pause");
}
async COMMAND_TYPE_DEBUGGER_SHOW_HOVER(_data: any): Promise<any> {
await this.focus();
vscode.commands.executeCommand("editor.debug.action.showDebugHover");
}
async COMMAND_TYPE_DEBUGGER_START(_data: any): Promise<any> {
vscode.commands.executeCommand("workbench.action.debug.start");
}
async COMMAND_TYPE_DEBUGGER_STEP_INTO(_data: any): Promise<any> {
vscode.commands.executeCommand("workbench.action.debug.stepInto");
}
async COMMAND_TYPE_DEBUGGER_STEP_OUT(_data: any): Promise<any> {
vscode.commands.executeCommand("workbench.action.debug.stepOut");
}
async COMMAND_TYPE_DEBUGGER_STEP_OVER(_data: any): Promise<any> {
vscode.commands.executeCommand("workbench.action.debug.stepOver");
}
async COMMAND_TYPE_DEBUGGER_STOP(_data: any): Promise<any> {
vscode.commands.executeCommand("workbench.action.debug.stop");
}
async COMMAND_TYPE_DEBUGGER_TOGGLE_BREAKPOINT(_data: any): Promise<any> {
vscode.commands.executeCommand("editor.debug.action.toggleBreakpoint");
}
async COMMAND_TYPE_EVALUATE_IN_PLUGIN(data: any): Promise<any> {
vscode.commands.executeCommand(data.text);
}
async COMMAND_TYPE_GO_TO_DEFINITION(_data: any): Promise<any> {
await this.focus();
await vscode.commands.executeCommand("editor.action.revealDefinition");
}
async COMMAND_TYPE_NEXT_TAB(_data: any): Promise<any> {
await this.focus();
await vscode.commands.executeCommand("workbench.action.nextEditor");
await this.uiDelay();
this.updateActiveEditor();
}
async COMMAND_TYPE_OPEN_FILE(data: any): Promise<any> {
await vscode.window.showTextDocument(this.openFileList[data.index || 0]);
}
async COMMAND_TYPE_OPEN_FILE_LIST(data: any): Promise<any> {
await this.focus();
const path = data.path
.replace(/\//, "*/*")
.split("")
.map((e: string) => {
if (e == " ") {
return "*";
} else if (e.match(/[a-z]/)) {
return `{${e.toUpperCase()},${e.toLowerCase()}}`;
}
return e;
})
.join("");
let exclude: string[] = [
"**/.git",
"**/.hg",
"**/node_modules",
"**/npm_packages",
"**/npm",
...Object.keys(
(await vscode.workspace.getConfiguration("search", null).get("exclude")) || {}
),
...Object.keys((await vscode.workspace.getConfiguration("files", null).get("exclude")) || {}),
];
const ignorePath = await vscode.workspace.findFiles(".gitignore");
if (ignorePath.length > 0) {
exclude = exclude.concat(
ignoreParser._map(
ignoreParser._prepare(
Buffer.from(await vscode.workspace.fs.readFile(ignorePath[0]))
.toString("utf-8")
.split("\n")
)
)
);
}
this.openFileList = await vscode.workspace.findFiles(
`**/*${path}*`,
`{${exclude.map((e: string) => e.replace(/\\/g, "/")).join(",")}}`,
10
);
return { message: "sendText", data: { text: `callback open` } };
}
async COMMAND_TYPE_PREVIOUS_TAB(_data: any): Promise<any> {
await this.focus();
await vscode.commands.executeCommand("workbench.action.previousEditor");
await this.uiDelay();
this.updateActiveEditor();
}
async COMMAND_TYPE_REDO(_data: any): Promise<any> {
await this.focus();
await vscode.commands.executeCommand("redo");
await this.scrollToCursor();
}
async COMMAND_TYPE_SAVE(_data: any): Promise<any> {
await this.focus();
await vscode.commands.executeCommand("workbench.action.files.save");
}
async COMMAND_TYPE_SPLIT(data: any): Promise<any> {
await this.focus();
const direction = data.direction.toLowerCase();
const split = direction.charAt(0).toUpperCase() + direction.slice(1);
await vscode.commands.executeCommand(`workbench.action.splitEditor${split}`);
await this.uiDelay();
this.updateActiveEditor();
}
async COMMAND_TYPE_STYLE(_data: any): Promise<any> {
await this.focus();
await vscode.commands.executeCommand("editor.action.formatDocument");
await this.uiDelay();
}
async COMMAND_TYPE_SWITCH_TAB(data: any): Promise<any> {
await this.focus();
if (data.index <= 0) {
await vscode.commands.executeCommand("workbench.action.lastEditorInGroup");
} else {
await vscode.commands.executeCommand(`workbench.action.openEditorAtIndex${data.index}`);
}
await this.uiDelay();
this.updateActiveEditor();
}
async COMMAND_TYPE_UNDO(_data: any): Promise<any> {
await this.focus();
await vscode.commands.executeCommand("undo");
await this.scrollToCursor();
}
async COMMAND_TYPE_WINDOW(data: any): Promise<any> {
await this.focus();
const direction = data.direction.toLowerCase();
const split = direction.charAt(0).toUpperCase() + direction.slice(1);
await vscode.commands.executeCommand(`workspace.action.focus${split}Group`);
await this.uiDelay();
this.updateActiveEditor();
}
} | the_stack |
interface ZeptoStatic {
/**
* Core
**/
/**
* Create a Zepto collection object by performing a CSS selector, wrapping DOM nodes, or creating elements from an HTML string.
* @param selector
* @param context
* @return
**/
(selector: string, context?: any): ZeptoCollection;
/**
* @see ZeptoStatic();
* @param collection
**/
(collection: ZeptoCollection): ZeptoCollection;
/**
* @see ZeptoStatic();
* @param element
**/
(element: HTMLElement): ZeptoCollection;
/**
* @see ZeptoStatic();
* @param htmlString
**/
(htmlString: string): ZeptoCollection;
/**
* @see ZeptoStatic();
* @param attributes
**/
(htmlString: string, attributes: any): ZeptoCollection;
/**
* @see ZeptoStatic();
* @param object
**/
(object: any): ZeptoCollection; // window and document tests break without this
/**
* Turn a dasherized string into “camel case”. Doesn’t affect already camel-cased strings.
* @param str
* @return
**/
camelCase(str: string): string;
/**
* Check if the parent node contains the given DOM node. Returns false if both are the same node.
* @param parent
* @param node
* @return
**/
contains(parent: HTMLElement, node: HTMLElement): boolean;
/**
* Iterate over array elements or object key-value pairs. Returning false from the iterator function stops the iteration.
* @param collection
* @param fn
**/
each(collection: any[], fn: (index: number, item: any) => boolean): void;
/**
* @see ZeptoStatic.each
**/
each(collection: any, fn: (key: string, value: any) => boolean): void;
/**
* Extend target object with properties from each of the source objects, overriding the properties on target.
* By default, copying is shallow. An optional true for the first argument triggers deep (recursive) copying.
* @param target
* @param sources
* @return
**/
extend(target: any, ...sources: any[]): any;
/**
* @see ZeptoStatic.extend
* @param deep
**/
extend(deep: boolean, target: any, ...sources: any[]): any;
/**
* Zepto.fn is an object that holds all of the methods that are available on Zepto collections, such as addClass(), attr(), and other. Adding a function to this object makes that method available on every Zepto collection.
**/
fn: any;
/**
* Get a new array containing only the items for which the callback function returned true.
* @param items
* @param fn
* @return
**/
grep(items: any[], fn: (item: any) => boolean): any[];
/**
* Get the position of element inside an array, or -1 if not found.
* @param element
* @param array
* @param fromIndex
* @return
**/
inArray(element: any, array: any[], fromIndex?: number): number;
/**
* True if the object is an array.
* @param object
* @return
**/
isArray(object: any): boolean;
/**
* True if the object is a function.
* @param object
* @return
**/
isFunction(object: any): boolean;
/**
* True if the object is a “plain” JavaScript object, which is only true for object literals and objects created with new Object.
* @param object
* @return
**/
isPlainObject(object: any): boolean;
/**
* True if the object is a window object. This is useful for iframes where each one has its own window, and where these objects fail the regular obj === window check.
* @param object
* @return
**/
isWindow(object: any): boolean;
/**
* Iterate through elements of collection and return all results of running the iterator function, with null and undefined values filtered out.
* @param collection
* @param fn
* @return
**/
map(collection: any[], fn: (item: any, index: number) => any): any[];
/**
* Alias for the native JSON.parse method.
* @param str
* @retrun
**/
parseJSON(str: string): any;
/**
* Remove whitespace from beginning and end of a string; just like String.prototype.trim().
* @param str
* @return
**/
trim(str: string): string;
/**
* Get string type of an object. Possible types are: null undefined boolean number string function array date regexp object error.
* For other objects it will simply report “object”. To find out if an object is a plain JavaScript object, use isPlainObject.
* @param object
* @return
**/
type(object: any): string;
/**
* Event
**/
/**
* Create and initialize a DOM event of the specified type. If a properties object is given, use it to extend the new event object. The event is configured to bubble by default; this can be turned off by setting the bubbles property to false.
* An event initialized with this function can be triggered with trigger.
* @param type
* @param properties
* @return
**/
Event(type: string, properties: any): Event;
/**
* Get a function that ensures that the value of this in the original function refers to the context object. In the second form, the original function is read from the specific property of the context object.
**/
proxy(fn: Function, context: any): Function;
/**
* Ajax
**/
/**
* Perform an Ajax request. It can be to a local resource, or cross-domain via HTTP access control support in browsers or JSONP.
* Options:
* type (default: “GET”): HTTP request method (“GET”, “POST”, or other)
* url (default: current URL): URL to which the request is made
* data (default: none): data for the request; for GET requests it is appended to query string of the URL. Non-string objects will get serialized with $.param
* processData (default: true): whether to automatically serialize data for non-GET requests to string
* contentType (default: “application/x-www-form-urlencoded”): the Content-Type of the data being posted to the server (this can also be set via headers). Pass false to skip setting the default value.
* dataType (default: none): response type to expect from the server (“json”, “jsonp”, “xml”, “html”, or “text”)
* timeout (default: 0): request timeout in milliseconds, 0 for no timeout
* headers: object of additional HTTP headers for the Ajax request
* async (default: true): set to false to issue a synchronous (blocking) request
* global (default: true): trigger global Ajax events on this request
* context (default: window): context to execute callbacks in
* traditional (default: false): activate traditional (shallow) serialization of data parameters with $.param
* If the URL contains =? or dataType is “jsonp”, the request is performed by injecting a <script> tag instead of using XMLHttpRequest (see JSONP). This has the limitation of contentType, dataType, headers, and async not being supported.
* @param options
* @return
**/
ajax(options: ZeptoAjaxSettings): XMLHttpRequest;
/**
* Perform a JSONP request to fetch data from another domain.
* This method has no advantages over $.ajax and should not be used.
* @param options Ajax settings to use with JSONP call.
* @deprecated use $.ajax instead.
**/
ajaxJSONP(options: ZeptoAjaxSettings): XMLHttpRequest;
/**
* Object containing the default settings for Ajax requests. Most settings are described in $.ajax. The ones that are useful when set globally are:
* @example
* timeout (default: 0): set to a non-zero value to specify a default timeout for Ajax requests in milliseconds
* global (default: true): set to false to prevent firing Ajax events
* xhr (default: XMLHttpRequest factory): set to a function that returns instances of XMLHttpRequest (or a compatible object)
* accepts: MIME types to request from the server for specific dataType values:
* script: “text/javascript, application/javascript”
* json: “application/json”
* xml: “application/xml, text/xml”
* html: “text/html”
* text: “text/plain”
**/
ajaxSettings: ZeptoAjaxSettings;
/**
* Perform an Ajax GET request. This is a shortcut for the $.ajax method.
* @param url URL to send the HTTP GET request to.
* @param fn Callback function when the HTTP GET request is completed.
* @return The XMLHttpRequest object.
**/
get (url: string, fn: (data: any, status: string, xhr: XMLHttpRequest) => void ): XMLHttpRequest;
/**
* @see ZeptoStatic.get
* @param data See ZeptoAjaxSettings.data
**/
get (url: string, data: any, fn: (data: any, status: string, xhr: XMLHttpRequest) => void ): XMLHttpRequest;
/**
* Get JSON data via Ajax GET request. This is a shortcut for the $.ajax method.
* @param url URL to send the HTTP GET request to.
* @param fn Callback function when the HTTP GET request is completed.
* @return The XMLHttpRequest object.
**/
getJSON(url: string, fn: (data: any, status: string, xhr: XMLHttpRequest) => void ): XMLHttpRequest;
/**
* @see ZeptoStatic.getJSON
* @param data See ZeptoAjaxSettings.data
**/
getJSON(url: string, data: any, fn: (data: any, status: string, xhr: XMLHttpRequest) => void ): XMLHttpRequest;
/**
* Serialize an object to a URL-encoded string representation for use in Ajax request query strings and post data. If shallow is set, nested objects are not serialized and nested array values won’t use square brackets on their keys.
* Also accepts an array in serializeArray format, where each item has “name” and “value” properties.
* @param object Serialize this object to URL-encoded string representation.
* @param shallow Only serialize the first level of `object`.
* @return Seralized URL-encoded string representation of `object`.
**/
param(object: any, shallow?: boolean): string;
/**
* Perform an Ajax POST request. This is a shortcut for the $.ajax method.
* @param url URL to send the HTTP POST request to.
* @param fn Callback function when the HTTP POST request is completed.
* @return The XMLHttpRequest object.
**/
post(url: string, fn: (data: any, status: string, xhr: XMLHttpRequest) => void , dataType?: string): XMLHttpRequest;
/**
* @see ZeptoStatic.post
* @param data See ZeptoAjaxSettings.data
**/
post(url: string, data: any, fn: (data: any, status: string, xhr: XMLHttpRequest) => void , dataType?: string): XMLHttpRequest;
/**
* Effects
**/
/**
* Global settings for animations.
**/
fx: ZeptoEffects;
/**
* Detect
**/
/**
* The following boolean flags are set to true if they apply, if not they're either set to 'false' or 'undefined'. We recommend accessing them with `!!` prefixed to coerce to a boolean.
**/
os: {
/**
* OS version.
**/
version: string;
/**
* General device type
**/
phone: boolean;
tablet: boolean;
/**
* Specific OS
**/
ios: boolean;
android: boolean;
webos: boolean;
blackberry: boolean;
bb10: boolean;
rimtabletos: boolean;
/**
* Specific device type
**/
iphone: boolean;
ipad: boolean;
touchpad: boolean;
kindle: boolean;
};
/**
* The following boolean flags are set to true if they apply, if not they're either set to 'false' or 'undefined'. We recommend accessing them with `!!` prefixed to coerce to a boolean.
**/
browser: {
/**
* Browser version.
**/
version: string;
/**
* Specific browser
**/
chrome: boolean;
firefox: boolean;
silk: boolean;
playbook: boolean;
};
}
interface ZeptoEffects {
/**
* (default false in browsers that support CSS transitions): set to true to disable all animate() transitions.
**/
off: boolean;
/**
* An object with duration settings for animations.
* Change existing values or add new properties to affect animations that use a string for setting duration.
**/
speeds: ZeptoEffectsSpeeds;
}
interface ZeptoEffectsSpeeds {
/**
* Default = 400ms.
**/
_default: number;
/**
* Default = 200ms.
**/
fast: number;
/**
* Default = 600ms.
**/
slow: number;
}
interface ZeptoCollection {
/**
* Core
**/
/**
* Modify the current collection by adding the results of performing the CSS selector on the whole document, or, if context is given, just inside context elements.
* @param selector
* @param context
* @return Self object.
**/
add(selector: string, context?: any): ZeptoCollection;
/**
* Add class name to each of the elements in the collection. Multiple class names can be given in a space-separated string.
* @param name
* @return Self object.
**/
addClass(name: string): ZeptoCollection;
/**
* Add content to the DOM after each elements in the collection. The content can be an HTML string, a DOM node or an array of nodes.
* @param content
* @return Self object.
**/
after(content: string): ZeptoCollection;
/*
* @see ZeptoCollection.after
**/
after(content: HTMLElement): ZeptoCollection;
/**
* @see ZeptoCollection.after
**/
after(content: HTMLElement[]): ZeptoCollection;
/**
* @see ZeptoCollection.after
**/
after(content: ZeptoCollection): ZeptoCollection;
/**
* Append content to the DOM inside each individual element in the collection. The content can be an HTML string, a DOM node or an array of nodes.
* @param content
* @return Self object.
**/
append(content: string): ZeptoCollection;
/**
* @see ZeptoCollection.append
**/
append(content: HTMLElement): ZeptoCollection;
/**
* @see ZeptoCollection.append
**/
append(content: HTMLElement[]): ZeptoCollection;
/**
* @see ZeptoCollection.append
**/
append(content: ZeptoCollection): ZeptoCollection;
/**
* Append elements from the current collection to the target element. This is like append, but with reversed operands.
* @param target
* @return Self object.
**/
appendTo(target: string): ZeptoCollection;
/**
* @see ZeptoCollection.appendTo
**/
appendTo(target: HTMLElement): ZeptoCollection;
/**
* @see ZeptoCollection.appendTo
**/
appendTo(target: HTMLElement[]): ZeptoCollection;
/**
* @see ZeptoCollection.appendTo
**/
appendTo(target: ZeptoCollection): ZeptoCollection;
/**
* Read or set DOM attributes. When no value is given, reads specified attribute from the first element in the collection. When value is given, sets the attribute to that value on each element in the collection. When value is null, the attribute is removed (like with removeAttr). Multiple attributes can be set by passing an object with name-value pairs.
* To read DOM properties such as checked or selected, use prop.
* @param name
* @return
**/
attr(name: string): string;
/**
* @see ZeptoCollection.attr
* @param value
**/
attr(name: string, value: any): ZeptoCollection;
/**
* @see ZeptoCollection.attr
* @param fn
* @param oldValue
**/
attr(name: string, fn: (index: number, oldValue: any) => void ): ZeptoCollection;
/**
* @see ZeptoCollection.attr
* @param object
**/
attr(object: any): ZeptoCollection;
/**
* Add content to the DOM before each element in the collection. The content can be an HTML string, a DOM node or an array of nodes.
* @param content
* @return Self object.
**/
before(content: string): ZeptoCollection;
/**
* @see ZeptoCollection.before
**/
before(content: HTMLElement): ZeptoCollection;
/**
* @see ZeptoCollection.before
**/
before(content: HTMLElement[]): ZeptoCollection;
/**
* @see ZeptoCollection.before
**/
before(content: ZeptoCollection): ZeptoCollection;
/**
* Get immediate children of each element in the current collection. If selector is given, filter the results to only include ones matching the CSS selector.
* @param selector
* @return Children elements.
**/
children(selector?: string): ZeptoCollection;
/**
* Duplicate all elements in the collection via deep clone.
* (!) This method doesn't have an option for copying data and event handlers over to the new elements, as it has in jQuery.
* @return Clone of the self object.
**/
clone(): ZeptoCollection;
/**
* Traverse upwards from the current element to find the first element that matches the selector. If context node is given, consider only elements that are its descendants. This method is similar to parents(selector), but it only returns the first ancestor matched.
* If a Zepto collection or element is given, the resulting element will have to match one of the given elements instead of a selector.
* @param selector
* @param context
* @return Closest element from the selector and context.
**/
closest(selector: string, context?: any): ZeptoCollection;
/**
* Modify the collection by adding elements to it. If any of the arguments is an array, its elements are merged into the current collection.
* (!) This is a Zepto-provided method that is not part of the jQuery API.
* @param nodes
* @return Self object.
**/
concat(...nodes: any[]): ZeptoCollection;
/**
* Get the children of each element in the collection, including text and comment nodes.
* @return Children including text and comment nodes.
**/
contents(): ZeptoCollection;
/**
* Read or set CSS properties on DOM elements. When no value is given, returns the CSS property from the first element in the collection. When a value is given, sets the property to that value on each element of the collection. Multiple properties can be set by passing an object to the method.
* When a value for a property is blank (empty string, null, or undefined), that property is removed. When a unitless number value is given, “px” is appended to it for properties that require units.
* @param property
* @return
**/
css(property: string): any;
/**
* @see ZeptoCollection.css
* @param value
**/
css(property: string, value: any): ZeptoCollection;
/**
* @see ZeptoCollection.css
* @param properties
**/
css(properties: any): ZeptoCollection;
/**
* Read or write data-* DOM attributes. Behaves like attr, but prepends data- to the attribute name.
* When reading attribute values, the following conversions apply:
* “true”, “false”, and “null” are converted to corresponding types;
* number values are converted to actual numeric types;
* JSON values are parsed, if it’s valid JSON;
* everything else is returned as string.
* (!) Zepto's basic implementation of `data()` only stores strings. To store arbitrary objects, include the optional "data" module in your custom build of Zepto.
* @param name
* @return
**/
data(name: string): any;
/**
* @see ZeptoCollection.data
* @param value
**/
data(name: string, value: any): ZeptoCollection;
/**
* Iterate through every element of the collection. Inside the iterator function, this keyword refers to the current item (also passed as the second argument to the function). If the iterator function returns false, iteration stops.
* @param fn
* @param item
* @return Self object.
**/
each(fn: (index: number, item: any) => boolean): ZeptoCollection;
/**
* Clear DOM contents of each element in the collection.
* @return Self object.
**/
empty(): ZeptoCollection;
/**
* Get the item at position specified by index from the current collection.
* @param index
* @return Item specified by index in this collection.
**/
eq(index: number): ZeptoCollection;
/**
* Filter the collection to contain only items that match the CSS selector. If a function is given, return only elements for which the function returns a truthy value. Inside the function, the this keyword refers to the current element.
* For the opposite, see not.
* @param selector
* @return Filtered collection.
**/
filter(selector: string): ZeptoCollection;
/**
* @see ZeptoCollection.filter
* @param fn
**/
filter(fn: (index: number) => boolean): ZeptoCollection;
/**
* Find elements that match CSS selector executed in scope of nodes in the current collection.
* If a Zepto collection or element is given, filter those elements down to only ones that are descendants of element in the current collection.
* @param selector
* @return Found items.
**/
find(selector: string): ZeptoCollection;
/**
* @see ZeptoCollection.find
* @param collection
**/
find(collection: ZeptoCollection): ZeptoCollection;
/**
* @see ZeptoCollection.find
* @param element
**/
find(element: Element): ZeptoCollection;
/**
* Get the first element of the current collection.
* @return First element in the current collection.
**/
first(): ZeptoCollection;
/**
* Iterate through every element of the collection. Similar to each, but the arguments for the iterator functions are different, and returning false from the iterator won’t stop the iteration.
* (!) This is a Zepto-provided method that is not part of the jQuery API.
* @param fn
* @return
**/
forEach(fn: (item: any, index: number, array: any[]) => void ): ZeptoCollection;
/**
* Get all elements or a single element from the current collection. When no index is given, returns all elements in an ordinary array. When index is specified, return only the element at that position. This is different than eq in the way that the returned node is not wrapped in a Zepto collection.
* @return
**/
get (): HTMLElement[];
/**
* @see ZeptoCollection.get
* @param index
**/
get (index: number): HTMLElement;
/**
* Filter the current collection to include only elements that have any number of descendants that match a selector, or that contain a specific DOM node.
* @param selector
* @return
**/
has(selector: string): ZeptoCollection;
/**
* @see ZeptoCollection.has
* @param node
**/
has(node: HTMLElement): ZeptoCollection;
/**
* Check if any elements in the collection have the specified class.
* @param name
* @return
**/
hasClass(name: string): boolean;
/**
* Get the height of the first element in the collection; or set the height of all elements in the collection.
* @return
**/
height(): number;
/**
* @see ZeptoCollection.height
* @param value
**/
height(value: number): ZeptoCollection;
/**
* @see ZeptoCollection.height
* @param fn
**/
height(fn: (index: number, oldHeight: number) => void ): ZeptoCollection;
/**
* Hide elements in this collection by setting their display CSS property to none.
* @return
**/
hide(): ZeptoCollection;
/**
* Get or set HTML contents of elements in the collection. When no content given, returns innerHTML of the first element. When content is given, use it to replace contents of each element. Content can be any of the types described in append.
* @return
**/
html(): string;
/**
* @see ZeptoCollection.html
* @param content
**/
html(content: string): ZeptoCollection;
/**
* @see ZeptoCollection.html
* @param content
**/
html(content: HTMLElement): ZeptoCollection;
/**
* @see ZeptoCollection.html
* @param content
**/
html(content: HTMLElement[]): ZeptoCollection;
/**
* @see ZeptoCollection.html
* @param fn
**/
html(fn: (index: number, oldHtml: string) => void ): ZeptoCollection;
/**
* Get the position of an element. When no element is given, returns position of the current element among its siblings. When an element is given, returns its position in the current collection. Returns -1 if not found.
* @param element
* @return
**/
index(element?: string): number;
/**
* @see ZeptoCollection.index
* @param element
**/
index(element?: HTMLElement): number;
/**
* @see ZeptoCollection.index
* @param element
**/
index(element?: any): number; // not sure so leaving in for now
/**
* Get the position of an element in the current collection. If fromIndex number is given, search only from that position onwards. Returns the 0-based position when found and -1 if not found. Use of index is recommended over this method.
* (!) This is a Zepto-provided method that is not part of the jQuery API.
* @see ZeptoCollection.index
* @param element
* @param fromIndex
* @return
**/
indexOf(element: string, fromIndex?: number): number;
/**
* @see ZeptoCollection.indexOf
* @param element
**/
indexOf(element: HTMLElement, fromIndex?: number): number;
/**
* @see ZeptoCollection.indexOf
* @param element
**/
indexOf(element: any, fromIndex?: number): number; // not sure so leaving in for now
/**
* Insert elements from the current collection after the target element in the DOM. This is like after, but with reversed operands.
* @param target
* @return
**/
insertAfter(target: string): ZeptoCollection;
/**
* @see ZeptoCollection.insertAfter
* @param target
**/
insertAfter(target: HTMLElement): ZeptoCollection;
/**
* Insert elements from the current collection before each of the target elements in the DOM. This is like before, but with reversed operands.
* @param target
* @return
**/
insertBefore(target: string): ZeptoCollection;
/**
* @see ZeptoCollection.insertBefore
* @param target
**/
insertBefore(target: HTMLElement): ZeptoCollection;
/**
* Check if the first element of the current collection matches the CSS selector. For basic support of jQuery’s non-standard pseudo-selectors such as :visible, include the optional “selector” module.
* (!) jQuery CSS extensions are not supported. The optional "selector" module only provides limited support for few of the most used ones.
* @param selector
* @return
**/
is(selector?: string): boolean;
/**
* Get the last element of the current collection.
* @return
**/
last(): ZeptoCollection;
/**
* Iterate through all elements and collect the return values of the iterator function. Inside the iterator function, this keyword refers to the current item (also passed as the second argument to the function).
* Returns a collection of results of iterator function, with null and undefined values filtered out.
* @param fn
* @return
**/
map(fn: (index: number, item: any) => any): ZeptoCollection;
/**
* Get the next sibling—optinally filtered by selector—of each element in the collection.
* @param selector
* @return
**/
next(selector?: string): ZeptoCollection;
/**
* Filter the current collection to get a new collection of elements that don’t match the CSS selector. If another collection is given instead of selector, return only elements not present in it. If a function is given, return only elements for which the function returns a falsy value. Inside the function, the this keyword refers to the current element.
* For the opposite, see filter.
* @param selector
* @return
**/
not(selector: string): ZeptoCollection;
/**
* @see ZeptoCollection.not
* @param collection
**/
not(collection: ZeptoCollection): ZeptoCollection;
/**
* @see ZeptoCollection.not
* @param fn
**/
not(fn: (index: number) => boolean): ZeptoCollection;
/**
* Get position of the element in the document. Returns an object with properties: top, left, width and height.
* When given an object with properties left and top, use those values to position each element in the collection relative to the document.
* @return
**/
offset(): ZeptoCoordinates;
/**
* @see ZeptoCollection.offset
* @param coordinates
**/
offset(coordinates: ZeptoCoordinates): ZeptoCollection;
/**
* @see ZeptoCollection.offset
* @param fn
**/
offset(fn: (index: number, oldOffset: number) => void ): ZeptoCollection;
/**
* Find the first ancestor element that is positioned, meaning its CSS position value is “relative”, “absolute” or “fixed”.
* @return
**/
offsetParent(): ZeptoCollection;
/**
* Get immediate parents of each element in the collection. If CSS selector is given, filter results to include only ones matching the selector.
* @param selector
* @return
**/
parent(selector?: string): ZeptoCollection;
/**
* Get all ancestors of each element in the collection. If CSS selector is given, filter results to include only ones matching the selector.
* To get only immediate parents, use parent. To only get the first ancestor that matches the selector, use closest.
* @param selector
* @return
**/
parents(selector?: string): ZeptoCollection;
/**
* Get values from a named property of each element in the collection, with null and undefined values filtered out.
* (!) This is a Zepto-provided method that is not part of the jQuery API.
* @param property
* @return
**/
pluck(property: string): string[];
/**
* Get the position of the first element in the collection, relative to the offsetParent. This information is useful when absolutely positioning an element to appear aligned with another.
* Returns an object with properties: top, left.
* @return
**/
position(): ZeptoPosition;
/**
* Prepend content to the DOM inside each element in the collection. The content can be an HTML string, a DOM node or an array of nodes.
* @param content
* @return
**/
prepend(content: string): ZeptoCollection;
/**
* @see ZeptoCollection.prepend
* @param content
**/
prepend(content: HTMLElement): ZeptoCollection;
/**
* @see ZeptoCollection.prepend
* @param content
**/
prepend(content: HTMLElement[]): ZeptoCollection;
/**
* @see ZeptoCollection.prepend
* @param content
**/
prepend(content: ZeptoCollection): ZeptoCollection;
/**
* Prepend elements of the current collection inside each of the target elements. This is like prepend, only with reversed operands.
* @param content
* @return
**/
prependTo(content: string): ZeptoCollection;
/**
* @see ZeptoCollection.prependTo
* @param content
**/
prependTo(content: HTMLElement): ZeptoCollection;
/**
* @see ZeptoCollection.prependTo
* @param content
**/
prependTo(content: HTMLElement[]): ZeptoCollection;
/**
* @see ZeptoCollection.prependTo
* @param content
**/
prependTo(content: ZeptoCollection): ZeptoCollection;
/**
* Get the previous sibling—optionally filtered by selector—of each element in the collection.
* @param selector
* @return
**/
prev(selector?: string): ZeptoCollection;
/**
* Read or set properties of DOM elements. This should be preferred over attr in case of reading values of properties that change with user interaction over time, such as checked and selected.
* @param prop
* @return
**/
prop(name: string): any;
/**
* @see ZeptoCollection.Prop
* @param value
**/
prop(name: string, value: any): ZeptoCollection;
/**
* @see ZeptoCollection.Prop
* @param fn
**/
prop(name: string, fn: (index: number, oldValue: any) => void ): ZeptoCollection;
/**
* Add elements to the end of the current collection.
* (!) This is a Zepto-provided method that is not part of the jQuery API.
* @param elements
* @return
**/
push(...elements: any[]): ZeptoCollection;
/**
* Attach an event handler for the “DOMContentLoaded” event that fires when the DOM on the page is ready. It’s recommended to use the $() function instead of this method.
* @param fn
* @return
**/
ready(fn: ($: ZeptoStatic) => void ): ZeptoCollection;
/**
* Identical to Array.reduce that iterates over current collection.
* (!) This is a Zepto-provided method that is not part of the jQuery API.
* @param fn
* @return
**/
reduce(fn: (memo: any, item: any, index: number, array: any[], initial: any) => any): any;
/**
* Remove elements in the current collection from their parent nodes, effectively detaching them from the DOM.
* @return
**/
remove(): ZeptoCollection;
/**
* Remove the specified attribute from all elements in the collection.
* @param name
* @return
**/
removeAttr(name: string): ZeptoCollection;
/**
* Remove the specified class name from all elements in the collection. When the class name isn’t given, remove all class names. Multiple class names can be given in a space-separated string.
* @param name
* @return
**/
removeClass(name?: string): ZeptoCollection;
/**
* @see ZeptoCollection.removeClass
* @param fn
**/
removeClass(fn: (index: number, oldClassName: string) => void ): ZeptoCollection;
/**
* Replace each element in the collection—both its contents and the element itself—with the new content. Content can be of any type described in before.
* @param content
* @return
**/
replaceWith(content: string): ZeptoCollection;
/**
* @see ZeptoCollection.replacewith
* @param content
**/
replaceWith(content: HTMLElement): ZeptoCollection;
/**
* @see ZeptoCollection.replacewith
* @param content
**/
replaceWith(content: HTMLElement[]): ZeptoCollection;
/**
* Gets the value of how many pixels were scrolled so far on window or scrollable element on the page.
* @return
**/
scrollTop(): number;
/**
* Restore the default value for the “display” property of each element in the array, effectively showing them if they were hidden with hide.
* @return
**/
show(): ZeptoCollection;
/**
* Get all sibling nodes of each element in the collection. If CSS selector is specified, filter the results to contain only elements that match the selector.
* @param selector
* @return
**/
siblings(selector?: string): ZeptoCollection;
/**
* Get the number of elements in this collection.
* @return
**/
size(): number;
/**
* Get the number of elements in this collection.
**/
length: number;
/**
* Extract the subset of this array, starting at start index. If end is specified, extract up to but not including end index.
* @param start
* @param end
* @return
**/
slice(start?: number, end?: number): ZeptoCollection[];
/**
* Get or set the text content of elements in the collection. When no content is given, returns the text content of the first element in the collection. When content is given, uses it to replace the text contents of each element in the collection. This is similar to html, with the exception it can’t be used for getting or setting HTML.
* @return
**/
text(): string;
/**
* @see ZeptoCollection.text
* @param content
* @return
**/
text(content: string): ZeptoCollection;
/**
* Toggle between showing and hiding each of the elements, based on whether the first element is visible or not. If setting is present, this method behaves like show if setting is truthy or hide otherwise.
* @param setting
* @return
**/
toggle(setting?: boolean): ZeptoCollection;
/**
* Toggle given class names (space-separated) in each element in the collection. The class name is removed if present on an element; otherwise it’s added. If setting is present, this method behaves like addClass if setting is truthy or removeClass otherwise.
* @param names
* @param setting
* @return
**/
toggleClass(names: string, setting?: boolean): ZeptoCollection;
/**
* @see ZeptoCollection.toggleClass
* @param fn
**/
toggleClass(fn: (index: number, oldClassNames: string) => void , setting?: boolean): ZeptoCollection;
/**
* Remove immediate parent nodes of each element in the collection and put their children in their place. Basically, this method removes one level of ancestry while keeping current elements in the DOM.
* @return
**/
unwrap(): ZeptoCollection;
/**
* Get or set the value of form controls. When no value is given, return the value of the first element. For <select multiple>, an array of values is returend. When a value is given, set all elements to this value.
* @return
**/
val(): string;
/**
* @see ZeptoCollection.val
* @param value
* @return
**/
val(value: any): ZeptoCollection;
/**
* @see ZeptoCollection.val
* @param fn
**/
val(fn: (index: number, oldValue: any) => void ): ZeptoCollection;
/**
* Get the width of the first element in the collection; or set the width of all elements in the collection.
* @return
**/
width(): number;
/**
* @see ZeptoCollection.width
* @param value
* @return
**/
width(value: number): ZeptoCollection;
/**
* @see ZeptoCollection.width
* @param fn
**/
width(fn: (index: number, oldWidth: number) => void ): ZeptoCollection;
/**
* Wrap each element of the collection separately in a DOM structure. Structure can be a single element or several nested elements, and can be passed in as a HTML string or DOM node, or as a function that is called for each element and returns one of the first two types.
* Keep in mind that wrapping works best when operating on nodes that are part of the DOM. When calling wrap() on a new element and then inserting the result in the document, the element will lose the wrapping.
* @param structure
* @return
**/
wrap(structure: string): ZeptoCollection;
/**
* @see ZeptoCollection.wrap
* @param structure
**/
wrap(structure: HTMLElement): ZeptoCollection;
/**
* @see ZeptoCollection.wrap
* @param fn
**/
wrap(fn: (index: number) => string): ZeptoCollection;
/**
* Wrap all elements in a single structure. Structure can be a single element or several nested elements, and can be passed in as a HTML string or DOM node.
* @param structure
* @return
**/
wrapAll(structure: string): ZeptoCollection;
/**
* @see ZeptoCollection.wrapAll
* @param structure
**/
wrapAll(structure: HTMLElement): ZeptoCollection;
/**
* Wrap the contents of each element separately in a structure. Structure can be a single element or several nested elements, and can be passed in as a HTML string or DOM node, or as a function that is called for each element and returns one of the first two types.
* @param structure
* @return
**/
wrapInner(structure: string): ZeptoCollection;
/**
* @see ZeptoCollection.wrapInner
* @param structure
**/
wrapInner(structure: HTMLElement): ZeptoCollection;
/**
* @see ZeptoCollection.wrapInner
* @param fn
**/
wrapInner(fn: (index: number) => string): ZeptoCollection;
/**
* Event
**/
/**
* Attach an event handler to elements.
* @deprecated use ZeptoCollection.on instead.
* @param type
* @param fn
* @return
**/
bind(type: string, fn: ZeptoEventHandler): ZeptoCollection;
/**
* Attach an event handler that is only triggered when the event originated from a node that matches a selector.
* @depcreated use ZeptoCollection.on instead.
* @param selector
* @param type
* @param fn
* @return
**/
delegate(selector: string, type: string, fn: ZeptoEventHandler): ZeptoCollection;
/**
* Detach event handler added by live.
* @deprecated use ZeptoCollection.off instead.
* @param type
* @param fn
* @return
**/
die(type: string, fn: ZeptoEventHandler): ZeptoCollection;
/**
* @see ZeptoCollection.die
* @deprecated use ZeptoCollection.off instead.
* @param types
**/
die(types: any): ZeptoCollection;
/**
* Like delegate where the selector is taken from the current collection.
* @deprepcated use ZeptoCollection.on instead.
* @param type
* @param fn
* @return
**/
live(type: string, fn: ZeptoEventHandler): ZeptoCollection;
/**
* Detach event handlers added with on. To detach a specific event handler, the same function must be passed that was used for on(). Otherwise, just calling this method with an event type with detach all handlers of that type. When called without arguments, it detaches all event handlers registered on current elements.
* @param type
* @param selector
* @param fn
* @return
**/
off(type: string, selector: string, fn: ZeptoEventHandler): ZeptoCollection;
/**
* @see ZeptoCollection.off
**/
off(type: string, fn: ZeptoEventHandler): ZeptoCollection;
/**
* @see ZeptoCollection.off
**/
off(type: string, selector?: string): ZeptoCollection;
/**
* @see ZeptoCollection.off
**/
off(): ZeptoCollection;
/**
* @see ZeptoCollection.off
* @param events
**/
off(events: ZeptoEventHandlers, selector?: string): ZeptoCollection;
/**
* Add event handlers to the elements in collection. Multiple event types can be passed in a space-separated string, or as an object where event types are keys and handlers are values. If a CSS selector is given, the handler function will only be called when an event originates from an element that matches the selector.
* Event handlers are executed in the context of the element to which the handler is attached, or the matching element in case a selector is provided. When an event handler returns false, preventDefault() is called for the current event, preventing the default browser action such as following links.
* @param type
* @param selector
* @param fn
* @return
**/
on(type: string, selector: string, fn: ZeptoEventHandler): ZeptoCollection;
/**
* @see ZeptoCollection.on
**/
on(type: string, fn: ZeptoEventHandler): ZeptoCollection;
// todo: v0.9 will introduce string literals
//on(type: 'ajaxStart', fn: ZeptoAjaxStartEvent): ZeptoCollection;
//on(type: 'ajaxBeforeSend', fn: ZeptoAjaxBeforeSendEvent): ZeptoCollection;
//on(type: 'ajaxSend', fn: ZeptoAjaxSendEvent): ZeptoCollection;
//on(type: 'ajaxSuccess', fn: ZeptoAjaxSuccessEvent): ZeptoCollection;
//on(type: 'ajaxError', fn: ZeptoAjaxErrorEvent): ZeptoCollection;
//on(type: 'ajaxComplete', fn: ZeptoAjaxCompleteEvent): ZeptoCollection;
//on(type: 'ajaxStop', fn: ZeptoAjaxStopEvent): ZeptoCollection;
/**
* @see ZeptoCollection.on
* @param events
**/
on(events: ZeptoEventHandlers, selector?: string): ZeptoCollection;
/**
* Adds an event handler that removes itself the first time it runs, ensuring that the handler only fires once.
* @param type
* @param fn
* @return
**/
one(type: string, fn: ZeptoEventHandler ): ZeptoCollection;
/**
* @see ZeptoCollection.one
* @param events
**/
one(events: ZeptoEventHandlers): ZeptoCollection;
/**
* Trigger the specified event on elements of the collection. Event can either be a string type, or a full event object obtained with $.Event. If a data array is given, it is passed as additional arguments to event handlers.
* (!) Zepto only supports triggering events on DOM elements.
* @param event
* @param data
* @return
**/
trigger(event: string, data?: any[]): ZeptoCollection;
/**
* Like trigger, but triggers only event handlers on current elements and doesn’t bubble.
* @param event
* @param data
* @return
**/
triggerHandler(event: string, data?: any[]): ZeptoCollection;
/**
* Detach event handler added with bind.
* @deprecated use ZeptoCollection.off instead.
* @param type
* @param fn
* @return
**/
unbind(type: string, fn: ZeptoEventHandler): ZeptoCollection;
/**
* Detach event handler added with delegate.
* @deprecated use ZeptoCollection.off instead.
* @param selector
* @param type
* @param fn
* @return
**/
undelegate(selector: string, type: string, fn: ZeptoEventHandler): ZeptoCollection;
focusin(): ZeptoCollection;
focusin(fn: ZeptoEventHandler): ZeptoCollection;
focusout(): ZeptoCollection;
focusout(fn: ZeptoEventHandler): ZeptoCollection;
load(): ZeptoCollection;
load(fn: ZeptoEventHandler): ZeptoCollection;
resize(): ZeptoCollection;
resize(fn: ZeptoEventHandler): ZeptoCollection;
scroll(): ZeptoCollection;
scroll(fn: ZeptoEventHandler): ZeptoCollection;
unload(): ZeptoCollection;
unload(fn: ZeptoEventHandler): ZeptoCollection;
click(): ZeptoCollection;
click(fn: ZeptoEventHandler): ZeptoCollection;
dblclick(): ZeptoCollection;
dblclick(fn: ZeptoEventHandler): ZeptoCollection;
mousedown(): ZeptoCollection;
mousedown(fn: ZeptoEventHandler): ZeptoCollection;
mouseup(): ZeptoCollection;
mouseup(fn: ZeptoEventHandler): ZeptoCollection;
mousemove(): ZeptoCollection;
mousemove(fn: ZeptoEventHandler): ZeptoCollection;
mouseover(): ZeptoCollection;
mouseover(fn: ZeptoEventHandler): ZeptoCollection;
mouseout(): ZeptoCollection;
mouseout(fn: ZeptoEventHandler): ZeptoCollection;
mouseenter(): ZeptoCollection;
mouseenter(fn: ZeptoEventHandler): ZeptoCollection;
mouseleave(): ZeptoCollection;
mouseleave(fn: ZeptoEventHandler): ZeptoCollection;
change(): ZeptoCollection;
change(fn: ZeptoEventHandler): ZeptoCollection;
select(): ZeptoCollection;
select(fn: ZeptoEventHandler): ZeptoCollection;
keydown(): ZeptoCollection;
keydown(fn: ZeptoEventHandler): ZeptoCollection;
keypress(): ZeptoCollection;
keypress(fn: ZeptoEventHandler): ZeptoCollection;
keyup(): ZeptoCollection;
keyup(fn: ZeptoEventHandler): ZeptoCollection;
error(): ZeptoCollection;
error(fn: ZeptoEventHandler): ZeptoCollection;
focus(): ZeptoCollection;
focus(fn: ZeptoEventHandler): ZeptoCollection;
blur(): ZeptoCollection;
blur(fn: ZeptoEventHandler): ZeptoCollection;
/**
* Ajax
**/
/**
* Set the html contents of the current collection to the result of a GET Ajax call to the given URL. Optionally, a CSS selector can be specified in the URL, like so, to use only the HTML content matching the selector for updating the collection:
* $('#some_element').load('/foo.html #bar')
* If no CSS selector is given, the complete response text is used instead.
* Note that any JavaScript blocks found are only executed in case no selector is given.
* @param url URL to send the HTTP GET request to.
* @param fn Callback function when the HTTP GET request is completed.
* @return Self object.
* @example
* $('#some_element').load('/foo.html #bar')
**/
load(url: string, fn?: (data: any, status: string, xhr: XMLHttpRequest) => void ): ZeptoCollection;
/**
* Form
**/
/**
* Serialize form values to an URL-encoded string for use in Ajax post requests.
* @return Seralized form values in URL-encoded string.
**/
serialize(): string;
/**
* Serialize form into an array of objects with name and value properties. Disabled form controls, buttons, and unchecked radio buttons/checkboxes are skipped. The result doesn’t include data from file inputs.
* @return Array with name value pairs from the Form.
**/
serializeArray(): any[];
/**
* Trigger or attach a handler for the submit event. When no function given, trigger the “submit” event on the current form and have it perform its submit action unless preventDefault() was called for the event.
* When a function is given, this simply attaches it as a handler for the “submit” event on current elements.
* @return Self object.
**/
submit(): ZeptoCollection;
/**
* @see ZeptoCollection.submit
* @param fn Handler for the 'submit' event on current elements.
* @return Self object.
**/
submit(fn: (e: any) => void ): ZeptoCollection;
/**
* Effects
**/
/**
* Smoothly transition CSS properties of elements in the current collection.
* @param properties object that holds CSS values to animate to; or CSS keyframe animation name.
* Zepto also supports the following CSS transform porperties:
* translate(X|Y|Z|3d)
* rotate(X|Y|Z|3d)
* scale(X|Y|Z)
* matrix(3d)
* perspective
* skew(X|Y)
* @param duration (default 400): duration in milliseconds, or a string:
* fast (200 ms)
* slow (600 ms)
* any custom property of $.fx.speeds
* @param easing (default linear): specifies the type of animation easing to use, one of:
* ease
* linear
* ease-in
* ease-out
* ease-in-out
* cubic-bezier(x1, y1, x2, y2)
* @param complete Callback function when the animation has completed.
* @return Self object.
* @note If the duration is 0 or $.fx.off is true (default in a browser that doesn’t support CSS transitions), animations will not be executed; instead the target values will take effect instantly. Similarly, when the target CSS properties match the current state of the element, there will be no animation and the complete function won’t be called.
* If the first argument is a string instead of object, it is taken as a CSS keyframe animation name.
* @note Zepto exclusively uses CSS transitions for effects and animation. jQuery easings are not supported. jQuery's syntax for relative changes ("=+10px") is not supported. See the spec for a list of animatable properties (http://www.w3.org/TR/css3-transitions/#animatable-properties-). Browser support may vary, so be sure to test in all browsers you want to support.
**/
animate(properties: any, duration?: number, easing?: string, complete?: () => void ): ZeptoCollection;
/**
* @see ZeptoCollection.animate
* @param options Animation options.
**/
animate(properties: any, options: ZeptoAnimateSettings): ZeptoCollection;
}
interface ZeptoAjaxSettings {
type?: string;
url?: string;
data?: any;
processData?: boolean;
contentType?: string;
mimeType?: string;
dataType?: string;
jsonp?: string;
jsonpCallback?: any; // string or Function
timeout?: number;
headers?: { [key: string]: string };
async?: boolean;
global?: boolean;
context?: any;
traditional?: boolean;
cache?: boolean;
xhrFields?: { [key: string]: any };
username?: string;
password?: string;
beforeSend?: (xhr: XMLHttpRequest, settings: ZeptoAjaxSettings) => boolean;
success?: (data: any, status: string, xhr: XMLHttpRequest) => void;
error?: (xhr: XMLHttpRequest, errorType: string, error: Error) => void;
complete?: (xhr: XMLHttpRequest, status: string) => void;
}
// Fired if no other ajax requests are currently active
// event name: ajaxStart
interface ZeptoAjaxStartEvent {
(): void;
}
// Before sending the request, can be cancelled
// event name: ajaxBeforeSend
interface ZeptoAjaxBeforeSendEvent {
(xhr: XMLHttpRequest, options: ZeptoAjaxSettings): void;
}
// Like ajaxBeforeSend, but not cancellable
// event name: ajaxSend
interface ZeptoAjaxSendEvent {
(xhr: XMLHttpRequest, options: ZeptoAjaxSettings): void;
}
// When the response is success
// event name: ajaxSuccess
interface ZeptoAjaxSuccessEvent {
(xhr: XMLHttpRequest, options: ZeptoAjaxSettings, data: any): void;
}
// When there was an error
// event name: ajaxError
interface ZeptoAjaxErrorEvent {
(xhr: XMLHttpRequest, options: ZeptoAjaxSettings, error: Error): void;
}
// After request has completed, regardless of error or success
// event name: ajaxComplete
interface ZeptoAjaxCompleteEvent {
(xhr: XMLHttpRequest, options: ZeptoAjaxSettings): void;
}
// Fired if this was the last active Ajax request.
// event name: ajaxStop
interface ZeptoAjaxStopEvent {
(): void;
}
interface ZeptoAnimateSettings {
duration?: number;
easing?: string;
complete?: () => void;
}
interface ZeptoPosition {
top: number;
left: number;
}
interface ZeptoCoordinates extends ZeptoPosition {
width: number;
height: number;
}
interface ZeptoEventHandlers {
[key: string]: ZeptoEventHandler;
}
interface ZeptoEventHandler {
(e: Event, ...args: any[]): any;
}
declare var Zepto: (fn: ($: ZeptoStatic) => void) => void;
declare var $: ZeptoStatic; | the_stack |
import BigNumber from 'bignumber.js';
import _ from 'lodash';
import { INTEGERS } from '../src/lib/Constants';
import { BaseValue, Index, Price, TxResult, address } from '../src/lib/types';
import { mineAvgBlock } from './helpers/EVM';
import { expect, expectBN, expectBaseValueEqual } from './helpers/Expect';
import initializePerpetual from './helpers/initializePerpetual';
import { ITestContext, perpetualDescribe } from './helpers/perpetualDescribe';
import { buy, sell } from './helpers/trade';
import { expectBalances, mintAndDeposit, expectMarginBalances, expectContractSurplus } from './helpers/balances';
const marginAmount = new BigNumber(1000);
const positionSize = new BigNumber(12);
let long: address;
let short: address;
let otherAccountA: address;
let otherAccountB: address;
let otherAccountC: address;
async function init(ctx: ITestContext): Promise<void> {
await initializePerpetual(ctx);
long = ctx.accounts[2];
short = ctx.accounts[3];
otherAccountA = ctx.accounts[4];
otherAccountB = ctx.accounts[5];
otherAccountC = ctx.accounts[6];
// Set up initial balances:
// +---------+--------+----------+
// | account | margin | position |
// |---------+--------+----------+
// | long | 0 | 12 |
// | short | 2000 | -12 |
// +---------+--------+----------+
await Promise.all([
ctx.perpetual.testing.oracle.setPrice(new Price(100)),
mintAndDeposit(ctx, long, marginAmount),
mintAndDeposit(ctx, short, marginAmount),
]);
const txResult = await buy(ctx, long, short, positionSize, marginAmount);
// Sanity check balances.
await expectBalances(
ctx,
txResult,
[long, short],
[0, 2000],
[12, -12],
);
}
perpetualDescribe('P1Settlement', init, (ctx: ITestContext) => {
describe('_loadContext()', () => {
it('Updates the global index for a positive funding rate', async () => {
await ctx.perpetual.testing.funder.setFunding(new BaseValue('0.005'));
let txResult = await triggerIndexUpdate(otherAccountA);
await expectIndexUpdated(txResult, new BaseValue('0.5'));
txResult = await triggerIndexUpdate(otherAccountA);
await expectIndexUpdated(txResult, new BaseValue('1.0'));
});
it('Updates the global index for a negative funding rate', async () => {
await ctx.perpetual.testing.funder.setFunding(new BaseValue('-0.005'));
let txResult = await triggerIndexUpdate(otherAccountA);
await expectIndexUpdated(txResult, new BaseValue('-0.5'));
txResult = await triggerIndexUpdate(otherAccountA);
await expectIndexUpdated(txResult, new BaseValue('-1.0'));
});
it('Updates the global index over time with a variable funding rate and price', async () => {
await ctx.perpetual.testing.funder.setFunding(new BaseValue('0.000001'));
let txResult = await triggerIndexUpdate(otherAccountA);
await expectIndexUpdated(txResult, new BaseValue('0.0001'));
await ctx.perpetual.testing.funder.setFunding(new BaseValue('4'));
txResult = await triggerIndexUpdate(otherAccountA);
await expectIndexUpdated(txResult, new BaseValue('400.0001'));
await ctx.perpetual.testing.oracle.setPrice(new Price('40'));
txResult = await triggerIndexUpdate(otherAccountA);
await expectIndexUpdated(txResult, new BaseValue('560.0001'));
await ctx.perpetual.testing.funder.setFunding(new BaseValue('-10.5'));
txResult = await triggerIndexUpdate(otherAccountA);
await expectIndexUpdated(txResult, new BaseValue('140.0001'));
await ctx.perpetual.testing.oracle.setPrice(new Price('0.00001'));
txResult = await triggerIndexUpdate(otherAccountA);
await expectIndexUpdated(txResult, new BaseValue('139.999995'));
});
it('Maintains solvency despite rounding errors in interest calculation', async () => {
// Set up balances:
// +---------------+--------+----------+
// | account | margin | position |
// |---------------+--------+----------+
// | otherAccountA | 10 | 7 |
// | otherAccountB | 10 | -3 |
// | otherAccountC | 10 | -4 |
// +---------------+--------+----------+
await Promise.all([
ctx.perpetual.testing.oracle.setPrice(new Price(1)),
mintAndDeposit(ctx, otherAccountA, 10),
mintAndDeposit(ctx, otherAccountB, 10),
mintAndDeposit(ctx, otherAccountC, 10),
]);
await buy(ctx, otherAccountA, otherAccountB, 3, 0);
let txResult = await buy(ctx, otherAccountA, otherAccountC, 4, 0);
// Check balances.
await expectBalances(
ctx,
txResult,
[otherAccountA, otherAccountB, otherAccountC],
[10, 10, 10],
[7, -3, -4],
false,
);
// Time period 1, global index is 0.7
//
// Settle account A, paying 5 margin in interest. New balances:
// +---------------+--------+----------+-------------+--------------+
// | account | margin | position | local index | interest due |
// |---------------+--------+----------+-------------+--------------+
// | otherAccountA | 5 | 7 | 0.7 | 0 |
// | otherAccountB | 10 | -3 | 0 | 2.1 |
// | otherAccountC | 10 | -4 | 0 | 2.8 |
// +---------------+--------+----------+-------------+--------------+
await ctx.perpetual.testing.funder.setFunding(new BaseValue('0.7'));
txResult = await triggerIndexUpdate(otherAccountA);
await expectMarginBalances(ctx, txResult, [otherAccountA], [5], false);
// Time period 1, global index is 1.4
//
// Settle all accounts. New balances:
// +---------------+--------+----------+-------------+--------------+
// | account | margin | position | local index | interest due |
// |---------------+--------+----------+-------------+--------------+
// | otherAccountA | 0 | 7 | 1.4 | 0 |
// | otherAccountB | 14 | -3 | 1.4 | 0 |
// | otherAccountC | 15 | -4 | 1.4 | 0 |
// +---------------+--------+----------+-------------+--------------+
await triggerIndexUpdate(otherAccountA);
await ctx.perpetual.testing.funder.setFunding(new BaseValue(0));
await triggerIndexUpdate(otherAccountB);
txResult = await triggerIndexUpdate(otherAccountC);
// Check balances.
await expectBalances(
ctx,
txResult,
[otherAccountA, otherAccountB, otherAccountC],
[0, 14, 15],
[7, -3, -4],
false,
);
await expectContractSurplus(
ctx,
[long, short, otherAccountA, otherAccountB, otherAccountC],
1,
);
});
});
describe('_settleAccount()', () => {
it('Settles interest accumulated on an account', async () => {
// Sequence of operations:
// +---------------+-------------+-----------+--------------+------------+
// | operation | long margin | long pos. | short margin | short pos. |
// |---------------+-------------+-----------+--------------+------------|
// | deposit | 1000 | 0 | 1000 | 0 |
// | trade | 0 | 12 | 2000 | -12 |
// | settle(long) | -50 | 12 | 2000 | -12 |
// | settle(short) | 0 | 12 | 2050 | -12 |
// +---------------+-------------+-----------+--------------+------------+
// Accumulate interest and settle the long account.
await ctx.perpetual.testing.funder.setFunding(new BaseValue('0.05'));
let txResult = await triggerIndexUpdate(long);
await ctx.perpetual.testing.funder.setFunding(new BaseValue('0'));
// Check account settlement log.
const expectedInterest = new BigNumber('60'); // 0.05 * 100 * 12
expectAccountSettledLog(txResult, long, expectedInterest.negated());
// Check balances after settlement of the long. Note that the short is not yet settled.
await expectBalances(
ctx,
txResult,
[long, short],
[expectedInterest.negated(), marginAmount.times(2)],
[positionSize, positionSize.negated()],
false, // fullSettled
true, // positionsSumToZero
);
// Settle the short account and check account settlement log.
txResult = await triggerIndexUpdate(short);
expectAccountSettledLog(txResult, short, expectedInterest);
// Check balances after settlement of the short account.
await expectBalances(
ctx,
txResult,
[long, short],
[expectedInterest.negated(), marginAmount.times(2).plus(expectedInterest)],
[positionSize, positionSize.negated()],
);
});
it('Can settle accounts with a different frequency for each account', async () => {
// Accumulate interest and settle the long account.
await ctx.perpetual.testing.funder.setFunding(new BaseValue('0.05'));
let txResult: TxResult;
for (let i = 0; i < 9; i += 1) {
txResult = await triggerIndexUpdate(long);
}
await ctx.perpetual.testing.funder.setFunding(new BaseValue('0'));
const expectedInterest = new BigNumber('540'); // 0.05 * 100 * 12 * 9
// Check balances after settlement of the long. Note that the short is not yet settled.
await expectBalances(
ctx,
txResult,
[long, short],
[expectedInterest.negated(), marginAmount.times(2)],
[positionSize, positionSize.negated()],
false, // fullSettled
true, // positionsSumToZero
);
// Settle the short account and check account settlement log.
txResult = await triggerIndexUpdate(short);
expectAccountSettledLog(txResult, short, expectedInterest);
// Check balances after settlement of the short account.
await expectBalances(
ctx,
txResult,
[long, short],
[expectedInterest.negated(), marginAmount.times(2).plus(expectedInterest)],
[positionSize, positionSize.negated()],
);
});
it('Does not settle an account if its local index is up-to-date', async () => {
await ctx.perpetual.testing.funder.setFunding(new BaseValue('0.05'));
// Wait until we get two deposits with the same timestamp.
let result1: TxResult;
let result2: TxResult;
let block1: any;
let block2: any;
let numTries = 0;
do {
result1 = await ctx.perpetual.margin.deposit(long, new BigNumber(0));
result2 = await ctx.perpetual.margin.deposit(long, new BigNumber(0));
[block1, block2] = await Promise.all([
ctx.perpetual.web3.eth.getBlock(result1.blockNumber),
ctx.perpetual.web3.eth.getBlock(result2.blockNumber),
]);
numTries += 1;
}
while (block1.timestamp !== block2.timestamp && numTries < 10);
// Expect the second deposit not to trigger settlement of the account.
const logs = ctx.perpetual.logs.parseLogs(result2);
const filteredLogs = _.filter(logs, { name: 'LogAccountSettled' });
expect(filteredLogs.length, 'filter for LogAccountSettled').to.equal(0);
});
it('Does not settle an account with no position', async () => {
// Accumulate interest on long and short accounts.
const localIndexBefore = await ctx.perpetual.getters.getAccountIndex(otherAccountA);
await ctx.perpetual.testing.funder.setFunding(new BaseValue('0.05'));
const txResult = await triggerIndexUpdate(otherAccountA);
// Check logs.
const logs = ctx.perpetual.logs.parseLogs(txResult);
const filteredLogs = _.filter(logs, { name: 'LogAccountSettled' });
expect(filteredLogs.length, 'filter for LogAccountSettled').to.equal(0);
// Check balance.
const { margin, position } = await ctx.perpetual.getters.getAccountBalance(otherAccountA);
expectBN(margin).to.eq(INTEGERS.ZERO);
expectBN(position).to.eq(INTEGERS.ZERO);
// Check local index.
const localIndexAfter = await ctx.perpetual.getters.getAccountIndex(otherAccountA);
expectBN(localIndexAfter.baseValue.value).to.not.eq(localIndexBefore.baseValue.value);
expectBN(localIndexAfter.timestamp).to.not.eq(localIndexBefore.timestamp);
});
});
describe('_isCollateralized()', () => {
const largeValue = new BigNumber(2).pow(120).minus(1);
it('can handle large values', async () => {
await mintAndDeposit(ctx, otherAccountA, largeValue);
await mineAvgBlock();
await buy(ctx, otherAccountA, long, 1, 100);
await mineAvgBlock();
await sell(ctx, otherAccountA, long, 1, 100);
await mineAvgBlock();
await ctx.perpetual.margin.withdraw(
otherAccountA,
otherAccountA,
largeValue,
{ from: otherAccountA },
);
});
});
// ============ Helper Functions ============
/**
* Triggers an index update and settles an account by making a deposit of zero.
*/
async function triggerIndexUpdate(account: address): Promise<TxResult> {
await mineAvgBlock();
return ctx.perpetual.margin.deposit(account, new BigNumber(0), { from: account });
}
/**
* Check the global index value emitted by the log and returned by the getter.
*/
async function expectIndexUpdated(
txResult: TxResult,
expectedBaseValue: BaseValue,
): Promise<void> {
// Construct expected Index.
const { timestamp } = await ctx.perpetual.web3.eth.getBlock(txResult.blockNumber);
const expectedIndex: Index = {
timestamp: new BigNumber(timestamp),
baseValue: expectedBaseValue,
};
// Check the getter function.
const globalIndex = await ctx.perpetual.getters.getGlobalIndex();
expectBaseValueEqual(globalIndex.baseValue, expectedIndex.baseValue, 'index value from getter');
expectBN(globalIndex.timestamp, 'index timestamp from logs').to.eq(expectedIndex.timestamp);
// Check the logs.
const logs = ctx.perpetual.logs.parseLogs(txResult);
const filteredLogs = _.filter(logs, { name: 'LogIndex' });
expect(filteredLogs.length, 'filter for LogIndex').to.equal(1);
const loggedIndex: Index = filteredLogs[0].args.index;
expectBaseValueEqual(loggedIndex.baseValue, expectedIndex.baseValue, 'index value from logs');
expectBN(loggedIndex.timestamp, 'index timestamp from logs').to.eq(expectedIndex.timestamp);
}
function expectAccountSettledLog(
txResult: TxResult,
account: address,
expectedInterest: BigNumber,
): void {
const logs = ctx.perpetual.logs.parseLogs(txResult);
const filteredLogs = _.filter(logs, { name: 'LogAccountSettled' });
expect(filteredLogs.length, 'filter for LogAccountSettled').to.equal(1);
const accountSettledLog = filteredLogs[0];
expect(accountSettledLog.args.account, 'the settled account address').to.equal(account);
let actualInterest = accountSettledLog.args.amount;
expect(typeof accountSettledLog.args.isPositive).to.equal('boolean');
if (!accountSettledLog.args.isPositive) {
actualInterest = actualInterest.negated();
}
expectBN(actualInterest, 'interest applied in account settlement').to.eq(expectedInterest);
}
}); | the_stack |
import * as path from "path";
import * as fs from "fs-extra";
import { print } from "graphql";
import { mergeTypeDefs } from "@graphql-tools/merge";
import { loadFilesSync } from "@graphql-tools/load-files";
import * as cdk from "@aws-cdk/core";
import * as rds from "@aws-cdk/aws-rds";
import * as appsync from "@aws-cdk/aws-appsync";
import * as dynamodb from "@aws-cdk/aws-dynamodb";
import * as secretsmanager from "@aws-cdk/aws-secretsmanager";
import { App } from "./App";
import { Table } from "./Table";
import { Function as Fn, FunctionProps, FunctionDefinition } from "./Function";
import { Permissions } from "./util/permission";
/////////////////////
// Interfaces
/////////////////////
export interface AppSyncApiProps {
readonly graphqlApi?: appsync.IGraphqlApi | AppSyncApiCdkGraphqlProps;
readonly dataSources?: {
[key: string]:
| FunctionDefinition
| AppSyncApiLambdaDataSourceProps
| AppSyncApiDynamoDbDataSourceProps
| AppSyncApiRdsDataSourceProps
| AppSyncApiHttpDataSourceProps;
};
readonly resolvers?: {
[key: string]: string | FunctionDefinition | AppSyncApiResolverProps;
};
readonly defaultFunctionProps?: FunctionProps;
}
export interface AppSyncApiLambdaDataSourceProps {
readonly function: FunctionDefinition;
readonly options?: appsync.DataSourceOptions;
}
export interface AppSyncApiDynamoDbDataSourceProps {
readonly table: Table | dynamodb.Table;
readonly options?: appsync.DataSourceOptions;
}
export interface AppSyncApiRdsDataSourceProps {
readonly serverlessCluster: rds.IServerlessCluster;
readonly secretStore: secretsmanager.ISecret;
readonly databaseName?: string;
readonly options?: appsync.DataSourceOptions;
}
export interface AppSyncApiHttpDataSourceProps {
readonly endpoint: string;
readonly options?: appsync.HttpDataSourceOptions;
}
export interface AppSyncApiResolverProps {
readonly dataSource?: string;
readonly function?: FunctionDefinition;
readonly resolverProps?: AppSyncApiCdkResolverProps;
}
export interface AppSyncApiCdkGraphqlProps
extends Omit<appsync.GraphqlApiProps, "name" | "schema"> {
readonly name?: string;
readonly schema?: string | string[] | appsync.Schema;
}
export type AppSyncApiCdkResolverProps = Omit<
appsync.BaseResolverProps,
"fieldName" | "typeName"
>;
/////////////////////
// Construct
/////////////////////
export class AppSyncApi extends cdk.Construct {
public readonly graphqlApi: appsync.GraphqlApi;
private readonly functionsByDsKey: { [key: string]: Fn };
private readonly dataSourcesByDsKey: {
[key: string]: appsync.BaseDataSource;
};
private readonly dsKeysByResKey: { [key: string]: string };
private readonly resolversByResKey: { [key: string]: appsync.Resolver };
private readonly permissionsAttachedForAllFunctions: Permissions[];
private readonly defaultFunctionProps?: FunctionProps;
constructor(scope: cdk.Construct, id: string, props?: AppSyncApiProps) {
super(scope, id);
const root = scope.node.root as App;
const { graphqlApi, dataSources, resolvers, defaultFunctionProps } =
props || {};
this.functionsByDsKey = {};
this.dataSourcesByDsKey = {};
this.resolversByResKey = {};
this.dsKeysByResKey = {};
this.permissionsAttachedForAllFunctions = [];
this.defaultFunctionProps = defaultFunctionProps;
////////////////////
// Create Api
////////////////////
if (cdk.Construct.isConstruct(graphqlApi)) {
this.graphqlApi = graphqlApi as appsync.GraphqlApi;
} else {
const graphqlApiProps = (graphqlApi || {}) as AppSyncApiCdkGraphqlProps;
// build schema
let mainSchema: appsync.Schema | undefined;
if (typeof graphqlApiProps.schema === "string") {
mainSchema = appsync.Schema.fromAsset(graphqlApiProps.schema);
} else if (Array.isArray(graphqlApiProps.schema)) {
if (graphqlApiProps.schema.length > 0) {
// merge schema files
const mergedSchema = mergeTypeDefs(
loadFilesSync(graphqlApiProps.schema)
);
const filePath = path.join(
root.buildDir,
`appsyncapi-${id}-${this.node.addr}.graphql`
);
fs.writeFileSync(filePath, print(mergedSchema));
mainSchema = appsync.Schema.fromAsset(filePath);
}
} else {
mainSchema = graphqlApiProps.schema;
}
this.graphqlApi = new appsync.GraphqlApi(this, "Api", {
name: root.logicalPrefixedName(id),
xrayEnabled: true,
...graphqlApiProps,
// handle schema is "string"
schema: mainSchema,
});
}
///////////////////////////
// Configure data sources
///////////////////////////
if (dataSources) {
Object.keys(dataSources).forEach((key: string) =>
this.addDataSource(this, key, dataSources[key])
);
}
///////////////////////////
// Configure resolvers
///////////////////////////
if (resolvers) {
Object.keys(resolvers).forEach((key: string) =>
this.addResolver(this, key, resolvers[key])
);
}
}
public get url(): string {
return this.graphqlApi.graphqlUrl;
}
public addDataSources(
scope: cdk.Construct,
dataSources: {
[key: string]:
| FunctionDefinition
| AppSyncApiLambdaDataSourceProps
| AppSyncApiDynamoDbDataSourceProps
| AppSyncApiRdsDataSourceProps
| AppSyncApiHttpDataSourceProps;
}
): void {
Object.keys(dataSources).forEach((key: string) => {
// add data source
const fn = this.addDataSource(scope, key, dataSources[key]);
// attached existing permissions
if (fn) {
this.permissionsAttachedForAllFunctions.forEach((permissions) =>
fn.attachPermissions(permissions)
);
}
});
}
public addResolvers(
scope: cdk.Construct,
resolvers: {
[key: string]: FunctionDefinition | AppSyncApiResolverProps;
}
): void {
Object.keys(resolvers).forEach((key: string) => {
// add resolver
const fn = this.addResolver(scope, key, resolvers[key]);
// attached existing permissions
if (fn) {
this.permissionsAttachedForAllFunctions.forEach((permissions) =>
fn.attachPermissions(permissions)
);
}
});
}
private addDataSource(
scope: cdk.Construct,
dsKey: string,
dsValue:
| FunctionDefinition
| AppSyncApiLambdaDataSourceProps
| AppSyncApiDynamoDbDataSourceProps
| AppSyncApiRdsDataSourceProps
| AppSyncApiHttpDataSourceProps
): Fn | undefined {
let dataSource;
let lambda;
// Lambda ds
if ((dsValue as AppSyncApiLambdaDataSourceProps).function) {
dsValue = dsValue as AppSyncApiLambdaDataSourceProps;
lambda = Fn.fromDefinition(
scope,
`Lambda_${dsKey}`,
dsValue.function,
this.defaultFunctionProps,
`Cannot define defaultFunctionProps when a Function is passed in to the "${dsKey} data source`
);
dataSource = this.graphqlApi.addLambdaDataSource(
dsKey,
lambda,
dsValue.options
);
}
// DynamoDb ds
else if ((dsValue as AppSyncApiDynamoDbDataSourceProps).table) {
dsValue = dsValue as AppSyncApiDynamoDbDataSourceProps;
const table =
dsValue.table instanceof Table
? dsValue.table.dynamodbTable
: dsValue.table;
dataSource = this.graphqlApi.addDynamoDbDataSource(
dsKey,
table,
dsValue.options
);
}
// Rds ds
else if ((dsValue as AppSyncApiRdsDataSourceProps).serverlessCluster) {
dsValue = dsValue as AppSyncApiRdsDataSourceProps;
dataSource = this.graphqlApi.addRdsDataSource(
dsKey,
dsValue.serverlessCluster,
dsValue.secretStore,
dsValue.databaseName,
dsValue.options
);
}
// Http ds
else if ((dsValue as AppSyncApiHttpDataSourceProps).endpoint) {
dsValue = dsValue as AppSyncApiHttpDataSourceProps;
dataSource = this.graphqlApi.addHttpDataSource(
dsKey,
dsValue.endpoint,
dsValue.options
);
}
// Lambda function
else {
dsValue = dsValue as FunctionDefinition;
lambda = Fn.fromDefinition(
scope,
`Lambda_${dsKey}`,
dsValue,
this.defaultFunctionProps,
`Cannot define defaultFunctionProps when a Function is passed in to the "${dsKey} data source`
);
dataSource = this.graphqlApi.addLambdaDataSource(dsKey, lambda);
}
this.dataSourcesByDsKey[dsKey] = dataSource;
if (lambda) {
this.functionsByDsKey[dsKey] = lambda;
}
return lambda;
}
private addResolver(
scope: cdk.Construct,
resKey: string,
resValue: FunctionDefinition | AppSyncApiResolverProps
): Fn | undefined {
// Normalize resKey
resKey = this.normalizeResolverKey(resKey);
// Get type and field
const resolverKeyParts = resKey.split(" ");
if (resolverKeyParts.length !== 2) {
throw new Error(`Invalid resolver ${resKey}`);
}
const [typeName, fieldName] = resolverKeyParts;
if (fieldName.length === 0) {
throw new Error(`Invalid field defined for "${resKey}"`);
}
///////////////////
// Create data source if not created before
///////////////////
let lambda;
let dataSource;
let dataSourceKey;
let resolverProps;
// DataSource key
if (
typeof resValue === "string" &&
Object.keys(this.dataSourcesByDsKey).includes(resValue)
) {
dataSourceKey = resValue;
dataSource = this.dataSourcesByDsKey[resValue];
resolverProps = {};
}
// DataSource key not exist (string does not have a dot, assume it is referencing a data store)
else if (typeof resValue === "string" && resValue.indexOf(".") === -1) {
throw new Error(
`Failed to create resolver "${resKey}". Data source "${resValue}" does not exist.`
);
}
// Lambda resolver
else if (this.isLambdaResolverProps(resValue as AppSyncApiResolverProps)) {
resValue = resValue as AppSyncApiResolverProps;
lambda = Fn.fromDefinition(
scope,
`Lambda_${typeName}_${fieldName}`,
resValue.function as FunctionDefinition,
this.defaultFunctionProps,
`Cannot define defaultFunctionProps when a Function is passed in to the "${resKey} resolver`
);
dataSourceKey = this.buildDataSourceKey(typeName, fieldName);
dataSource = this.graphqlApi.addLambdaDataSource(dataSourceKey, lambda);
resolverProps = resValue.resolverProps || {};
}
// DataSource resolver
else if (
this.isDataSourceResolverProps(resValue as AppSyncApiResolverProps)
) {
resValue = resValue as AppSyncApiResolverProps;
dataSourceKey = resValue.dataSource as string;
dataSource = this.dataSourcesByDsKey[dataSourceKey];
resolverProps = resValue.resolverProps || {};
}
// Lambda function
else {
resValue = resValue as FunctionDefinition;
lambda = Fn.fromDefinition(
scope,
`Lambda_${typeName}_${fieldName}`,
resValue,
this.defaultFunctionProps,
`Cannot define defaultFunctionProps when a Function is passed in to the "${resKey} resolver`
);
dataSourceKey = this.buildDataSourceKey(typeName, fieldName);
dataSource = this.graphqlApi.addLambdaDataSource(dataSourceKey, lambda);
resolverProps = {};
}
// Store new data source created
if (lambda) {
this.dataSourcesByDsKey[dataSourceKey] = dataSource;
this.functionsByDsKey[dataSourceKey] = lambda;
}
this.dsKeysByResKey[resKey] = dataSourceKey;
///////////////////
// Create resolver
///////////////////
const resolver = this.graphqlApi.createResolver({
dataSource,
typeName,
fieldName,
...resolverProps,
});
this.resolversByResKey[resKey] = resolver;
return lambda;
}
private isLambdaResolverProps(object: AppSyncApiResolverProps): boolean {
return object.function !== undefined;
}
private isDataSourceResolverProps(object: AppSyncApiResolverProps): boolean {
return object.dataSource !== undefined;
}
private normalizeResolverKey(resolverKey: string): string {
// remove extra spaces in the key
return resolverKey.split(/\s+/).join(" ");
}
private buildDataSourceKey(typeName: string, fieldName: string): string {
return `LambdaDS_${typeName}_${fieldName}`;
}
public getFunction(key: string): Fn | undefined {
let fn = this.functionsByDsKey[key];
if (!fn) {
const resKey = this.normalizeResolverKey(key);
const dsKey = this.dsKeysByResKey[resKey];
fn = this.functionsByDsKey[dsKey];
}
return fn;
}
public getDataSource(key: string): appsync.BaseDataSource | undefined {
let ds = this.dataSourcesByDsKey[key];
if (!ds) {
const resKey = this.normalizeResolverKey(key);
const dsKey = this.dsKeysByResKey[resKey];
ds = this.dataSourcesByDsKey[dsKey];
}
return ds;
}
public getResolver(key: string): appsync.Resolver | undefined {
const resKey = this.normalizeResolverKey(key);
return this.resolversByResKey[resKey];
}
public attachPermissions(permissions: Permissions): void {
Object.values(this.functionsByDsKey).forEach((fn) =>
fn.attachPermissions(permissions)
);
this.permissionsAttachedForAllFunctions.push(permissions);
}
public attachPermissionsToDataSource(
key: string,
permissions: Permissions
): void {
const fn = this.getFunction(key);
if (!fn) {
throw new Error(
`Failed to attach permissions. Function does not exist for key "${key}".`
);
}
fn.attachPermissions(permissions);
}
} | the_stack |
import {
EventEmitterLike,
ListenerCallbackData,
ListenerRemoveCallback,
NotificationCallback,
SourceReceiver,
SourceSender,
} from "../../models";
/**
* Manages IPC listeners.
*/
export class IpcListeners {
/**
* Stores all callback listeners.
*/
private static callbacks = new Map<string, ListenerCallbackData>();
/**
* @param source Event emitter like object that acts a as source.
*/
constructor(private source: EventEmitterLike) {
}
/**
* Add receiver to specified channel.
* @param channel Channel to add receiver to.
* @param callback Receiver callback.
* @param onRemove Callback to be called on remove.
* @returns `true` is receiver has been added, `false` if receiver already exist for this channel.
*/
public addReceiver(channel: string, callback: SourceReceiver<any>, onRemove: ListenerRemoveCallback) {
const data = this.getChannel(channel);
if (data.receiver === null) {
data.receiver = {
callback,
onRemove,
};
this.updateChannelSubscription(channel);
return true;
}
return false;
}
/**
* Check if channel has a receiver or if there is receiver on any channel.
* @param channel Channel to check.
*/
public hasReceiver(channel?: string) {
if (channel) {
const data = this.getChannel(channel);
return data.receiver !== null;
} else {
for (const [, data] of IpcListeners.callbacks) {
if (data.receiver !== null) {
return true;
}
}
return false;
}
}
/**
* Remove receiver from specific channel or all channels.
* @param channel Specify channel to remove receiver from.
*/
public removeReceiver(channel?: string) {
const remove = (ch: string, data: ListenerCallbackData) => {
if (data.receiver !== null) {
data.receiver = null;
this.updateChannelSubscription(ch);
}
};
if (channel) {
remove(channel, this.getChannel(channel));
} else {
for (const [ch, data] of IpcListeners.callbacks) {
remove(ch, data);
}
}
return this;
}
/**
* Add sender to specified channel.
* @param channel Channel to add receiver to.
* @param callback Sender callback.
* @param onRemove Callback to be called on remove.
* @returns `true` is sender has been added, `false` if sender with the same reference already exists.
*/
public addSender(channel: string, callback: SourceSender<any>, onRemove: ListenerRemoveCallback) {
const data = this.getChannel(channel);
if (!data.senders.has(callback)) {
data.senders.set(callback, onRemove);
this.updateChannelSubscription(channel);
return true;
}
return false;
}
/**
* Check if channel has any or specific sender, or if there is any or specific sender on any channel.
* @param channel Channel to check.
* @param callback Callback to check for.
*/
public hasSender(channel?: string, callback?: SourceSender<any>) {
if (channel) {
const data = this.getChannel(channel);
if (data.senders.size > 0) {
return callback ? data.senders.has(callback) : true;
}
} else {
for (const [, data] of IpcListeners.callbacks) {
if (data.senders.size > 0) {
if (callback) {
if (data.senders.has(callback)) {
return true;
}
} else {
return true;
}
}
}
}
return false;
}
/**
* Remove specific or all sender(-s) from specific channel. Or remove all senders from all channels.
* @param channel Specify channel to remove sender(-s) from.
* @param channel Specify sender to remove from channel.
*/
public removeSender(channel?: string, callback?: SourceSender<any>) {
const remove = (ch: string, data: ListenerCallbackData, cb?: SourceSender<any>) => {
let atLeastOneRemoved: boolean = false;
if (cb) {
const onRemove = data.senders.get(cb);
if (onRemove) {
atLeastOneRemoved = true;
data.senders.delete(cb);
onRemove();
}
} else {
atLeastOneRemoved = data.senders.size > 0;
for (const [sender, onRemove] of data.senders) {
data.senders.delete(sender);
onRemove();
}
}
if (atLeastOneRemoved) {
this.updateChannelSubscription(ch);
}
};
if (channel) {
const data = this.getChannel(channel);
remove(channel, data, callback);
} else {
for (const [ch, data] of IpcListeners.callbacks) {
remove(ch, data);
}
}
return this;
}
/**
* Add notification to specified channel.
* @param channel Channel to add notification to.
* @param callback Notification callback.
* @param onRemove Callback to be called on remove.
* @returns `true` is notification has been added, `false` if notification with the same reference already exists.
*/
public addNotification(
channel: string,
callback: NotificationCallback<any, any, any>,
onRemove: ListenerRemoveCallback,
) {
const data = this.getChannel(channel);
if (!data.notifications.has(callback)) {
data.notifications.set(callback, onRemove);
return true;
}
return false;
}
/**
* Check if channel has any or specific notification, or if there is any or specific notification on any channel.
* @param channel Channel to check.
* @param callback Callback to check for.
*/
public hasNotification(channel?: string, callback?: NotificationCallback<any, any, any>) {
if (channel) {
const data = this.getChannel(channel);
if (data.notifications.size > 0) {
return callback ? data.notifications.has(callback) : true;
}
} else {
for (const [, data] of IpcListeners.callbacks) {
if (data.notifications.size > 0) {
if (callback) {
if (data.notifications.has(callback)) {
return true;
}
} else {
return true;
}
}
}
}
return false;
}
/**
* Remove specific or all notification(-s) from specific channel. Or remove all notifications from all channels.
* @param channel Specify channel to remove notification(-s) from.
* @param channel Specify notification to remove from channel.
*/
public removeNotification(channel?: string, callback?: NotificationCallback<any, any, any>) {
const remove = (ch: string, data: ListenerCallbackData, cb?: NotificationCallback<any, any, any>) => {
if (cb) {
const onRemove = data.notifications.get(cb);
if (onRemove) {
data.notifications.delete(cb);
onRemove();
}
} else {
for (const [notification, onRemove] of data.notifications) {
data.notifications.delete(notification);
onRemove();
}
}
};
if (channel) {
const data = this.getChannel(channel);
remove(channel, data, callback);
} else {
for (const [ch, data] of IpcListeners.callbacks) {
remove(ch, data);
}
}
return this;
}
/**
* Retrieves channel data from callbacks object and initializes if needed.
* @param channel Channel to retrieve callbacks to.
*/
private getChannel(channel: string) {
let data = IpcListeners.callbacks.get(channel);
if (!data) {
const newData: ListenerCallbackData = {
isListening: false,
notifications: new Map(),
receiver: null,
senders: new Map(),
sourceCallback: (ev, receivedData) => {
if (newData.receiver !== null) {
newData.receiver.callback(
ev,
receivedData,
() => this.removeReceiver(channel),
newData.notifications,
);
}
for (const [callback] of newData.senders) {
callback(ev, receivedData, () => this.removeSender(channel, callback));
}
},
};
data = newData;
IpcListeners.callbacks.set(channel, data);
}
return data;
}
/**
* Subscribes to or unsubscribes from source.
* @param channel Channel to check.
*/
private updateChannelSubscription(channel: string) {
const data = this.getChannel(channel);
if (data.isListening) {
if (data.receiver === null && data.senders.size === 0) {
this.source.removeListener(channel, data.sourceCallback);
data.isListening = false;
}
} else {
if (data.receiver !== null || data.senders.size > 0) {
this.source.on(channel, data.sourceCallback);
data.isListening = true;
}
}
}
} | the_stack |
import Long from 'long';
import _m0 from 'protobufjs/minimal';
import { Resource } from '../../../../opentelemetry/proto/resource/v1/resource';
import { InstrumentationLibrary, KeyValue } from '../../../../opentelemetry/proto/common/v1/common';
export const protobufPackage = 'opentelemetry.proto.trace.v1';
/** A collection of InstrumentationLibrarySpans from a Resource. */
export interface ResourceSpans {
/**
* The resource for the spans in this message.
* If this field is not set then no resource info is known.
*/
resource: Resource | undefined;
/** A list of InstrumentationLibrarySpans that originate from a resource. */
instrumentationLibrarySpans: InstrumentationLibrarySpans[];
}
/** A collection of Spans produced by an InstrumentationLibrary. */
export interface InstrumentationLibrarySpans {
/**
* The instrumentation library information for the spans in this message.
* Semantically when InstrumentationLibrary isn't set, it is equivalent with
* an empty instrumentation library name (unknown).
*/
instrumentationLibrary: InstrumentationLibrary | undefined;
/** A list of Spans that originate from an instrumentation library. */
spans: Span[];
}
/**
* Span represents a single operation within a trace. Spans can be
* nested to form a trace tree. Spans may also be linked to other spans
* from the same or different trace and form graphs. Often, a trace
* contains a root span that describes the end-to-end latency, and one
* or more subspans for its sub-operations. A trace can also contain
* multiple root spans, or none at all. Spans do not need to be
* contiguous - there may be gaps or overlaps between spans in a trace.
*
* The next available field id is 17.
*/
export interface Span {
/**
* A unique identifier for a trace. All spans from the same trace share
* the same `trace_id`. The ID is a 16-byte array. An ID with all zeroes
* is considered invalid.
*
* This field is semantically required. Receiver should generate new
* random trace_id if empty or invalid trace_id was received.
*
* This field is required.
*/
traceId: Uint8Array;
/**
* A unique identifier for a span within a trace, assigned when the span
* is created. The ID is an 8-byte array. An ID with all zeroes is considered
* invalid.
*
* This field is semantically required. Receiver should generate new
* random span_id if empty or invalid span_id was received.
*
* This field is required.
*/
spanId: Uint8Array;
/**
* trace_state conveys information about request position in multiple distributed tracing graphs.
* It is a trace_state in w3c-trace-context format: https://www.w3.org/TR/trace-context/#tracestate-header
* See also https://github.com/w3c/distributed-tracing for more details about this field.
*/
traceState: string;
/**
* The `span_id` of this span's parent span. If this is a root span, then this
* field must be empty. The ID is an 8-byte array.
*/
parentSpanId: Uint8Array;
/**
* A description of the span's operation.
*
* For example, the name can be a qualified method name or a file name
* and a line number where the operation is called. A best practice is to use
* the same display name at the same call point in an application.
* This makes it easier to correlate spans in different traces.
*
* This field is semantically required to be set to non-empty string.
* When null or empty string received - receiver may use string "name"
* as a replacement. There might be smarted algorithms implemented by
* receiver to fix the empty span name.
*
* This field is required.
*/
name: string;
/**
* Distinguishes between spans generated in a particular context. For example,
* two spans with the same name may be distinguished using `CLIENT` (caller)
* and `SERVER` (callee) to identify queueing latency associated with the span.
*/
kind: Span_SpanKind;
/**
* start_time_unix_nano is the start time of the span. On the client side, this is the time
* kept by the local machine where the span execution starts. On the server side, this
* is the time when the server's application handler starts running.
* Value is UNIX Epoch time in nanoseconds since 00:00:00 UTC on 1 January 1970.
*
* This field is semantically required and it is expected that end_time >= start_time.
*/
startTimeUnixNano: number;
/**
* end_time_unix_nano is the end time of the span. On the client side, this is the time
* kept by the local machine where the span execution ends. On the server side, this
* is the time when the server application handler stops running.
* Value is UNIX Epoch time in nanoseconds since 00:00:00 UTC on 1 January 1970.
*
* This field is semantically required and it is expected that end_time >= start_time.
*/
endTimeUnixNano: number;
/**
* attributes is a collection of key/value pairs. The value can be a string,
* an integer, a double or the Boolean values `true` or `false`. Note, global attributes
* like server name can be set using the resource API. Examples of attributes:
*
* "/http/user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
* "/http/server_latency": 300
* "abc.com/myattribute": true
* "abc.com/score": 10.239
*/
attributes: KeyValue[];
/**
* dropped_attributes_count is the number of attributes that were discarded. Attributes
* can be discarded because their keys are too long or because there are too many
* attributes. If this value is 0, then no attributes were dropped.
*/
droppedAttributesCount: number;
/** events is a collection of Event items. */
events: Span_Event[];
/**
* dropped_events_count is the number of dropped events. If the value is 0, then no
* events were dropped.
*/
droppedEventsCount: number;
/**
* links is a collection of Links, which are references from this span to a span
* in the same or different trace.
*/
links: Span_Link[];
/**
* dropped_links_count is the number of dropped links after the maximum size was
* enforced. If this value is 0, then no links were dropped.
*/
droppedLinksCount: number;
/**
* An optional final status for this span. Semantically when Status isn't set, it means
* span's status code is unset, i.e. assume STATUS_CODE_UNSET (code = 0).
*/
status: Status | undefined;
}
/**
* SpanKind is the type of span. Can be used to specify additional relationships between spans
* in addition to a parent/child relationship.
*/
export enum Span_SpanKind {
/**
* SPAN_KIND_UNSPECIFIED - Unspecified. Do NOT use as default.
* Implementations MAY assume SpanKind to be INTERNAL when receiving UNSPECIFIED.
*/
SPAN_KIND_UNSPECIFIED = 0,
/**
* SPAN_KIND_INTERNAL - Indicates that the span represents an internal operation within an application,
* as opposed to an operation happening at the boundaries. Default value.
*/
SPAN_KIND_INTERNAL = 1,
/**
* SPAN_KIND_SERVER - Indicates that the span covers server-side handling of an RPC or other
* remote network request.
*/
SPAN_KIND_SERVER = 2,
/** SPAN_KIND_CLIENT - Indicates that the span describes a request to some remote service. */
SPAN_KIND_CLIENT = 3,
/**
* SPAN_KIND_PRODUCER - Indicates that the span describes a producer sending a message to a broker.
* Unlike CLIENT and SERVER, there is often no direct critical path latency relationship
* between producer and consumer spans. A PRODUCER span ends when the message was accepted
* by the broker while the logical processing of the message might span a much longer time.
*/
SPAN_KIND_PRODUCER = 4,
/**
* SPAN_KIND_CONSUMER - Indicates that the span describes consumer receiving a message from a broker.
* Like the PRODUCER kind, there is often no direct critical path latency relationship
* between producer and consumer spans.
*/
SPAN_KIND_CONSUMER = 5,
UNRECOGNIZED = -1,
}
export function span_SpanKindFromJSON(object: any): Span_SpanKind {
switch (object) {
case 0:
case 'SPAN_KIND_UNSPECIFIED':
return Span_SpanKind.SPAN_KIND_UNSPECIFIED;
case 1:
case 'SPAN_KIND_INTERNAL':
return Span_SpanKind.SPAN_KIND_INTERNAL;
case 2:
case 'SPAN_KIND_SERVER':
return Span_SpanKind.SPAN_KIND_SERVER;
case 3:
case 'SPAN_KIND_CLIENT':
return Span_SpanKind.SPAN_KIND_CLIENT;
case 4:
case 'SPAN_KIND_PRODUCER':
return Span_SpanKind.SPAN_KIND_PRODUCER;
case 5:
case 'SPAN_KIND_CONSUMER':
return Span_SpanKind.SPAN_KIND_CONSUMER;
case -1:
case 'UNRECOGNIZED':
default:
return Span_SpanKind.UNRECOGNIZED;
}
}
export function span_SpanKindToJSON(object: Span_SpanKind): string {
switch (object) {
case Span_SpanKind.SPAN_KIND_UNSPECIFIED:
return 'SPAN_KIND_UNSPECIFIED';
case Span_SpanKind.SPAN_KIND_INTERNAL:
return 'SPAN_KIND_INTERNAL';
case Span_SpanKind.SPAN_KIND_SERVER:
return 'SPAN_KIND_SERVER';
case Span_SpanKind.SPAN_KIND_CLIENT:
return 'SPAN_KIND_CLIENT';
case Span_SpanKind.SPAN_KIND_PRODUCER:
return 'SPAN_KIND_PRODUCER';
case Span_SpanKind.SPAN_KIND_CONSUMER:
return 'SPAN_KIND_CONSUMER';
default:
return 'UNKNOWN';
}
}
/**
* Event is a time-stamped annotation of the span, consisting of user-supplied
* text description and key-value pairs.
*/
export interface Span_Event {
/** time_unix_nano is the time the event occurred. */
timeUnixNano: number;
/**
* name of the event.
* This field is semantically required to be set to non-empty string.
*/
name: string;
/** attributes is a collection of attribute key/value pairs on the event. */
attributes: KeyValue[];
/**
* dropped_attributes_count is the number of dropped attributes. If the value is 0,
* then no attributes were dropped.
*/
droppedAttributesCount: number;
}
/**
* A pointer from the current span to another span in the same trace or in a
* different trace. For example, this can be used in batching operations,
* where a single batch handler processes multiple requests from different
* traces or when the handler receives a request from a different project.
*/
export interface Span_Link {
/**
* A unique identifier of a trace that this linked span is part of. The ID is a
* 16-byte array.
*/
traceId: Uint8Array;
/** A unique identifier for the linked span. The ID is an 8-byte array. */
spanId: Uint8Array;
/** The trace_state associated with the link. */
traceState: string;
/** attributes is a collection of attribute key/value pairs on the link. */
attributes: KeyValue[];
/**
* dropped_attributes_count is the number of dropped attributes. If the value is 0,
* then no attributes were dropped.
*/
droppedAttributesCount: number;
}
/**
* The Status type defines a logical error model that is suitable for different
* programming environments, including REST APIs and RPC APIs.
*/
export interface Status {
/**
* The deprecated status code. This is an optional field.
*
* This field is deprecated and is replaced by the `code` field below. See backward
* compatibility notes below. According to our stability guarantees this field
* will be removed in 12 months, on Oct 22, 2021. All usage of old senders and
* receivers that do not understand the `code` field MUST be phased out by then.
*
* @deprecated
*/
deprecatedCode: Status_DeprecatedStatusCode;
/** A developer-facing human readable error message. */
message: string;
/** The status code. */
code: Status_StatusCode;
}
export enum Status_DeprecatedStatusCode {
DEPRECATED_STATUS_CODE_OK = 0,
DEPRECATED_STATUS_CODE_CANCELLED = 1,
DEPRECATED_STATUS_CODE_UNKNOWN_ERROR = 2,
DEPRECATED_STATUS_CODE_INVALID_ARGUMENT = 3,
DEPRECATED_STATUS_CODE_DEADLINE_EXCEEDED = 4,
DEPRECATED_STATUS_CODE_NOT_FOUND = 5,
DEPRECATED_STATUS_CODE_ALREADY_EXISTS = 6,
DEPRECATED_STATUS_CODE_PERMISSION_DENIED = 7,
DEPRECATED_STATUS_CODE_RESOURCE_EXHAUSTED = 8,
DEPRECATED_STATUS_CODE_FAILED_PRECONDITION = 9,
DEPRECATED_STATUS_CODE_ABORTED = 10,
DEPRECATED_STATUS_CODE_OUT_OF_RANGE = 11,
DEPRECATED_STATUS_CODE_UNIMPLEMENTED = 12,
DEPRECATED_STATUS_CODE_INTERNAL_ERROR = 13,
DEPRECATED_STATUS_CODE_UNAVAILABLE = 14,
DEPRECATED_STATUS_CODE_DATA_LOSS = 15,
DEPRECATED_STATUS_CODE_UNAUTHENTICATED = 16,
UNRECOGNIZED = -1,
}
export function status_DeprecatedStatusCodeFromJSON(object: any): Status_DeprecatedStatusCode {
switch (object) {
case 0:
case 'DEPRECATED_STATUS_CODE_OK':
return Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_OK;
case 1:
case 'DEPRECATED_STATUS_CODE_CANCELLED':
return Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_CANCELLED;
case 2:
case 'DEPRECATED_STATUS_CODE_UNKNOWN_ERROR':
return Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_UNKNOWN_ERROR;
case 3:
case 'DEPRECATED_STATUS_CODE_INVALID_ARGUMENT':
return Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_INVALID_ARGUMENT;
case 4:
case 'DEPRECATED_STATUS_CODE_DEADLINE_EXCEEDED':
return Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_DEADLINE_EXCEEDED;
case 5:
case 'DEPRECATED_STATUS_CODE_NOT_FOUND':
return Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_NOT_FOUND;
case 6:
case 'DEPRECATED_STATUS_CODE_ALREADY_EXISTS':
return Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_ALREADY_EXISTS;
case 7:
case 'DEPRECATED_STATUS_CODE_PERMISSION_DENIED':
return Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_PERMISSION_DENIED;
case 8:
case 'DEPRECATED_STATUS_CODE_RESOURCE_EXHAUSTED':
return Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_RESOURCE_EXHAUSTED;
case 9:
case 'DEPRECATED_STATUS_CODE_FAILED_PRECONDITION':
return Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_FAILED_PRECONDITION;
case 10:
case 'DEPRECATED_STATUS_CODE_ABORTED':
return Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_ABORTED;
case 11:
case 'DEPRECATED_STATUS_CODE_OUT_OF_RANGE':
return Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_OUT_OF_RANGE;
case 12:
case 'DEPRECATED_STATUS_CODE_UNIMPLEMENTED':
return Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_UNIMPLEMENTED;
case 13:
case 'DEPRECATED_STATUS_CODE_INTERNAL_ERROR':
return Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_INTERNAL_ERROR;
case 14:
case 'DEPRECATED_STATUS_CODE_UNAVAILABLE':
return Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_UNAVAILABLE;
case 15:
case 'DEPRECATED_STATUS_CODE_DATA_LOSS':
return Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_DATA_LOSS;
case 16:
case 'DEPRECATED_STATUS_CODE_UNAUTHENTICATED':
return Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_UNAUTHENTICATED;
case -1:
case 'UNRECOGNIZED':
default:
return Status_DeprecatedStatusCode.UNRECOGNIZED;
}
}
export function status_DeprecatedStatusCodeToJSON(object: Status_DeprecatedStatusCode): string {
switch (object) {
case Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_OK:
return 'DEPRECATED_STATUS_CODE_OK';
case Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_CANCELLED:
return 'DEPRECATED_STATUS_CODE_CANCELLED';
case Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_UNKNOWN_ERROR:
return 'DEPRECATED_STATUS_CODE_UNKNOWN_ERROR';
case Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_INVALID_ARGUMENT:
return 'DEPRECATED_STATUS_CODE_INVALID_ARGUMENT';
case Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_DEADLINE_EXCEEDED:
return 'DEPRECATED_STATUS_CODE_DEADLINE_EXCEEDED';
case Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_NOT_FOUND:
return 'DEPRECATED_STATUS_CODE_NOT_FOUND';
case Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_ALREADY_EXISTS:
return 'DEPRECATED_STATUS_CODE_ALREADY_EXISTS';
case Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_PERMISSION_DENIED:
return 'DEPRECATED_STATUS_CODE_PERMISSION_DENIED';
case Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_RESOURCE_EXHAUSTED:
return 'DEPRECATED_STATUS_CODE_RESOURCE_EXHAUSTED';
case Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_FAILED_PRECONDITION:
return 'DEPRECATED_STATUS_CODE_FAILED_PRECONDITION';
case Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_ABORTED:
return 'DEPRECATED_STATUS_CODE_ABORTED';
case Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_OUT_OF_RANGE:
return 'DEPRECATED_STATUS_CODE_OUT_OF_RANGE';
case Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_UNIMPLEMENTED:
return 'DEPRECATED_STATUS_CODE_UNIMPLEMENTED';
case Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_INTERNAL_ERROR:
return 'DEPRECATED_STATUS_CODE_INTERNAL_ERROR';
case Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_UNAVAILABLE:
return 'DEPRECATED_STATUS_CODE_UNAVAILABLE';
case Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_DATA_LOSS:
return 'DEPRECATED_STATUS_CODE_DATA_LOSS';
case Status_DeprecatedStatusCode.DEPRECATED_STATUS_CODE_UNAUTHENTICATED:
return 'DEPRECATED_STATUS_CODE_UNAUTHENTICATED';
default:
return 'UNKNOWN';
}
}
/**
* For the semantics of status codes see
* https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/api.md#set-status
*/
export enum Status_StatusCode {
/** STATUS_CODE_UNSET - The default status. */
STATUS_CODE_UNSET = 0,
/**
* STATUS_CODE_OK - The Span has been validated by an Application developers or Operator to have
* completed successfully.
*/
STATUS_CODE_OK = 1,
/** STATUS_CODE_ERROR - The Span contains an error. */
STATUS_CODE_ERROR = 2,
UNRECOGNIZED = -1,
}
export function status_StatusCodeFromJSON(object: any): Status_StatusCode {
switch (object) {
case 0:
case 'STATUS_CODE_UNSET':
return Status_StatusCode.STATUS_CODE_UNSET;
case 1:
case 'STATUS_CODE_OK':
return Status_StatusCode.STATUS_CODE_OK;
case 2:
case 'STATUS_CODE_ERROR':
return Status_StatusCode.STATUS_CODE_ERROR;
case -1:
case 'UNRECOGNIZED':
default:
return Status_StatusCode.UNRECOGNIZED;
}
}
export function status_StatusCodeToJSON(object: Status_StatusCode): string {
switch (object) {
case Status_StatusCode.STATUS_CODE_UNSET:
return 'STATUS_CODE_UNSET';
case Status_StatusCode.STATUS_CODE_OK:
return 'STATUS_CODE_OK';
case Status_StatusCode.STATUS_CODE_ERROR:
return 'STATUS_CODE_ERROR';
default:
return 'UNKNOWN';
}
}
const baseResourceSpans: object = {};
export const ResourceSpans = {
encode(message: ResourceSpans, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.resource !== undefined) {
Resource.encode(message.resource, writer.uint32(10).fork()).ldelim();
}
for (const v of message.instrumentationLibrarySpans) {
InstrumentationLibrarySpans.encode(v!, writer.uint32(18).fork()).ldelim();
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): ResourceSpans {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseResourceSpans } as ResourceSpans;
message.instrumentationLibrarySpans = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.resource = Resource.decode(reader, reader.uint32());
break;
case 2:
message.instrumentationLibrarySpans.push(
InstrumentationLibrarySpans.decode(reader, reader.uint32())
);
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): ResourceSpans {
const message = { ...baseResourceSpans } as ResourceSpans;
message.instrumentationLibrarySpans = [];
if (object.resource !== undefined && object.resource !== null) {
message.resource = Resource.fromJSON(object.resource);
} else {
message.resource = undefined;
}
if (object.instrumentationLibrarySpans !== undefined && object.instrumentationLibrarySpans !== null) {
for (const e of object.instrumentationLibrarySpans) {
message.instrumentationLibrarySpans.push(InstrumentationLibrarySpans.fromJSON(e));
}
}
return message;
},
toJSON(message: ResourceSpans): unknown {
const obj: any = {};
message.resource !== undefined &&
(obj.resource = message.resource ? Resource.toJSON(message.resource) : undefined);
if (message.instrumentationLibrarySpans) {
obj.instrumentationLibrarySpans = message.instrumentationLibrarySpans.map((e) =>
e ? InstrumentationLibrarySpans.toJSON(e) : undefined
);
} else {
obj.instrumentationLibrarySpans = [];
}
return obj;
},
fromPartial(object: DeepPartial<ResourceSpans>): ResourceSpans {
const message = { ...baseResourceSpans } as ResourceSpans;
message.instrumentationLibrarySpans = [];
if (object.resource !== undefined && object.resource !== null) {
message.resource = Resource.fromPartial(object.resource);
} else {
message.resource = undefined;
}
if (object.instrumentationLibrarySpans !== undefined && object.instrumentationLibrarySpans !== null) {
for (const e of object.instrumentationLibrarySpans) {
message.instrumentationLibrarySpans.push(InstrumentationLibrarySpans.fromPartial(e));
}
}
return message;
},
};
const baseInstrumentationLibrarySpans: object = {};
export const InstrumentationLibrarySpans = {
encode(message: InstrumentationLibrarySpans, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.instrumentationLibrary !== undefined) {
InstrumentationLibrary.encode(message.instrumentationLibrary, writer.uint32(10).fork()).ldelim();
}
for (const v of message.spans) {
Span.encode(v!, writer.uint32(18).fork()).ldelim();
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): InstrumentationLibrarySpans {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseInstrumentationLibrarySpans,
} as InstrumentationLibrarySpans;
message.spans = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.instrumentationLibrary = InstrumentationLibrary.decode(reader, reader.uint32());
break;
case 2:
message.spans.push(Span.decode(reader, reader.uint32()));
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): InstrumentationLibrarySpans {
const message = {
...baseInstrumentationLibrarySpans,
} as InstrumentationLibrarySpans;
message.spans = [];
if (object.instrumentationLibrary !== undefined && object.instrumentationLibrary !== null) {
message.instrumentationLibrary = InstrumentationLibrary.fromJSON(object.instrumentationLibrary);
} else {
message.instrumentationLibrary = undefined;
}
if (object.spans !== undefined && object.spans !== null) {
for (const e of object.spans) {
message.spans.push(Span.fromJSON(e));
}
}
return message;
},
toJSON(message: InstrumentationLibrarySpans): unknown {
const obj: any = {};
message.instrumentationLibrary !== undefined &&
(obj.instrumentationLibrary = message.instrumentationLibrary
? InstrumentationLibrary.toJSON(message.instrumentationLibrary)
: undefined);
if (message.spans) {
obj.spans = message.spans.map((e) => (e ? Span.toJSON(e) : undefined));
} else {
obj.spans = [];
}
return obj;
},
fromPartial(object: DeepPartial<InstrumentationLibrarySpans>): InstrumentationLibrarySpans {
const message = {
...baseInstrumentationLibrarySpans,
} as InstrumentationLibrarySpans;
message.spans = [];
if (object.instrumentationLibrary !== undefined && object.instrumentationLibrary !== null) {
message.instrumentationLibrary = InstrumentationLibrary.fromPartial(object.instrumentationLibrary);
} else {
message.instrumentationLibrary = undefined;
}
if (object.spans !== undefined && object.spans !== null) {
for (const e of object.spans) {
message.spans.push(Span.fromPartial(e));
}
}
return message;
},
};
const baseSpan: object = {
traceState: '',
name: '',
kind: 0,
startTimeUnixNano: 0,
endTimeUnixNano: 0,
droppedAttributesCount: 0,
droppedEventsCount: 0,
droppedLinksCount: 0,
};
export const Span = {
encode(message: Span, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.traceId.length !== 0) {
writer.uint32(10).bytes(message.traceId);
}
if (message.spanId.length !== 0) {
writer.uint32(18).bytes(message.spanId);
}
if (message.traceState !== '') {
writer.uint32(26).string(message.traceState);
}
if (message.parentSpanId.length !== 0) {
writer.uint32(34).bytes(message.parentSpanId);
}
if (message.name !== '') {
writer.uint32(42).string(message.name);
}
if (message.kind !== 0) {
writer.uint32(48).int32(message.kind);
}
if (message.startTimeUnixNano !== 0) {
writer.uint32(57).fixed64(message.startTimeUnixNano);
}
if (message.endTimeUnixNano !== 0) {
writer.uint32(65).fixed64(message.endTimeUnixNano);
}
for (const v of message.attributes) {
KeyValue.encode(v!, writer.uint32(74).fork()).ldelim();
}
if (message.droppedAttributesCount !== 0) {
writer.uint32(80).uint32(message.droppedAttributesCount);
}
for (const v of message.events) {
Span_Event.encode(v!, writer.uint32(90).fork()).ldelim();
}
if (message.droppedEventsCount !== 0) {
writer.uint32(96).uint32(message.droppedEventsCount);
}
for (const v of message.links) {
Span_Link.encode(v!, writer.uint32(106).fork()).ldelim();
}
if (message.droppedLinksCount !== 0) {
writer.uint32(112).uint32(message.droppedLinksCount);
}
if (message.status !== undefined) {
Status.encode(message.status, writer.uint32(122).fork()).ldelim();
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): Span {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseSpan } as Span;
message.attributes = [];
message.events = [];
message.links = [];
message.traceId = new Uint8Array();
message.spanId = new Uint8Array();
message.parentSpanId = new Uint8Array();
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.traceId = reader.bytes();
break;
case 2:
message.spanId = reader.bytes();
break;
case 3:
message.traceState = reader.string();
break;
case 4:
message.parentSpanId = reader.bytes();
break;
case 5:
message.name = reader.string();
break;
case 6:
message.kind = reader.int32() as any;
break;
case 7:
message.startTimeUnixNano = longToNumber(reader.fixed64() as Long);
break;
case 8:
message.endTimeUnixNano = longToNumber(reader.fixed64() as Long);
break;
case 9:
message.attributes.push(KeyValue.decode(reader, reader.uint32()));
break;
case 10:
message.droppedAttributesCount = reader.uint32();
break;
case 11:
message.events.push(Span_Event.decode(reader, reader.uint32()));
break;
case 12:
message.droppedEventsCount = reader.uint32();
break;
case 13:
message.links.push(Span_Link.decode(reader, reader.uint32()));
break;
case 14:
message.droppedLinksCount = reader.uint32();
break;
case 15:
message.status = Status.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Span {
const message = { ...baseSpan } as Span;
message.attributes = [];
message.events = [];
message.links = [];
message.traceId = new Uint8Array();
message.spanId = new Uint8Array();
message.parentSpanId = new Uint8Array();
if (object.traceId !== undefined && object.traceId !== null) {
message.traceId = bytesFromBase64(object.traceId);
}
if (object.spanId !== undefined && object.spanId !== null) {
message.spanId = bytesFromBase64(object.spanId);
}
if (object.traceState !== undefined && object.traceState !== null) {
message.traceState = String(object.traceState);
} else {
message.traceState = '';
}
if (object.parentSpanId !== undefined && object.parentSpanId !== null) {
message.parentSpanId = bytesFromBase64(object.parentSpanId);
}
if (object.name !== undefined && object.name !== null) {
message.name = String(object.name);
} else {
message.name = '';
}
if (object.kind !== undefined && object.kind !== null) {
message.kind = span_SpanKindFromJSON(object.kind);
} else {
message.kind = 0;
}
if (object.startTimeUnixNano !== undefined && object.startTimeUnixNano !== null) {
message.startTimeUnixNano = Number(object.startTimeUnixNano);
} else {
message.startTimeUnixNano = 0;
}
if (object.endTimeUnixNano !== undefined && object.endTimeUnixNano !== null) {
message.endTimeUnixNano = Number(object.endTimeUnixNano);
} else {
message.endTimeUnixNano = 0;
}
if (object.attributes !== undefined && object.attributes !== null) {
for (const e of object.attributes) {
message.attributes.push(KeyValue.fromJSON(e));
}
}
if (object.droppedAttributesCount !== undefined && object.droppedAttributesCount !== null) {
message.droppedAttributesCount = Number(object.droppedAttributesCount);
} else {
message.droppedAttributesCount = 0;
}
if (object.events !== undefined && object.events !== null) {
for (const e of object.events) {
message.events.push(Span_Event.fromJSON(e));
}
}
if (object.droppedEventsCount !== undefined && object.droppedEventsCount !== null) {
message.droppedEventsCount = Number(object.droppedEventsCount);
} else {
message.droppedEventsCount = 0;
}
if (object.links !== undefined && object.links !== null) {
for (const e of object.links) {
message.links.push(Span_Link.fromJSON(e));
}
}
if (object.droppedLinksCount !== undefined && object.droppedLinksCount !== null) {
message.droppedLinksCount = Number(object.droppedLinksCount);
} else {
message.droppedLinksCount = 0;
}
if (object.status !== undefined && object.status !== null) {
message.status = Status.fromJSON(object.status);
} else {
message.status = undefined;
}
return message;
},
toJSON(message: Span): unknown {
const obj: any = {};
message.traceId !== undefined &&
(obj.traceId = base64FromBytes(message.traceId !== undefined ? message.traceId : new Uint8Array()));
message.spanId !== undefined &&
(obj.spanId = base64FromBytes(message.spanId !== undefined ? message.spanId : new Uint8Array()));
message.traceState !== undefined && (obj.traceState = message.traceState);
message.parentSpanId !== undefined &&
(obj.parentSpanId = base64FromBytes(
message.parentSpanId !== undefined ? message.parentSpanId : new Uint8Array()
));
message.name !== undefined && (obj.name = message.name);
message.kind !== undefined && (obj.kind = span_SpanKindToJSON(message.kind));
message.startTimeUnixNano !== undefined && (obj.startTimeUnixNano = message.startTimeUnixNano);
message.endTimeUnixNano !== undefined && (obj.endTimeUnixNano = message.endTimeUnixNano);
if (message.attributes) {
obj.attributes = message.attributes.map((e) => (e ? KeyValue.toJSON(e) : undefined));
} else {
obj.attributes = [];
}
message.droppedAttributesCount !== undefined && (obj.droppedAttributesCount = message.droppedAttributesCount);
if (message.events) {
obj.events = message.events.map((e) => (e ? Span_Event.toJSON(e) : undefined));
} else {
obj.events = [];
}
message.droppedEventsCount !== undefined && (obj.droppedEventsCount = message.droppedEventsCount);
if (message.links) {
obj.links = message.links.map((e) => (e ? Span_Link.toJSON(e) : undefined));
} else {
obj.links = [];
}
message.droppedLinksCount !== undefined && (obj.droppedLinksCount = message.droppedLinksCount);
message.status !== undefined && (obj.status = message.status ? Status.toJSON(message.status) : undefined);
return obj;
},
fromPartial(object: DeepPartial<Span>): Span {
const message = { ...baseSpan } as Span;
message.attributes = [];
message.events = [];
message.links = [];
if (object.traceId !== undefined && object.traceId !== null) {
message.traceId = object.traceId;
} else {
message.traceId = new Uint8Array();
}
if (object.spanId !== undefined && object.spanId !== null) {
message.spanId = object.spanId;
} else {
message.spanId = new Uint8Array();
}
if (object.traceState !== undefined && object.traceState !== null) {
message.traceState = object.traceState;
} else {
message.traceState = '';
}
if (object.parentSpanId !== undefined && object.parentSpanId !== null) {
message.parentSpanId = object.parentSpanId;
} else {
message.parentSpanId = new Uint8Array();
}
if (object.name !== undefined && object.name !== null) {
message.name = object.name;
} else {
message.name = '';
}
if (object.kind !== undefined && object.kind !== null) {
message.kind = object.kind;
} else {
message.kind = 0;
}
if (object.startTimeUnixNano !== undefined && object.startTimeUnixNano !== null) {
message.startTimeUnixNano = object.startTimeUnixNano;
} else {
message.startTimeUnixNano = 0;
}
if (object.endTimeUnixNano !== undefined && object.endTimeUnixNano !== null) {
message.endTimeUnixNano = object.endTimeUnixNano;
} else {
message.endTimeUnixNano = 0;
}
if (object.attributes !== undefined && object.attributes !== null) {
for (const e of object.attributes) {
message.attributes.push(KeyValue.fromPartial(e));
}
}
if (object.droppedAttributesCount !== undefined && object.droppedAttributesCount !== null) {
message.droppedAttributesCount = object.droppedAttributesCount;
} else {
message.droppedAttributesCount = 0;
}
if (object.events !== undefined && object.events !== null) {
for (const e of object.events) {
message.events.push(Span_Event.fromPartial(e));
}
}
if (object.droppedEventsCount !== undefined && object.droppedEventsCount !== null) {
message.droppedEventsCount = object.droppedEventsCount;
} else {
message.droppedEventsCount = 0;
}
if (object.links !== undefined && object.links !== null) {
for (const e of object.links) {
message.links.push(Span_Link.fromPartial(e));
}
}
if (object.droppedLinksCount !== undefined && object.droppedLinksCount !== null) {
message.droppedLinksCount = object.droppedLinksCount;
} else {
message.droppedLinksCount = 0;
}
if (object.status !== undefined && object.status !== null) {
message.status = Status.fromPartial(object.status);
} else {
message.status = undefined;
}
return message;
},
};
const baseSpan_Event: object = {
timeUnixNano: 0,
name: '',
droppedAttributesCount: 0,
};
export const Span_Event = {
encode(message: Span_Event, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.timeUnixNano !== 0) {
writer.uint32(9).fixed64(message.timeUnixNano);
}
if (message.name !== '') {
writer.uint32(18).string(message.name);
}
for (const v of message.attributes) {
KeyValue.encode(v!, writer.uint32(26).fork()).ldelim();
}
if (message.droppedAttributesCount !== 0) {
writer.uint32(32).uint32(message.droppedAttributesCount);
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): Span_Event {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseSpan_Event } as Span_Event;
message.attributes = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.timeUnixNano = longToNumber(reader.fixed64() as Long);
break;
case 2:
message.name = reader.string();
break;
case 3:
message.attributes.push(KeyValue.decode(reader, reader.uint32()));
break;
case 4:
message.droppedAttributesCount = reader.uint32();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Span_Event {
const message = { ...baseSpan_Event } as Span_Event;
message.attributes = [];
if (object.timeUnixNano !== undefined && object.timeUnixNano !== null) {
message.timeUnixNano = Number(object.timeUnixNano);
} else {
message.timeUnixNano = 0;
}
if (object.name !== undefined && object.name !== null) {
message.name = String(object.name);
} else {
message.name = '';
}
if (object.attributes !== undefined && object.attributes !== null) {
for (const e of object.attributes) {
message.attributes.push(KeyValue.fromJSON(e));
}
}
if (object.droppedAttributesCount !== undefined && object.droppedAttributesCount !== null) {
message.droppedAttributesCount = Number(object.droppedAttributesCount);
} else {
message.droppedAttributesCount = 0;
}
return message;
},
toJSON(message: Span_Event): unknown {
const obj: any = {};
message.timeUnixNano !== undefined && (obj.timeUnixNano = message.timeUnixNano);
message.name !== undefined && (obj.name = message.name);
if (message.attributes) {
obj.attributes = message.attributes.map((e) => (e ? KeyValue.toJSON(e) : undefined));
} else {
obj.attributes = [];
}
message.droppedAttributesCount !== undefined && (obj.droppedAttributesCount = message.droppedAttributesCount);
return obj;
},
fromPartial(object: DeepPartial<Span_Event>): Span_Event {
const message = { ...baseSpan_Event } as Span_Event;
message.attributes = [];
if (object.timeUnixNano !== undefined && object.timeUnixNano !== null) {
message.timeUnixNano = object.timeUnixNano;
} else {
message.timeUnixNano = 0;
}
if (object.name !== undefined && object.name !== null) {
message.name = object.name;
} else {
message.name = '';
}
if (object.attributes !== undefined && object.attributes !== null) {
for (const e of object.attributes) {
message.attributes.push(KeyValue.fromPartial(e));
}
}
if (object.droppedAttributesCount !== undefined && object.droppedAttributesCount !== null) {
message.droppedAttributesCount = object.droppedAttributesCount;
} else {
message.droppedAttributesCount = 0;
}
return message;
},
};
const baseSpan_Link: object = { traceState: '', droppedAttributesCount: 0 };
export const Span_Link = {
encode(message: Span_Link, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.traceId.length !== 0) {
writer.uint32(10).bytes(message.traceId);
}
if (message.spanId.length !== 0) {
writer.uint32(18).bytes(message.spanId);
}
if (message.traceState !== '') {
writer.uint32(26).string(message.traceState);
}
for (const v of message.attributes) {
KeyValue.encode(v!, writer.uint32(34).fork()).ldelim();
}
if (message.droppedAttributesCount !== 0) {
writer.uint32(40).uint32(message.droppedAttributesCount);
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): Span_Link {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseSpan_Link } as Span_Link;
message.attributes = [];
message.traceId = new Uint8Array();
message.spanId = new Uint8Array();
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.traceId = reader.bytes();
break;
case 2:
message.spanId = reader.bytes();
break;
case 3:
message.traceState = reader.string();
break;
case 4:
message.attributes.push(KeyValue.decode(reader, reader.uint32()));
break;
case 5:
message.droppedAttributesCount = reader.uint32();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Span_Link {
const message = { ...baseSpan_Link } as Span_Link;
message.attributes = [];
message.traceId = new Uint8Array();
message.spanId = new Uint8Array();
if (object.traceId !== undefined && object.traceId !== null) {
message.traceId = bytesFromBase64(object.traceId);
}
if (object.spanId !== undefined && object.spanId !== null) {
message.spanId = bytesFromBase64(object.spanId);
}
if (object.traceState !== undefined && object.traceState !== null) {
message.traceState = String(object.traceState);
} else {
message.traceState = '';
}
if (object.attributes !== undefined && object.attributes !== null) {
for (const e of object.attributes) {
message.attributes.push(KeyValue.fromJSON(e));
}
}
if (object.droppedAttributesCount !== undefined && object.droppedAttributesCount !== null) {
message.droppedAttributesCount = Number(object.droppedAttributesCount);
} else {
message.droppedAttributesCount = 0;
}
return message;
},
toJSON(message: Span_Link): unknown {
const obj: any = {};
message.traceId !== undefined &&
(obj.traceId = base64FromBytes(message.traceId !== undefined ? message.traceId : new Uint8Array()));
message.spanId !== undefined &&
(obj.spanId = base64FromBytes(message.spanId !== undefined ? message.spanId : new Uint8Array()));
message.traceState !== undefined && (obj.traceState = message.traceState);
if (message.attributes) {
obj.attributes = message.attributes.map((e) => (e ? KeyValue.toJSON(e) : undefined));
} else {
obj.attributes = [];
}
message.droppedAttributesCount !== undefined && (obj.droppedAttributesCount = message.droppedAttributesCount);
return obj;
},
fromPartial(object: DeepPartial<Span_Link>): Span_Link {
const message = { ...baseSpan_Link } as Span_Link;
message.attributes = [];
if (object.traceId !== undefined && object.traceId !== null) {
message.traceId = object.traceId;
} else {
message.traceId = new Uint8Array();
}
if (object.spanId !== undefined && object.spanId !== null) {
message.spanId = object.spanId;
} else {
message.spanId = new Uint8Array();
}
if (object.traceState !== undefined && object.traceState !== null) {
message.traceState = object.traceState;
} else {
message.traceState = '';
}
if (object.attributes !== undefined && object.attributes !== null) {
for (const e of object.attributes) {
message.attributes.push(KeyValue.fromPartial(e));
}
}
if (object.droppedAttributesCount !== undefined && object.droppedAttributesCount !== null) {
message.droppedAttributesCount = object.droppedAttributesCount;
} else {
message.droppedAttributesCount = 0;
}
return message;
},
};
const baseStatus: object = { deprecatedCode: 0, message: '', code: 0 };
export const Status = {
encode(message: Status, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.deprecatedCode !== 0) {
writer.uint32(8).int32(message.deprecatedCode);
}
if (message.message !== '') {
writer.uint32(18).string(message.message);
}
if (message.code !== 0) {
writer.uint32(24).int32(message.code);
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): Status {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseStatus } as Status;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.deprecatedCode = reader.int32() as any;
break;
case 2:
message.message = reader.string();
break;
case 3:
message.code = reader.int32() as any;
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Status {
const message = { ...baseStatus } as Status;
if (object.deprecatedCode !== undefined && object.deprecatedCode !== null) {
message.deprecatedCode = status_DeprecatedStatusCodeFromJSON(object.deprecatedCode);
} else {
message.deprecatedCode = 0;
}
if (object.message !== undefined && object.message !== null) {
message.message = String(object.message);
} else {
message.message = '';
}
if (object.code !== undefined && object.code !== null) {
message.code = status_StatusCodeFromJSON(object.code);
} else {
message.code = 0;
}
return message;
},
toJSON(message: Status): unknown {
const obj: any = {};
message.deprecatedCode !== undefined &&
(obj.deprecatedCode = status_DeprecatedStatusCodeToJSON(message.deprecatedCode));
message.message !== undefined && (obj.message = message.message);
message.code !== undefined && (obj.code = status_StatusCodeToJSON(message.code));
return obj;
},
fromPartial(object: DeepPartial<Status>): Status {
const message = { ...baseStatus } as Status;
if (object.deprecatedCode !== undefined && object.deprecatedCode !== null) {
message.deprecatedCode = object.deprecatedCode;
} else {
message.deprecatedCode = 0;
}
if (object.message !== undefined && object.message !== null) {
message.message = object.message;
} else {
message.message = '';
}
if (object.code !== undefined && object.code !== null) {
message.code = object.code;
} else {
message.code = 0;
}
return message;
},
};
declare var self: any | undefined;
declare var window: any | undefined;
var globalThis: any = (() => {
if (typeof globalThis !== 'undefined') return globalThis;
if (typeof self !== 'undefined') return self;
if (typeof window !== 'undefined') return window;
if (typeof global !== 'undefined') return global;
throw 'Unable to locate global object';
})();
const atob: (b64: string) => string =
globalThis.atob || ((b64) => globalThis.Buffer.from(b64, 'base64').toString('binary'));
function bytesFromBase64(b64: string): Uint8Array {
const bin = atob(b64);
const arr = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; ++i) {
arr[i] = bin.charCodeAt(i);
}
return arr;
}
const btoa: (bin: string) => string =
globalThis.btoa || ((bin) => globalThis.Buffer.from(bin, 'binary').toString('base64'));
function base64FromBytes(arr: Uint8Array): string {
const bin: string[] = [];
for (let i = 0; i < arr.byteLength; ++i) {
bin.push(String.fromCharCode(arr[i]));
}
return btoa(bin.join(''));
}
type Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;
function longToNumber(long: Long): number {
if (long.gt(Number.MAX_SAFE_INTEGER)) {
throw new globalThis.Error('Value is larger than Number.MAX_SAFE_INTEGER');
}
return long.toNumber();
}
if (_m0.util.Long !== Long) {
_m0.util.Long = Long as any;
_m0.configure();
} | the_stack |
import EventHandling from './eventhandling';
import config from './config';
import log from './log';
import {
applyMixins,
deepClone,
equal,
isDocument,
isFolder,
pathsFromRoot
} from './util';
/**
* This module defines functions that are mixed into remoteStorage.local when
* it is instantiated (currently one of indexeddb.js, localstorage.js, or
* inmemorystorage.js).
*
* All remoteStorage.local implementations should therefore implement
* this.getNodes, this.setNodes, and this.forAllNodes. The rest is blended in
* here to create a GPD (get/put/delete) interface which the BaseClient can
* talk to.
*
* @interface
*/
abstract class CachingLayer {
// FIXME
// this process of updating nodes needs to be heavily documented first, then
// refactored. Right now it's almost impossible to refactor as there's no
// explanation of why things are implemented certain ways or what the goal(s)
// of the behavior are. -slvrbckt (+1 -les)
private _updateNodesRunning = false;
private _updateNodesQueued = [];
// functions that will be overwritten
// ----------------------------------
abstract getNodes(paths: string[]): Promise<RSNodes>;
abstract diffHandler(...args: any[]);
abstract forAllNodes(cb: (node) => any): Promise<void>;
abstract setNodes(nodes: RSNodes): Promise<void>;
// --------------------------------------------------
// TODO: improve our code structure so that this function
// could call sync.queueGetRequest directly instead of needing
// this hacky third parameter as a callback
get (path: string, maxAge: number, queueGetRequest: (path: string) => Promise<QueuedRequestResponse>): Promise<QueuedRequestResponse> {
if (typeof (maxAge) === 'number') {
return this.getNodes(pathsFromRoot(path))
.then((objs) => {
const node: RSNode = getLatest(objs[path]);
if (isOutdated(objs, maxAge)) {
return queueGetRequest(path);
} else if (node) {
return {statusCode: 200, body: node.body || node.itemsMap, contentType: node.contentType};
} else {
return {statusCode: 404};
}
});
} else {
return this.getNodes([path])
.then((objs) => {
const node = getLatest(objs[path]);
if (node) {
if (isFolder(path)) {
for (const i in node.itemsMap) {
// the hasOwnProperty check here is only because our jshint settings require it:
if (node.itemsMap.hasOwnProperty(i) && node.itemsMap[i] === false) {
delete node.itemsMap[i];
}
}
}
return {statusCode: 200, body: node.body || node.itemsMap, contentType: node.contentType};
} else {
return {statusCode: 404};
}
});
}
}
put(path: string, body: any, contentType: string): Promise<RSNodes> {
const paths = pathsFromRoot(path);
function _processNodes(nodePaths, nodes) {
try {
for (let i = 0, len = nodePaths.length; i < len; i++) {
const nodePath = nodePaths[i];
let node = nodes[nodePath];
let previous;
if (!node) {
nodes[nodePath] = node = makeNode(nodePath);
}
// Document
if (i === 0) {
previous = getLatest(node);
node.local = {
body: body,
contentType: contentType,
previousBody: (previous ? previous.body : undefined),
previousContentType: (previous ? previous.contentType : undefined),
};
}
// Folder
else {
const itemName = nodePaths[i - 1].substring(nodePath.length);
node = updateFolderNodeWithItemName(node, itemName);
}
}
return nodes;
} catch (e) {
log('[Cachinglayer] Error during PUT', nodes, e);
throw e;
}
}
return this._updateNodes(paths, _processNodes);
}
delete(path: string): unknown {
const paths = pathsFromRoot(path);
return this._updateNodes(paths, function (nodePaths, nodes) {
for (let i = 0, len = nodePaths.length; i < len; i++) {
const nodePath = nodePaths[i];
const node = nodes[nodePath];
let previous;
if (!node) {
console.error('Cannot delete non-existing node ' + nodePath);
continue;
}
if (i === 0) {
// Document
previous = getLatest(node);
node.local = {
body: false,
previousBody: (previous ? previous.body : undefined),
previousContentType: (previous ? previous.contentType : undefined),
};
} else {
// Folder
if (!node.local) {
node.local = deepClone(node.common);
}
const itemName = nodePaths[i - 1].substring(nodePath.length);
delete node.local.itemsMap[itemName];
if (Object.getOwnPropertyNames(node.local.itemsMap).length > 0) {
// This folder still contains other items, don't remove any further ancestors
break;
}
}
}
return nodes;
});
}
flush(path: string): unknown {
return this._getAllDescendentPaths(path).then((paths) => {
return this.getNodes(paths);
}).then((nodes: RSNodes) => {
for (const nodePath in nodes) {
const node = nodes[nodePath];
if (node && node.common && node.local) {
this._emitChange({
path: node.path,
origin: 'local',
oldValue: (node.local.body === false ? undefined : node.local.body),
newValue: (node.common.body === false ? undefined : node.common.body)
});
}
nodes[nodePath] = undefined;
}
return this.setNodes(nodes);
});
}
private _emitChange(obj: ChangeObj) {
if (config.changeEvents[obj.origin]) {
this._emit('change', obj);
}
}
fireInitial() {
if (!config.changeEvents.local) {
return;
}
this.forAllNodes((node) => {
if (isDocument(node.path)) {
const latest = getLatest(node);
if (latest) {
this._emitChange({
path: node.path,
origin: 'local',
oldValue: undefined,
oldContentType: undefined,
newValue: latest.body,
newContentType: latest.contentType
});
}
}
}).then(() => {
this._emit('local-events-done');
});
}
// TODO add proper type
onDiff(diffHandler: any) {
this.diffHandler = diffHandler;
}
migrate(node: RSNode): RSNode {
if (typeof (node) === 'object' && !node.common) {
node.common = {};
if (typeof (node.path) === 'string') {
if (node.path.substr(-1) === '/' && typeof (node.body) === 'object') {
node.common.itemsMap = node.body;
}
} else {
//save legacy content of document node as local version
if (!node.local) {
node.local = {};
}
node.local.body = node.body;
node.local.contentType = node.contentType;
}
}
return node;
}
private _updateNodes(paths: string[], _processNodes): Promise<RSNodes> {
return new Promise((resolve, reject) => {
this._doUpdateNodes(paths, _processNodes, {
resolve: resolve,
reject: reject
});
});
}
private _doUpdateNodes(paths, _processNodes, promise) {
if (this._updateNodesRunning) {
this._updateNodesQueued.push({
paths: paths,
cb: _processNodes,
promise: promise
});
return;
} else {
this._updateNodesRunning = true;
}
this.getNodes(paths).then((nodes) => {
const existingNodes = deepClone(nodes);
const changeEvents = [];
nodes = _processNodes(paths, nodes);
for (const path in nodes) {
const node = nodes[path];
if (equal(node, existingNodes[path])) {
delete nodes[path];
} else if (isDocument(path)) {
if (
!equal(node.local.body, node.local.previousBody) ||
node.local.contentType !== node.local.previousContentType
) {
changeEvents.push({
path: path,
origin: 'window',
oldValue: node.local.previousBody,
newValue: node.local.body === false ? undefined : node.local.body,
oldContentType: node.local.previousContentType,
newContentType: node.local.contentType
});
}
delete node.local.previousBody;
delete node.local.previousContentType;
}
}
this.setNodes(nodes).then(() => {
this._emitChangeEvents(changeEvents);
promise.resolve({statusCode: 200});
});
}).then(() => {
return Promise.resolve();
}, (err) => {
promise.reject(err);
}).then(() => {
this._updateNodesRunning = false;
const nextJob = this._updateNodesQueued.shift();
if (nextJob) {
this._doUpdateNodes(nextJob.paths, nextJob.cb, nextJob.promise);
}
});
}
private _emitChangeEvents(events: RSEvent[]) {
for (let i = 0, len = events.length; i < len; i++) {
this._emitChange(events[i]);
if (this.diffHandler) {
this.diffHandler(events[i].path);
}
}
}
private _getAllDescendentPaths(path: string) {
if (isFolder(path)) {
return this.getNodes([path]).then((nodes) => {
const allPaths = [path];
const latest = getLatest(nodes[path]);
const itemNames = Object.keys(latest.itemsMap);
const calls = itemNames.map((itemName) => {
return this._getAllDescendentPaths(path + itemName).then((paths) => {
for (let i = 0, len = paths.length; i < len; i++) {
allPaths.push(paths[i]);
}
});
});
return Promise.all(calls).then(() => {
return allPaths;
});
});
} else {
return Promise.resolve([path]);
}
}
// treated as private but made public for unit testing
_getInternals() {
return {
getLatest: getLatest,
makeNode: makeNode,
isOutdated: isOutdated
};
}
}
function getLatest(node: RSNode): any {
if (typeof (node) !== 'object' || typeof (node.path) !== 'string') {
return;
}
if (isFolder(node.path)) {
if (node.local && node.local.itemsMap) {
return node.local;
}
if (node.common && node.common.itemsMap) {
return node.common;
}
} else {
if (node.local) {
if (node.local.body && node.local.contentType) {
return node.local;
}
if (node.local.body === false) {
return;
}
}
if (node.common && node.common.body && node.common.contentType) {
return node.common;
}
// Migration code! Once all apps use at least this version of the lib, we
// can publish clean-up code that migrates over any old-format data, and
// stop supporting it. For now, new apps will support data in both
// formats, thanks to this:
if (node.body && node.contentType) {
return {
body: node.body,
contentType: node.contentType
};
}
}
}
function isOutdated(nodes: RSNodes, maxAge: number): boolean {
for (const path in nodes) {
if (nodes[path] && nodes[path].remote) {
return true;
}
const nodeVersion = getLatest(nodes[path]);
if (nodeVersion && nodeVersion.timestamp && (new Date().getTime()) - nodeVersion.timestamp <= maxAge) {
return false;
} else if (!nodeVersion) {
return true;
}
}
return true;
}
function makeNode(path: string): RSNode {
const node: RSNode = {path: path, common: {}};
if (isFolder(path)) {
node.common.itemsMap = {};
}
return node;
}
function updateFolderNodeWithItemName(node: RSNode, itemName: string): RSNode {
if (!node.common) {
node.common = {
itemsMap: {}
};
}
if (!node.common.itemsMap) {
node.common.itemsMap = {};
}
if (!node.local) {
node.local = deepClone(node.common);
}
if (!node.local.itemsMap) {
node.local.itemsMap = node.common.itemsMap;
}
node.local.itemsMap[itemName] = true;
return node;
}
interface CachingLayer extends EventHandling {};
applyMixins(CachingLayer, [EventHandling]);
export = CachingLayer; | the_stack |
import * as path from 'path';
import tmrm = require('azure-pipelines-task-lib/mock-run');
import { setEndpointData, setAgentsData, mockTaskArgument, nock, MOCK_SUBSCRIPTION_ID, mockAzureSpringCloudExists, mockCommonAzureAPIs } from './mock_utils';
import { ASC_RESOURCE_TYPE, MOCK_RESOURCE_GROUP_NAME } from './mock_utils'
import assert = require('assert');
const MOCK_SAS_URL = "https://mockFileShare.file.core.windows.net/mockId/resources/mockId2?sv=2018-03-28&sr=f&sig=%2Bh3X40ta1Oyp0Lar6Fg99MXVmTR%2BHm109ZbuwCCCus0%3D&se=2020-12-03T06%3A06%3A13Z&sp=w";
const MOCK_RELATIVE_PATH = "resources/c256e6792411d5e86bbe81265a60f62cdf5d7d9eb70fa8f303baf95ec84bb7f7-2020120304-2a3a6867-3a9f-41fd-bef9-e18e52d2e55a";
const MOCK_DEPLOYMENT_STATUS_ENDPOINT = `/subscriptions/${MOCK_SUBSCRIPTION_ID}/resourceGroups/${MOCK_RESOURCE_GROUP_NAME}/providers/Microsoft.AppPlatform/locations/eastus2/operationStatus/default/operationId/mockoperationid?api-version=2020-07-01`
export class DeploymentFailsWithInsufficientDeploymentL0 {
static readonly TEST_NAME = 'DeploymentToStagingSucceedsL0';
static readonly MOCK_APP_NAME = 'testapp';
public static startTest() {
console.log(`running ${this.TEST_NAME}`);
let taskPath = path.join(__dirname, '..', 'azurespringclouddeployment.js');
let taskMockRunner: tmrm.TaskMockRunner = new tmrm.TaskMockRunner(taskPath);
setEndpointData();
setAgentsData();
mockCommonAzureAPIs();
mockAzureSpringCloudExists(this.TEST_NAME);
this.mockTwoDeployments();
let nockScope = this.mockDeploymentApis();
taskMockRunner.registerMock('./azure-storage', {
uploadFileToSasUrl: async function (sasUrl: string, localPath: string) {
console.log('Executing mock upload to storage');
assert.strictEqual(sasUrl, MOCK_SAS_URL, "Attempting to upload to unexpected SAS URL");
assert.strictEqual(localPath, "dummy.jar", "Attempting to upload path other than the one provided");
}
});
taskMockRunner.setAnswers(mockTaskArgument());
taskMockRunner.registerMockExport('getPathInput', (name: string, required?: boolean, check?: boolean) => 'dummy.jar');
taskMockRunner.run();
}
/**
* Simulate a deployment list API that returns a production deployment and a staging deployment.
*/
private static mockTwoDeployments() {
nock('https://management.azure.com', {
reqheaders: {
"authorization": "Bearer DUMMY_ACCESS_TOKEN",
"content-type": "application/json; charset=utf-8",
"user-agent": "TFS_useragent"
}
}).get(`/subscriptions/${MOCK_SUBSCRIPTION_ID}/resourceGroups/${encodeURIComponent(MOCK_RESOURCE_GROUP_NAME)}/providers/${ASC_RESOURCE_TYPE}/${this.TEST_NAME}/apps/${this.MOCK_APP_NAME}/deployments?api-version=2020-07-01`)
.reply(200, {
"value": [
{
"id": `/subscriptions/${MOCK_SUBSCRIPTION_ID}/resourceGroups/${encodeURIComponent(MOCK_RESOURCE_GROUP_NAME)}/providers/${ASC_RESOURCE_TYPE}/${this.TEST_NAME}/apps/${this.MOCK_APP_NAME}/deployments/default`,
"name": "default",
"properties": {
"active": true,
"appName": this.MOCK_APP_NAME,
"deploymentSettings": {
"cpu": 1,
"environmentVariables": null,
"memoryInGB": 1,
"runtimeVersion": "Java_8"
},
"instances": [
{
"discoveryStatus": "UP",
"name": `${this.MOCK_APP_NAME}-default-7-7b77f5b6f5-fff9t`,
"startTime": "2021-03-13T01:39:20Z",
"status": "Running"
}
],
"provisioningState": "Succeeded",
"source": {
"relativePath": "<default>",
"type": "Jar"
},
"status": "Running"
},
"resourceGroup": MOCK_RESOURCE_GROUP_NAME,
"sku": {
"capacity": 1,
"name": "S0",
"tier": "Standard"
},
"type": `${ASC_RESOURCE_TYPE}/apps/deployments`
},
{
"id": `/subscriptions/${MOCK_SUBSCRIPTION_ID}/resourceGroups/${encodeURIComponent(MOCK_RESOURCE_GROUP_NAME)}/providers/${ASC_RESOURCE_TYPE}/${this.TEST_NAME}/apps/${this.MOCK_APP_NAME}/deployments/theOtherOne`,
"name": "theOtherOne",
"properties": {
"active": false,
"appName": this.MOCK_APP_NAME,
"deploymentSettings": {
"cpu": 1,
"environmentVariables": null,
"memoryInGB": 1,
"runtimeVersion": "Java_8"
},
"instances": [
{
"discoveryStatus": "UP",
"name": `${this.MOCK_APP_NAME}-theOtherOne-7-7b77f5b6f5-90210`,
"startTime": "2021-03-13T01:39:20Z",
"status": "Running"
}
],
"provisioningState": "Succeeded",
"source": {
"relativePath": "<default>",
"type": "Jar"
},
"status": "Running"
},
"resourceGroup": MOCK_RESOURCE_GROUP_NAME,
"sku": {
"capacity": 1,
"name": "S0",
"tier": "Standard"
},
"type": `${ASC_RESOURCE_TYPE}/apps/deployments`
}]
}).persist();
}
/** Simulate APIs invoked as part of deployment */
private static mockDeploymentApis() {
//mock get resource upload URL
nock('https://management.azure.com', {
reqheaders: {
"authorization": "Bearer DUMMY_ACCESS_TOKEN",
"content-type": "application/json; charset=utf-8",
"user-agent": "TFS_useragent"
}
})
.post(`/subscriptions/${MOCK_SUBSCRIPTION_ID}/resourceGroups/${MOCK_RESOURCE_GROUP_NAME}/providers/${ASC_RESOURCE_TYPE}/${this.TEST_NAME}/apps/${this.MOCK_APP_NAME}/getResourceUploadUrl?api-version=2020-07-01`)
.once()
.reply(200,
{
"relativePath": MOCK_RELATIVE_PATH,
"uploadUrl": MOCK_SAS_URL
}
)
// mock listTestKeys
.post(`/subscriptions/${MOCK_SUBSCRIPTION_ID}/resourceGroups/${MOCK_RESOURCE_GROUP_NAME}/providers/${ASC_RESOURCE_TYPE}/${this.TEST_NAME}/listTestKeys?api-version=2020-07-01`)
.once()
.reply(200,
{
"primaryKey": "mockPrimaryKey",
"secondaryKey": "mockSecondaryKey",
"primaryTestEndpoint": `https://primary:mockPrimaryKey@${this.MOCK_APP_NAME}.test.azuremicroservices.io`,
"secondaryTestEndpoint": `https://secondary:mockSecondaryKey@${this.MOCK_APP_NAME}.test.azuremicroservices.io`,
"enabled": true
}
)
// Mock the deployment update API:
.patch(`/subscriptions/${MOCK_SUBSCRIPTION_ID}/resourceGroups/${encodeURIComponent(MOCK_RESOURCE_GROUP_NAME)}/providers/${ASC_RESOURCE_TYPE}/${this.TEST_NAME}/apps/${this.MOCK_APP_NAME}/deployments/theOtherOne?api-version=2020-07-01`)
.once()
.reply((uri, serializedRequestBody) => {
let requestBody = JSON.parse(serializedRequestBody);
assert.strictEqual(requestBody.properties.source.relativePath, MOCK_RELATIVE_PATH);
assert.strictEqual(requestBody.properties.deploymentSettings.runtimeVersion, 'Java_11');
assert.strictEqual(requestBody.properties.deploymentSettings.environmentVariables.key1, 'val1');
assert.strictEqual(requestBody.properties.deploymentSettings.environmentVariables.key2, "val 2");
//We'd never have the .NET entry path parameter in a Java app in the real world,
//but we'll take this opportunity to ensure it's properly propagated when set as a task param.
assert.strictEqual(requestBody.properties.deploymentSettings.netCoreMainEntryPath, '/foobar.dll');
let responseBody = {
"provisioningState": "Updating"
}
let returnHeaders = {
'azure-asyncoperation': 'https://management.azure.com' + MOCK_DEPLOYMENT_STATUS_ENDPOINT
}
return [202, responseBody, returnHeaders];
})
// Mock the operation status URL
.get(MOCK_DEPLOYMENT_STATUS_ENDPOINT)
.once()
.reply(200, {
status: "Completed"
})
.persist();
}
}
DeploymentFailsWithInsufficientDeploymentL0.startTest(); | the_stack |
import { NetworkContext } from "@counterfactual/types";
import { Provider } from "ethers/providers";
import { BigNumber } from "ethers/utils";
import { fromExtendedKey } from "ethers/utils/hdnode";
import { UNASSIGNED_SEQ_NO } from "../constants";
import { SetStateCommitment } from "../ethereum";
import { AppInstance, StateChannel, StateChannelJSON } from "../models";
import { getCreate2MultisigAddress } from "../utils";
import { Opcode, Protocol } from "./enums";
import {
Context,
ProtocolExecutionFlow,
ProtocolMessage,
ProtocolParameters,
UninstallVirtualAppParams
} from "./types";
import { computeTokenIndexedFreeBalanceIncrements } from "./utils/get-outcome-increments";
import { assertIsValidSignature } from "./utils/signature-validator";
import { xkeyKthAddress } from "./xkeys";
function xkeyTo0thAddress(xpub: string) {
return fromExtendedKey(xpub).derivePath("0").address;
}
const { OP_SIGN, IO_SEND_AND_WAIT, IO_SEND } = Opcode;
/**
* @description This exchange is described at the following URL:
*
* specs.counterfactual.com/en/latest/protocols/uninstall-virtual-app.html
*/
export const UNINSTALL_VIRTUAL_APP_PROTOCOL: ProtocolExecutionFlow = {
/**
* Sequence 0 of the UNINSTALL_VIRTUAL_APP_PROTOCOL requires the initiator
* party to request to the intermediary to lock the state of the virtual app,
* then upon receiving confirmation it has been locked, then request to the
* intermediary to uninstall the agreement that was signed locking up the
* intermediary's capital based on the outcome of the virtul app at the
* agreed upon locked state.
*
* @param {Context} context
*/
0 /* Initiating */: async function*(context: Context) {
const {
message: { processID, params },
provider,
store,
network
} = context;
const {
sharedData: { stateChannelsMap }
} = store;
const {
intermediaryXpub,
responderXpub
} = params as UninstallVirtualAppParams;
const intermediaryAddress = xkeyKthAddress(intermediaryXpub, 0);
const responderAddress = xkeyKthAddress(responderXpub, 0);
const [
stateChannelWithAllThreeParties,
stateChannelWithIntermediary,
stateChannelWithResponding,
timeLockedPassThroughAppInstance
] = await getUpdatedStateChannelAndAppInstanceObjectsForInitiating(
stateChannelsMap,
params!,
provider,
network
);
const timeLockedPassThroughSetStateCommitment = new SetStateCommitment(
network,
timeLockedPassThroughAppInstance.identity,
timeLockedPassThroughAppInstance.hashOfLatestState,
timeLockedPassThroughAppInstance.appSeqNo,
timeLockedPassThroughAppInstance.defaultTimeout
);
const initiatingSignatureOnTimeLockedPassThroughSetStateCommitment = yield [
OP_SIGN,
timeLockedPassThroughSetStateCommitment
];
const m1 = {
params,
processID,
protocol: Protocol.UninstallVirtualApp,
seq: 1,
toXpub: intermediaryXpub,
customData: {
signature: initiatingSignatureOnTimeLockedPassThroughSetStateCommitment
}
} as ProtocolMessage;
const m4 = (yield [IO_SEND_AND_WAIT, m1]) as ProtocolMessage;
const {
customData: {
signature: responderSignatureOnTimeLockedPassThroughSetStateCommitment,
signature2: intermediarySignatureOnTimeLockedPassThroughSetStateCommitment
}
} = m4;
assertIsValidSignature(
responderAddress,
timeLockedPassThroughSetStateCommitment,
responderSignatureOnTimeLockedPassThroughSetStateCommitment
);
assertIsValidSignature(
intermediaryAddress,
timeLockedPassThroughSetStateCommitment,
intermediarySignatureOnTimeLockedPassThroughSetStateCommitment
);
await store.setCommitment(
[Protocol.Update, timeLockedPassThroughAppInstance.identityHash],
timeLockedPassThroughSetStateCommitment.getSignedTransaction([
initiatingSignatureOnTimeLockedPassThroughSetStateCommitment,
intermediarySignatureOnTimeLockedPassThroughSetStateCommitment,
responderSignatureOnTimeLockedPassThroughSetStateCommitment
])
);
const aliceIngridAppDisactivationCommitment = new SetStateCommitment(
network,
stateChannelWithIntermediary.freeBalance.identity,
stateChannelWithIntermediary.freeBalance.hashOfLatestState,
stateChannelWithIntermediary.freeBalance.versionNumber,
stateChannelWithIntermediary.freeBalance.timeout
);
const initiatingSignatureOnAliceIngridAppDisactivationCommitment = yield [
OP_SIGN,
aliceIngridAppDisactivationCommitment
];
const m5 = {
processID,
protocol: Protocol.UninstallVirtualApp,
seq: UNASSIGNED_SEQ_NO,
toXpub: intermediaryXpub,
customData: {
signature: initiatingSignatureOnAliceIngridAppDisactivationCommitment
}
} as ProtocolMessage;
const m8 = (yield [IO_SEND_AND_WAIT, m5]) as ProtocolMessage;
const {
customData: {
signature: intermediarySignatureOnAliceIngridAppDisactivationCommitment
}
} = m8;
assertIsValidSignature(
intermediaryAddress,
aliceIngridAppDisactivationCommitment,
intermediarySignatureOnAliceIngridAppDisactivationCommitment
);
await store.setCommitment(
[Protocol.Update, stateChannelWithIntermediary.freeBalance.identityHash],
aliceIngridAppDisactivationCommitment.getSignedTransaction([
initiatingSignatureOnAliceIngridAppDisactivationCommitment,
intermediarySignatureOnAliceIngridAppDisactivationCommitment
])
);
await store.saveStateChannel(stateChannelWithIntermediary);
await store.saveStateChannel(stateChannelWithAllThreeParties);
await store.saveStateChannel(stateChannelWithResponding);
},
1 /* Intermediary */: async function*(context: Context) {
const {
message: {
processID,
params,
customData: {
signature: initiatingSignatureOnTimeLockedPassThroughSetStateCommitment
}
},
provider,
store,
network
} = context;
const {
sharedData: { stateChannelsMap }
} = store;
const {
initiatorXpub,
responderXpub
} = params as UninstallVirtualAppParams;
const initiatorAddress = xkeyKthAddress(initiatorXpub, 0);
const responderAddress = xkeyKthAddress(responderXpub, 0);
const [
stateChannelWithAllThreeParties,
stateChannelWithInitiating,
stateChannelWithResponding,
timeLockedPassThroughAppInstance
] = await getUpdatedStateChannelAndAppInstanceObjectsForIntermediary(
stateChannelsMap,
params!,
provider,
network
);
const timeLockedPassThroughSetStateCommitment = new SetStateCommitment(
network,
timeLockedPassThroughAppInstance.identity,
timeLockedPassThroughAppInstance.hashOfLatestState,
timeLockedPassThroughAppInstance.appSeqNo,
timeLockedPassThroughAppInstance.defaultTimeout
);
assertIsValidSignature(
initiatorAddress,
timeLockedPassThroughSetStateCommitment,
initiatingSignatureOnTimeLockedPassThroughSetStateCommitment
);
const intermediarySignatureOnTimeLockedPassThroughSetStateCommitment = yield [
OP_SIGN,
timeLockedPassThroughSetStateCommitment
];
const m2 = {
processID,
params,
protocol: Protocol.UninstallVirtualApp,
seq: 2,
toXpub: responderXpub,
customData: {
signature: initiatingSignatureOnTimeLockedPassThroughSetStateCommitment,
signature2: intermediarySignatureOnTimeLockedPassThroughSetStateCommitment
}
} as ProtocolMessage;
const m3 = (yield [IO_SEND_AND_WAIT, m2]) as ProtocolMessage;
const {
customData: {
signature: respondingSignatureOnTimeLockedPassThroughSetStateCommitment
}
} = m3;
assertIsValidSignature(
responderAddress,
timeLockedPassThroughSetStateCommitment,
respondingSignatureOnTimeLockedPassThroughSetStateCommitment
);
await store.setCommitment(
[Protocol.Update, timeLockedPassThroughAppInstance.identityHash],
timeLockedPassThroughSetStateCommitment.getSignedTransaction([
initiatingSignatureOnTimeLockedPassThroughSetStateCommitment,
intermediarySignatureOnTimeLockedPassThroughSetStateCommitment,
respondingSignatureOnTimeLockedPassThroughSetStateCommitment
])
);
const m4 = {
processID,
protocol: Protocol.UninstallVirtualApp,
seq: UNASSIGNED_SEQ_NO,
toXpub: initiatorXpub,
customData: {
signature: respondingSignatureOnTimeLockedPassThroughSetStateCommitment,
signature2: intermediarySignatureOnTimeLockedPassThroughSetStateCommitment
}
} as ProtocolMessage;
const m5 = (yield [IO_SEND_AND_WAIT, m4]) as ProtocolMessage;
const {
customData: {
signature: initiatingSignatureOnAliceIngridAppDisactivationCommitment
}
} = m5;
const aliceIngridAppDisactivationCommitment = new SetStateCommitment(
network,
stateChannelWithInitiating.freeBalance.identity,
stateChannelWithInitiating.freeBalance.hashOfLatestState,
stateChannelWithInitiating.freeBalance.versionNumber,
stateChannelWithInitiating.freeBalance.timeout
);
assertIsValidSignature(
initiatorAddress,
aliceIngridAppDisactivationCommitment,
initiatingSignatureOnAliceIngridAppDisactivationCommitment
);
const intermediarySignatureOnAliceIngridAppDisactivationCommitment = yield [
OP_SIGN,
aliceIngridAppDisactivationCommitment
];
await store.setCommitment(
[Protocol.Update, stateChannelWithInitiating.freeBalance.identityHash],
aliceIngridAppDisactivationCommitment.getSignedTransaction([
initiatingSignatureOnAliceIngridAppDisactivationCommitment,
intermediarySignatureOnAliceIngridAppDisactivationCommitment
])
);
const ingridBobAppDisactivationCommitment = new SetStateCommitment(
network,
stateChannelWithResponding.freeBalance.identity,
stateChannelWithResponding.freeBalance.hashOfLatestState,
stateChannelWithResponding.freeBalance.versionNumber,
stateChannelWithResponding.freeBalance.timeout
);
const intermediarySignatureOnIngridBobAppDisactivationCommitment = yield [
OP_SIGN,
ingridBobAppDisactivationCommitment
];
const m6 = {
processID,
protocol: Protocol.UninstallVirtualApp,
seq: UNASSIGNED_SEQ_NO,
toXpub: responderXpub,
customData: {
signature: intermediarySignatureOnIngridBobAppDisactivationCommitment
}
} as ProtocolMessage;
const m7 = (yield [IO_SEND_AND_WAIT, m6]) as ProtocolMessage;
const {
customData: {
signature: respondingSignatureOnIngridBobAppDisactivationCommitment
}
} = m7;
assertIsValidSignature(
responderAddress,
ingridBobAppDisactivationCommitment,
respondingSignatureOnIngridBobAppDisactivationCommitment
);
await store.setCommitment(
[Protocol.Update, stateChannelWithResponding.freeBalance.identityHash],
ingridBobAppDisactivationCommitment.getSignedTransaction([
respondingSignatureOnIngridBobAppDisactivationCommitment,
intermediarySignatureOnIngridBobAppDisactivationCommitment
])
);
await store.saveStateChannel(stateChannelWithInitiating);
await store.saveStateChannel(stateChannelWithAllThreeParties);
await store.saveStateChannel(stateChannelWithResponding);
const m8 = {
processID,
protocol: Protocol.UninstallVirtualApp,
seq: UNASSIGNED_SEQ_NO,
toXpub: initiatorXpub,
customData: {
signature: intermediarySignatureOnAliceIngridAppDisactivationCommitment
}
} as ProtocolMessage;
yield [IO_SEND, m8];
},
2 /* Responding */: async function*(context: Context) {
const {
message: {
processID,
params,
customData: {
signature: initiatingSignatureOnTimeLockedPassThroughSetStateCommitment,
signature2: intermediarySignatureOnTimeLockedPassThroughSetStateCommitment
}
},
provider,
store,
network
} = context;
const {
sharedData: { stateChannelsMap }
} = store;
const {
initiatorXpub,
intermediaryXpub
} = params as UninstallVirtualAppParams;
const initiatorAddress = xkeyKthAddress(initiatorXpub, 0);
const intermediaryAddress = xkeyKthAddress(intermediaryXpub, 0);
const [
stateChannelWithAllThreeParties,
stateChannelWithIntermediary,
stateChannelWithInitiating,
timeLockedPassThroughAppInstance
] = await getUpdatedStateChannelAndAppInstanceObjectsForResponding(
stateChannelsMap,
params!,
provider,
network
);
const timeLockedPassThroughSetStateCommitment = new SetStateCommitment(
network,
timeLockedPassThroughAppInstance.identity,
timeLockedPassThroughAppInstance.hashOfLatestState,
timeLockedPassThroughAppInstance.appSeqNo,
timeLockedPassThroughAppInstance.defaultTimeout
);
assertIsValidSignature(
initiatorAddress,
timeLockedPassThroughSetStateCommitment,
initiatingSignatureOnTimeLockedPassThroughSetStateCommitment
);
assertIsValidSignature(
intermediaryAddress,
timeLockedPassThroughSetStateCommitment,
intermediarySignatureOnTimeLockedPassThroughSetStateCommitment
);
const respondingSignatureOnTimeLockedPassThroughSetStateCommitment = yield [
OP_SIGN,
timeLockedPassThroughSetStateCommitment
];
await store.setCommitment(
[Protocol.Update, timeLockedPassThroughAppInstance.identityHash],
timeLockedPassThroughSetStateCommitment.getSignedTransaction([
respondingSignatureOnTimeLockedPassThroughSetStateCommitment,
initiatingSignatureOnTimeLockedPassThroughSetStateCommitment,
intermediarySignatureOnTimeLockedPassThroughSetStateCommitment
])
);
const m3 = {
processID,
protocol: Protocol.UninstallVirtualApp,
seq: UNASSIGNED_SEQ_NO,
toXpub: intermediaryXpub,
customData: {
signature: respondingSignatureOnTimeLockedPassThroughSetStateCommitment
}
} as ProtocolMessage;
const m6 = (yield [IO_SEND_AND_WAIT, m3]) as ProtocolMessage;
const {
customData: {
signature: intermediarySignatureOnIngridBobAppDisactivationCommitment
}
} = m6;
const ingridBobAppDisactivationCommitment = new SetStateCommitment(
network,
stateChannelWithIntermediary.freeBalance.identity,
stateChannelWithIntermediary.freeBalance.hashOfLatestState,
stateChannelWithIntermediary.freeBalance.versionNumber,
stateChannelWithIntermediary.freeBalance.timeout
);
assertIsValidSignature(
intermediaryAddress,
ingridBobAppDisactivationCommitment,
intermediarySignatureOnIngridBobAppDisactivationCommitment
);
const respondingSignatureOnIngridBobAppDisactivationCommitment = yield [
OP_SIGN,
ingridBobAppDisactivationCommitment
];
await store.setCommitment(
[Protocol.Update, stateChannelWithIntermediary.freeBalance.identityHash],
ingridBobAppDisactivationCommitment.getSignedTransaction([
intermediarySignatureOnIngridBobAppDisactivationCommitment,
respondingSignatureOnIngridBobAppDisactivationCommitment
])
);
await store.saveStateChannel(stateChannelWithIntermediary);
await store.saveStateChannel(stateChannelWithAllThreeParties);
await store.saveStateChannel(stateChannelWithInitiating);
const m7 = {
processID,
protocol: Protocol.UninstallVirtualApp,
seq: UNASSIGNED_SEQ_NO,
toXpub: intermediaryXpub,
customData: {
signature: respondingSignatureOnIngridBobAppDisactivationCommitment
}
} as ProtocolMessage;
yield [IO_SEND, m7];
}
};
function getStateChannelFromMapWithOwners(
stateChannelsMap: { [multisigAddress: string]: StateChannelJSON },
userXpubs: string[],
network: NetworkContext
): StateChannel {
return StateChannel.fromJson(
stateChannelsMap[
getCreate2MultisigAddress(
userXpubs,
network.ProxyFactory,
network.MinimumViableMultisig
)
]
);
}
async function getUpdatedStateChannelAndAppInstanceObjectsForInitiating(
stateChannelsMap: { [multisigAddress: string]: StateChannelJSON },
params: ProtocolParameters,
provider: Provider,
network: NetworkContext
): Promise<[StateChannel, StateChannel, StateChannel, AppInstance]> {
const {
intermediaryXpub,
responderXpub,
initiatorXpub,
targetAppIdentityHash,
targetOutcome
} = params as UninstallVirtualAppParams;
const initiatorAddress = xkeyTo0thAddress(initiatorXpub);
const intermediaryAddress = xkeyTo0thAddress(intermediaryXpub);
const responderAddress = xkeyTo0thAddress(responderXpub);
const [
stateChannelWithAllThreeParties,
stateChannelWithIntermediary,
stateChannelWithResponding
] = [
getStateChannelFromMapWithOwners(
stateChannelsMap,
[initiatorXpub, responderXpub, intermediaryXpub],
network
),
getStateChannelFromMapWithOwners(
stateChannelsMap,
[initiatorXpub, intermediaryXpub],
network
),
getStateChannelFromMapWithOwners(
stateChannelsMap,
[initiatorXpub, responderXpub],
network
)
];
const agreement = stateChannelWithIntermediary.getSingleAssetTwoPartyIntermediaryAgreementFromVirtualApp(
targetAppIdentityHash
);
const { tokenAddress } = agreement;
const timeLockedPassThroughAppInstance = stateChannelWithAllThreeParties.getAppInstance(
agreement.timeLockedPassThroughIdentityHash
);
const virtualAppInstance = stateChannelWithResponding.getAppInstance(
timeLockedPassThroughAppInstance.state["targetAppIdentityHash"] // TODO: type
);
const virtualAppHasExpired = (timeLockedPassThroughAppInstance.state[
"switchesOutcomeAt"
] as BigNumber).lte(await provider.getBlockNumber());
const tokenIndexedIncrements = await computeTokenIndexedFreeBalanceIncrements(
virtualAppHasExpired
? timeLockedPassThroughAppInstance
: virtualAppInstance,
provider
);
return [
/**
* Remove the agreement from the app with the intermediary
*/
stateChannelWithAllThreeParties.removeAppInstance(
timeLockedPassThroughAppInstance.identityHash
),
/**
* Remove the agreement from the app with the intermediary
*/
stateChannelWithIntermediary.removeSingleAssetTwoPartyIntermediaryAgreement(
virtualAppInstance.identityHash,
{
[intermediaryAddress]:
tokenIndexedIncrements[tokenAddress][responderAddress],
[initiatorAddress]:
tokenIndexedIncrements[tokenAddress][initiatorAddress]
},
tokenAddress
),
/**
* Remove the virtual app itself
*/
stateChannelWithResponding.removeAppInstance(
virtualAppInstance.identityHash
),
/**
* Remove the TimeLockedPassThrough AppInstance in the 3-way channel
*/
timeLockedPassThroughAppInstance.setState({
...Object(timeLockedPassThroughAppInstance.state),
switchesOutcomeAt: 0,
defaultOutcome: targetOutcome
})
];
}
async function getUpdatedStateChannelAndAppInstanceObjectsForResponding(
stateChannelsMap: { [multisigAddress: string]: StateChannelJSON },
params: ProtocolParameters,
provider: Provider,
network: NetworkContext
): Promise<[StateChannel, StateChannel, StateChannel, AppInstance]> {
const {
intermediaryXpub,
responderXpub,
initiatorXpub,
targetAppIdentityHash,
targetOutcome
} = params as UninstallVirtualAppParams;
const initiatorAddress = xkeyTo0thAddress(initiatorXpub);
const intermediaryAddress = xkeyTo0thAddress(intermediaryXpub);
const responderAddress = xkeyTo0thAddress(responderXpub);
const [
stateChannelWithAllThreeParties,
stateChannelWithIntermediary,
stateChannelWithInitiating
] = [
getStateChannelFromMapWithOwners(
stateChannelsMap,
[initiatorXpub, responderXpub, intermediaryXpub],
network
),
getStateChannelFromMapWithOwners(
stateChannelsMap,
[responderXpub, intermediaryXpub],
network
),
getStateChannelFromMapWithOwners(
stateChannelsMap,
[initiatorXpub, responderXpub],
network
)
];
const agreement = stateChannelWithIntermediary.getSingleAssetTwoPartyIntermediaryAgreementFromVirtualApp(
targetAppIdentityHash
);
const { tokenAddress } = agreement;
const timeLockedPassThroughAppInstance = stateChannelWithAllThreeParties.getAppInstance(
agreement.timeLockedPassThroughIdentityHash
);
const virtualAppInstance = stateChannelWithInitiating.getAppInstance(
timeLockedPassThroughAppInstance.state["targetAppIdentityHash"] // TODO: type
);
const expectedOutcome = await virtualAppInstance.computeOutcomeWithCurrentState(
provider
);
if (expectedOutcome !== targetOutcome) {
throw Error(
"UninstallVirtualApp Protocol: Received targetOutcome that did not match expected outcome based on latest state of Virtual App."
);
}
const virtualAppHasExpired = (timeLockedPassThroughAppInstance.state[
"switchesOutcomeAt"
] as BigNumber).lte(await provider.getBlockNumber());
const tokenIndexedIncrements = await computeTokenIndexedFreeBalanceIncrements(
virtualAppHasExpired
? timeLockedPassThroughAppInstance
: virtualAppInstance,
provider
);
return [
/**
* Remove the agreement from the app with the intermediary
*/
stateChannelWithAllThreeParties.removeAppInstance(
timeLockedPassThroughAppInstance.identityHash
),
/**
* Remove the agreement from the app with the intermediary
*/
stateChannelWithIntermediary.removeSingleAssetTwoPartyIntermediaryAgreement(
virtualAppInstance.identityHash,
{
[intermediaryAddress]:
tokenIndexedIncrements[tokenAddress][initiatorAddress],
[responderAddress]:
tokenIndexedIncrements[tokenAddress][responderAddress]
},
tokenAddress
),
/**
* Remove the virtual app itself
*/
stateChannelWithInitiating.removeAppInstance(
virtualAppInstance.identityHash
),
/**
* Remove the TimeLockedPassThrough AppInstance in the 3-way channel
*/
timeLockedPassThroughAppInstance.setState({
...Object(timeLockedPassThroughAppInstance.state),
switchesOutcomeAt: 0,
defaultOutcome: expectedOutcome
})
];
}
async function getUpdatedStateChannelAndAppInstanceObjectsForIntermediary(
stateChannelsMap: { [multisigAddress: string]: StateChannelJSON },
params: ProtocolParameters,
provider: Provider,
network: NetworkContext
): Promise<[StateChannel, StateChannel, StateChannel, AppInstance]> {
const {
intermediaryXpub,
responderXpub,
initiatorXpub,
targetAppIdentityHash,
targetOutcome
} = params as UninstallVirtualAppParams;
const initiatorAddress = xkeyTo0thAddress(initiatorXpub);
const intermediaryAddress = xkeyTo0thAddress(intermediaryXpub);
const responderAddress = xkeyTo0thAddress(responderXpub);
const [
stateChannelWithAllThreeParties,
stateChannelWithInitiating,
stateChannelWithResponding
] = [
getStateChannelFromMapWithOwners(
stateChannelsMap,
[initiatorXpub, responderXpub, intermediaryXpub],
network
),
getStateChannelFromMapWithOwners(
stateChannelsMap,
[initiatorXpub, intermediaryXpub],
network
),
getStateChannelFromMapWithOwners(
stateChannelsMap,
[intermediaryXpub, responderXpub],
network
)
];
const agreementWithInitiating = stateChannelWithInitiating.getSingleAssetTwoPartyIntermediaryAgreementFromVirtualApp(
targetAppIdentityHash
);
const { tokenAddress } = agreementWithInitiating;
const timeLockedPassThroughAppInstance = stateChannelWithAllThreeParties.getAppInstance(
agreementWithInitiating.timeLockedPassThroughIdentityHash
);
const virtualAppHasExpired = (timeLockedPassThroughAppInstance.state[
"switchesOutcomeAt"
] as BigNumber).lte(await provider.getBlockNumber());
// FIXME: Come up with a better abstraction for this function. In this case,
// we want to pass in an outcome to use to compute the token indexed free
// balance increments, but the interfact of the function requires an AppInstance.
// Notice that I passed in an object for the AppInstance and an additional
// third parameter which is an `overrideOutcome`. That is generally messy code,
// so this TODO is to mark that we should improve this abstraction.
const tokenIndexedIncrements = await computeTokenIndexedFreeBalanceIncrements(
timeLockedPassThroughAppInstance,
provider,
virtualAppHasExpired
? (timeLockedPassThroughAppInstance.state["defaultOutcome"] as string)
: targetOutcome
);
return [
/**
* Remove the agreement from the 3-party app
*/
stateChannelWithAllThreeParties.removeAppInstance(
timeLockedPassThroughAppInstance.identityHash
),
/**
* Remove the agreement from the app with the initiating
*/
stateChannelWithInitiating.removeSingleAssetTwoPartyIntermediaryAgreement(
timeLockedPassThroughAppInstance.state["targetAppIdentityHash"],
{
[intermediaryAddress]:
tokenIndexedIncrements[tokenAddress][responderAddress],
[initiatorAddress]:
tokenIndexedIncrements[tokenAddress][initiatorAddress]
},
tokenAddress
),
/**
* Remove the agreement from the app with the responding
*/
stateChannelWithResponding.removeSingleAssetTwoPartyIntermediaryAgreement(
timeLockedPassThroughAppInstance.state["targetAppIdentityHash"],
{
[intermediaryAddress]:
tokenIndexedIncrements[tokenAddress][initiatorAddress],
[responderAddress]:
tokenIndexedIncrements[tokenAddress][responderAddress]
},
tokenAddress
),
/**
* Remove the TimeLockedPassThrough AppInstance in the 3-way channel
*/
timeLockedPassThroughAppInstance.setState({
...Object(timeLockedPassThroughAppInstance.state),
switchesOutcomeAt: 0,
defaultOutcome: targetOutcome
})
];
} | the_stack |
import { Badge, Button, Dropdown, Empty, Typography } from "antd"
import React, { useCallback, useEffect, useRef } from "react"
import { observer } from "mobx-react-lite"
import LeaderLine from "leader-line-new"
// @Store
import { apiKeysStore } from "stores/apiKeys"
import { sourcesStore } from "stores/sources"
import { destinationsStore } from "stores/destinations"
// @Components
import { EntityCard } from "lib/components/EntityCard/EntityCard"
import { EntityIcon } from "lib/components/EntityIcon/EntityIcon"
import { DropDownList } from "ui/components/DropDownList/DropDownList"
// @Icons
import { PlusOutlined } from "@ant-design/icons"
// @Utils
import { generatePath } from "react-router-dom"
// @Reference
import { destinationsReferenceList } from "catalog/destinations/lib"
import { destinationPageRoutes } from "../DestinationsPage/DestinationsPage.routes"
// @Styles
import styles from "./ConnectionsPage.module.less"
import { useServices } from "hooks/useServices"
import { throttle } from "lodash"
import Form from "antd/lib/form/Form"
import { APIKeyUtil } from "../../../utils/apiKeys.utils"
import { DestinationsUtils } from "../../../utils/destinations.utils"
import { SourcesUtils } from "../../../utils/sources.utils"
const CONNECTION_LINE_SIZE = 3
const CONNECTION_LINE_COLOR = "#415969"
const CONNECTION_LINE_HIGHLIGHTED_COLOR = "#878afc"
const connectionLines: { [key: string]: LeaderLine } = {}
const updateLinesPositions = () => {
// requestAnimationFrame(() => Object.values(connectionLines).forEach(line => line.position()))
// Object.values(connectionLines).forEach(line => line.position())
}
const ConnectionsPageComponent: React.FC = () => {
const containerRef = useRef<HTMLDivElement>(null)
const updateLines = () => {
destinationsStore.destinations.forEach(({ _uid, _onlyKeys = [], _sources = [] }) => {
;[..._onlyKeys, ..._sources].forEach(sourceId => {
const start = document.getElementById(sourceId)
const end = document.getElementById(_uid)
if (start && end && !connectionLines[`${sourceId}-${_uid}`])
connectionLines[`${sourceId}-${_uid}`] = new LeaderLine(start, end, {
endPlug: "behind",
startSocket: "right",
endSocket: "left",
color: CONNECTION_LINE_COLOR,
size: CONNECTION_LINE_SIZE,
})
})
})
}
const eraseLines = () => {
Object.entries(connectionLines).forEach(([key, line]) => {
line.remove()
delete connectionLines[key]
})
}
const handleCardMouseEnter = useCallback((sourceId: string) => {
Object.keys(connectionLines).forEach(key => {
if (key.startsWith(sourceId) || key.endsWith(sourceId)) {
connectionLines[key]?.setOptions({
color: CONNECTION_LINE_HIGHLIGHTED_COLOR,
})
} else {
connectionLines[key]?.setOptions({ size: 0.01 })
}
})
}, [])
const handleCardMouseLeave = useCallback(() => {
Object.keys(connectionLines).forEach(key => {
connectionLines[key]?.setOptions({ color: CONNECTION_LINE_COLOR })
connectionLines[key]?.setOptions({ size: CONNECTION_LINE_SIZE })
})
}, [])
useEffect(() => {
updateLines()
return () => {
eraseLines()
}
}, [destinationsStore.destinations, sourcesStore.sources, apiKeysStore.apiKeys])
useEffect(() => {
// move the lines on scroll
// containerRef.current.addEventListener("scroll", updateLinesPositions, { capture: true })
return () => {
// containerRef.current.removeEventListener("scroll", updateLinesPositions, { capture: true })
}
}, [])
return (
<div ref={containerRef} className="relative flex justify-center w-full h-full overflow-y-auto">
<div className="flex items-stretch w-full h-full max-w-3xl">
<Column
className="max-w-xs w-full"
header={
<div className="flex w-full mb-3">
<h3 className="block flex-auto text-3xl mb-0">{"Sources"}</h3>
<Dropdown
trigger={["click"]}
overlay={<AddSourceDropdownOverlay />}
className="flex-initial"
placement="bottomRight"
>
<Button type="ghost" size="large" icon={<PlusOutlined />}>
Add
</Button>
</Dropdown>
</div>
}
>
{apiKeysStore.hasApiKeys || sourcesStore.hasSources ? (
[
...apiKeysStore.apiKeys.map(apiKey => {
return (
<CardContainer id={apiKey.uid}>
<EntityCard
name={<CardTitle title={APIKeyUtil.getDisplayName(apiKey)} />}
message={<EntityMessage connectionTestOk={true} />}
link={"/api-keys/" + apiKey.uid}
icon={
<IconWrapper sizeTailwind={12}>
<EntityIcon entityType="api_key" />
</IconWrapper>
}
onMouseEnter={() => handleCardMouseEnter(apiKey.uid)}
onMouseLeave={handleCardMouseLeave}
/>
</CardContainer>
)
}),
...sourcesStore.sources.map(source => {
return (
<CardContainer id={source.sourceId}>
<EntityCard
name={<CardTitle title={SourcesUtils.getDisplayName(source)} />}
message={<EntityMessage connectionTestOk={source.connected} />}
link={`/sources/edit/${source.sourceId}`}
icon={
<IconWrapper sizeTailwind={12}>
<EntityIcon entityType="source" entitySubType={source.sourceProtoType} />
</IconWrapper>
}
onMouseEnter={() => handleCardMouseEnter(source.sourceId)}
onMouseLeave={handleCardMouseLeave}
/>
</CardContainer>
)
}),
]
) : (
<SourcesEmptyList />
)}
</Column>
<Column />
<Column
className="max-w-xs w-full"
header={
<div className="flex w-full mb-3">
<h3 className="block flex-auto text-3xl mb-0">{"Destinations"}</h3>
<Dropdown
trigger={["click"]}
placement="bottomRight"
overlay={
<DropDownList
hideFilter
list={destinationsReferenceList
.filter(dst => !dst["hidden"])
.map(dst => {
return {
title: dst.displayName,
id: dst.id,
icon: dst.ui.icon,
link: generatePath(destinationPageRoutes.newExact, {
type: dst.id,
}),
}
})}
/>
}
className="flex-initial"
>
<Button type="ghost" size="large" icon={<PlusOutlined />}>
Add
</Button>
</Dropdown>
</div>
}
>
{destinationsStore.hasDestinations ? (
destinationsStore.destinations.map(dst => {
return (
<CardContainer id={dst._uid}>
<EntityCard
name={<CardTitle title={DestinationsUtils.getDisplayName(dst)} />}
message={<EntityMessage connectionTestOk={dst._connectionTestOk} />}
link={`/destinations/edit/${dst._id}`}
icon={
<IconWrapper sizeTailwind={12}>
<EntityIcon entityType="destination" entitySubType={dst._type} />
</IconWrapper>
}
onMouseEnter={() => handleCardMouseEnter(dst._uid)}
onMouseLeave={handleCardMouseLeave}
/>
</CardContainer>
)
})
) : (
<DestinationsEmptyList />
)}
</Column>
</div>
</div>
)
}
const ConnectionsPage = observer(ConnectionsPageComponent)
ConnectionsPage.displayName = "ConnectionsPage"
export default ConnectionsPage
const AddSourceDropdownOverlay: React.FC = () => {
return (
<DropDownList
hideFilter
list={[
{
id: "api_key",
title: "Add JS Events API Key",
link: "/api_keys",
},
{
id: "connectors",
title: "Add Connector Source",
link: "/sources/add",
},
]}
/>
)
}
const EntityMessage: React.FC<{ connectionTestOk: boolean }> = ({ connectionTestOk }) => {
return (
<div>
<Badge
size="default"
status={connectionTestOk ? "processing" : "error"}
text={
connectionTestOk ? (
<span className={styles.processing}>{"Active"}</span>
) : (
<span className={styles.error}>{"Connection test failed"}</span>
)
}
/>
</div>
)
}
const IconWrapper: React.FC<{ sizeTailwind: number }> = ({ children, sizeTailwind }) => {
return <div className={`flex justify-center items-center h-${sizeTailwind} w-${sizeTailwind} m-3`}>{children}</div>
}
const Column: React.FC<{ header?: React.ReactNode; className?: string }> = ({ header, className, children }) => {
return (
<div className={`flex flex-col flex-auto ${className}`}>
{header && <div>{header}</div>}
<div className={`flex flex-col`}>{children}</div>
</div>
)
}
const CardContainer: React.FC<{ id: string }> = ({ id, children }) => {
return (
<div key={id} className={`my-2 w-full`} id={id}>
{children}
</div>
)
}
const ELLIPSIS_SUFFIX_LENGTH = 3
const CardTitle: React.FC<{ title: string }> = ({ title }) => {
const parsedTitle = {
start: title.slice(0, title.length - ELLIPSIS_SUFFIX_LENGTH),
end: title.slice(-ELLIPSIS_SUFFIX_LENGTH),
}
return (
<Typography.Text
className="w-full"
ellipsis={{
suffix: parsedTitle.end,
}}
>
{parsedTitle.start}
</Typography.Text>
)
}
const DestinationsEmptyList: React.FC = () => {
const services = useServices()
return (
<Empty
className="mt-20"
description={
<span>
The list is empty.{" "}
{services.features.createDemoDatabase && (
<>
You can add a destination manually or{" "}
<Button
type="link"
size="small"
className={styles.linkButton}
onClick={() => destinationsStore.createFreeDatabase()}
>
create a free demo database
</Button>{" "}
if you are just trying it out.
</>
)}
</span>
}
/>
)
}
const SourcesEmptyList: React.FC = () => {
return <Empty className="mt-20" description={`The list is empty`} />
} | the_stack |
namespace egret {
let PI = Math.PI;
let TwoPI = PI * 2;
let DEG_TO_RAD: number = PI / 180;
let matrixPool: Matrix[] = [];
/**
* The Matrix class represents a transformation matrix that determines how to map points from one coordinate space to
* another. You can perform various graphical transformations on a display object by setting the properties of a Matrix
* object, applying that Matrix object to the matrix property of a display object, These transformation functions include
* translation (x and y repositioning), rotation, scaling, and skewing.
* @version Egret 2.4
* @platform Web,Native
* @includeExample egret/geom/Matrix.ts
* @language en_US
*/
/**
* Matrix 类表示一个转换矩阵,它确定如何将点从一个坐标空间映射到另一个坐标空间。
* 您可以对一个显示对象执行不同的图形转换,方法是设置 Matrix 对象的属性,将该 Matrix
* 对象应用于显示对象的 matrix 属性。这些转换函数包括平移(x 和 y 重新定位)、旋转、缩放和倾斜。
* @version Egret 2.4
* @platform Web,Native
* @includeExample egret/geom/Matrix.ts
* @language zh_CN
*/
export class Matrix extends HashObject {
/**
* Releases a matrix instance to the object pool
* @param matrix matrix that Needs to be recycled
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 释放一个Matrix实例到对象池
* @param matrix 需要回收的 matrix
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public static release(matrix: Matrix): void {
if (!matrix) {
return;
}
matrixPool.push(matrix);
}
/**
* get a matrix instance from the object pool or create a new one.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 从对象池中取出或创建一个新的Matrix对象。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public static create(): Matrix {
let matrix = matrixPool.pop();
if (!matrix) {
matrix = new Matrix();
}
return matrix;
}
/**
* Creates a new Matrix object with the specified parameters.
* @param a The value that affects the positioning of pixels along the x axis when scaling or rotating an image.
* @param b The value that affects the positioning of pixels along the y axis when rotating or skewing an image.
* @param c The value that affects the positioning of pixels along the x axis when rotating or skewing an image.
* @param d The value that affects the positioning of pixels along the y axis when scaling or rotating an image..
* @param tx The distance by which to translate each point along the x axis.
* @param ty The distance by which to translate each point along the y axis.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 使用指定参数创建一个 Matrix 对象
* @param a 缩放或旋转图像时影响像素沿 x 轴定位的值。
* @param b 旋转或倾斜图像时影响像素沿 y 轴定位的值。
* @param c 旋转或倾斜图像时影响像素沿 x 轴定位的值。
* @param d 缩放或旋转图像时影响像素沿 y 轴定位的值。
* @param tx 沿 x 轴平移每个点的距离。
* @param ty 沿 y 轴平移每个点的距离。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
constructor(a: number = 1, b: number = 0, c: number = 0, d: number = 1, tx: number = 0, ty: number = 0) {
super();
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.tx = tx;
this.ty = ty;
}
/**
* The value that affects the positioning of pixels along the x axis when scaling or rotating an image.
* @default 1
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 缩放或旋转图像时影响像素沿 x 轴定位的值
* @default 1
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public a: number;
/**
* The value that affects the positioning of pixels along the y axis when rotating or skewing an image.
* @default 0
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 旋转或倾斜图像时影响像素沿 y 轴定位的值
* @default 0
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public b: number;
/**
* The value that affects the positioning of pixels along the x axis when rotating or skewing an image.
* @default 0
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 旋转或倾斜图像时影响像素沿 x 轴定位的值
* @default 0
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public c: number;
/**
* The value that affects the positioning of pixels along the y axis when scaling or rotating an image.
* @default 1
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 缩放或旋转图像时影响像素沿 y 轴定位的值
* @default 1
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public d: number;
/**
* The distance by which to translate each point along the x axis.
* @default 0
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 沿 x 轴平移每个点的距离
* @default 0
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public tx: number;
/**
* The distance by which to translate each point along the y axis.
* @default 0
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 沿 y 轴平移每个点的距离
* @default 0
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public ty: number;
/**
* Returns a new Matrix object that is a clone of this matrix, with an exact copy of the contained object.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 返回一个新的 Matrix 对象,它是此矩阵的克隆,带有与所含对象完全相同的副本。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public clone(): Matrix {
return new Matrix(this.a, this.b, this.c, this.d, this.tx, this.ty);
}
/**
* Concatenates a matrix with the current matrix, effectively combining the geometric effects of the two. In mathematical
* terms, concatenating two matrixes is the same as combining them using matrix multiplication.
* @param other The matrix to be concatenated to the source matrix.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 将某个矩阵与当前矩阵连接,从而将这两个矩阵的几何效果有效地结合在一起。在数学术语中,将两个矩阵连接起来与使用矩阵乘法将它们结合起来是相同的。
* @param other 要连接到源矩阵的矩阵。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public concat(other: Matrix): void {
let a = this.a * other.a;
let b = 0.0;
let c = 0.0;
let d = this.d * other.d;
let tx = this.tx * other.a + other.tx;
let ty = this.ty * other.d + other.ty;
if (this.b !== 0.0 || this.c !== 0.0 || other.b !== 0.0 || other.c !== 0.0) {
a += this.b * other.c;
d += this.c * other.b;
b += this.a * other.b + this.b * other.d;
c += this.c * other.a + this.d * other.c;
tx += this.ty * other.c;
ty += this.tx * other.b;
}
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.tx = tx;
this.ty = ty;
}
/**
* Copies all of the matrix data from the source Point object into the calling Matrix object.
* @param other The Matrix object from which to copy the data.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 将源 Matrix 对象中的所有矩阵数据复制到调用方 Matrix 对象中。
* @param other 要拷贝的目标矩阵
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public copyFrom(other: Matrix): Matrix {
this.a = other.a;
this.b = other.b;
this.c = other.c;
this.d = other.d;
this.tx = other.tx;
this.ty = other.ty;
return this;
}
/**
* Sets each matrix property to a value that causes a null transformation. An object transformed by applying an
* identity matrix will be identical to the original. After calling the identity() method, the resulting matrix
* has the following properties: a=1, b=0, c=0, d=1, tx=0, ty=0.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 为每个矩阵属性设置一个值,该值将导致矩阵无转换。通过应用恒等矩阵转换的对象将与原始对象完全相同。
* 调用 identity() 方法后,生成的矩阵具有以下属性:a=1、b=0、c=0、d=1、tx=0 和 ty=0。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public identity(): void {
this.a = this.d = 1;
this.b = this.c = this.tx = this.ty = 0;
}
/**
* Performs the opposite transformation of the original matrix. You can apply an inverted matrix to an object to
* undo the transformation performed when applying the original matrix.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 执行原始矩阵的逆转换。
* 您可以将一个逆矩阵应用于对象来撤消在应用原始矩阵时执行的转换。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public invert(): void {
this.$invertInto(this);
}
/**
* @private
*/
$invertInto(target: Matrix): void {
let a = this.a;
let b = this.b;
let c = this.c;
let d = this.d;
let tx = this.tx;
let ty = this.ty;
if (b == 0 && c == 0) {
target.b = target.c = 0;
if (a == 0 || d == 0) {
target.a = target.d = target.tx = target.ty = 0;
}
else {
a = target.a = 1 / a;
d = target.d = 1 / d;
target.tx = -a * tx;
target.ty = -d * ty;
}
return;
}
let determinant = a * d - b * c;
if (determinant == 0) {
target.identity();
return;
}
determinant = 1 / determinant;
let k = target.a = d * determinant;
b = target.b = -b * determinant;
c = target.c = -c * determinant;
d = target.d = a * determinant;
target.tx = -(k * tx + c * ty);
target.ty = -(b * tx + d * ty);
}
/**
* Applies a rotation transformation to the Matrix object.
* The rotate() method alters the a, b, c, and d properties of the Matrix object.
* @param angle The rotation angle in radians.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 对 Matrix 对象应用旋转转换。
* rotate() 方法将更改 Matrix 对象的 a、b、c 和 d 属性。
* @param angle 以弧度为单位的旋转角度。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public rotate(angle: number): void {
angle = +angle;
if (angle !== 0) {
angle = angle / DEG_TO_RAD;
let u = egret.NumberUtils.cos(angle);
let v = egret.NumberUtils.sin(angle);
let ta = this.a;
let tb = this.b;
let tc = this.c;
let td = this.d;
let ttx = this.tx;
let tty = this.ty;
this.a = ta * u - tb * v;
this.b = ta * v + tb * u;
this.c = tc * u - td * v;
this.d = tc * v + td * u;
this.tx = ttx * u - tty * v;
this.ty = ttx * v + tty * u;
}
}
/**
* Applies a scaling transformation to the matrix. The x axis is multiplied by sx, and the y axis it is multiplied by sy.
* The scale() method alters the a and d properties of the Matrix object.
* @param sx A multiplier used to scale the object along the x axis.
* @param sy A multiplier used to scale the object along the y axis.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 对矩阵应用缩放转换。x 轴乘以 sx,y 轴乘以 sy。
* scale() 方法将更改 Matrix 对象的 a 和 d 属性。
* @param sx 用于沿 x 轴缩放对象的乘数。
* @param sy 用于沿 y 轴缩放对象的乘数。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public scale(sx: number, sy: number): void {
if (sx !== 1) {
this.a *= sx;
this.c *= sx;
this.tx *= sx;
}
if (sy !== 1) {
this.b *= sy;
this.d *= sy;
this.ty *= sy;
}
}
/**
* Sets the members of Matrix to the specified values
* @param a The value that affects the positioning of pixels along the x axis when scaling or rotating an image.
* @param b The value that affects the positioning of pixels along the y axis when rotating or skewing an image.
* @param c The value that affects the positioning of pixels along the x axis when rotating or skewing an image.
* @param d The value that affects the positioning of pixels along the y axis when scaling or rotating an image..
* @param tx The distance by which to translate each point along the x axis.
* @param ty The distance by which to translate each point along the y axis.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 将 Matrix 的成员设置为指定值
* @param a 缩放或旋转图像时影响像素沿 x 轴定位的值。
* @param b 旋转或倾斜图像时影响像素沿 y 轴定位的值。
* @param c 旋转或倾斜图像时影响像素沿 x 轴定位的值。
* @param d 缩放或旋转图像时影响像素沿 y 轴定位的值。
* @param tx 沿 x 轴平移每个点的距离。
* @param ty 沿 y 轴平移每个点的距离。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public setTo(a: number, b: number, c: number, d: number, tx: number, ty: number): Matrix {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.tx = tx;
this.ty = ty;
return this;
}
/**
* Returns the result of applying the geometric transformation represented by the Matrix object to the specified point.
* @param pointX The x coordinate for which you want to get the result of the Matrix transformation.
* @param pointY The y coordinate for which you want to get the result of the Matrix transformation.
* @param resultPoint A reusable instance of Point for saving the results. Passing this parameter can reduce the
* number of reallocate objects, which allows you to get better code execution performance.
* @returns The point resulting from applying the Matrix transformation.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 返回将 Matrix 对象表示的几何转换应用于指定点所产生的结果。
* @param pointX 想要获得其矩阵转换结果的点的x坐标。
* @param pointY 想要获得其矩阵转换结果的点的y坐标。
* @param resultPoint 框架建议尽可能减少创建对象次数来优化性能,可以从外部传入一个复用的Point对象来存储结果,若不传入将创建一个新的Point对象返回。
* @returns 由应用矩阵转换所产生的点。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public transformPoint(pointX: number, pointY: number, resultPoint?: Point): Point {
let x = this.a * pointX + this.c * pointY + this.tx;
let y = this.b * pointX + this.d * pointY + this.ty;
if (resultPoint) {
resultPoint.setTo(x, y);
return resultPoint;
}
return new Point(x, y);
}
/**
* Translates the matrix along the x and y axes, as specified by the dx and dy parameters.
* @param dx The amount of movement along the x axis to the right, in pixels.
* @param dy The amount of movement down along the y axis, in pixels.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 沿 x 和 y 轴平移矩阵,由 dx 和 dy 参数指定。
* @param dx 沿 x 轴向右移动的量(以像素为单位)。
* @param dy 沿 y 轴向下移动的量(以像素为单位)。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public translate(dx: number, dy: number): void {
this.tx += dx;
this.ty += dy;
}
/**
* Determines whether two matrixes are equal.
* @param other The matrix to be compared.
* @returns A value of true if the object is equal to this Matrix object; false if it is not equal.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 是否与另一个矩阵数据相等
* @param other 要比较的另一个矩阵对象。
* @returns 是否相等,ture表示相等。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public equals(other: Matrix): boolean {
return this.a == other.a && this.b == other.b &&
this.c == other.c && this.d == other.d &&
this.tx == other.tx && this.ty == other.ty;
}
/**
* prepend matrix
* @param a The value that affects the positioning of pixels along the x axis when scaling or rotating an image.
* @param b The value that affects the positioning of pixels along the y axis when rotating or skewing an image.
* @param c The value that affects the positioning of pixels along the x axis when rotating or skewing an image.
* @param d The value that affects the positioning of pixels along the y axis when scaling or rotating an image..
* @param tx The distance by which to translate each point along the x axis.
* @param ty The distance by which to translate each point along the y axis.
* @returns matrix
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 前置矩阵
* @param a 缩放或旋转图像时影响像素沿 x 轴定位的值
* @param b 缩放或旋转图像时影响像素沿 y 轴定位的值
* @param c 缩放或旋转图像时影响像素沿 x 轴定位的值
* @param d 缩放或旋转图像时影响像素沿 y 轴定位的值
* @param tx 沿 x 轴平移每个点的距离
* @param ty 沿 y 轴平移每个点的距离
* @returns 矩阵自身
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public prepend(a: number, b: number, c: number, d: number, tx: number, ty: number): Matrix {
let tx1 = this.tx;
if (a != 1 || b != 0 || c != 0 || d != 1) {
let a1 = this.a;
let c1 = this.c;
this.a = a1 * a + this.b * c;
this.b = a1 * b + this.b * d;
this.c = c1 * a + this.d * c;
this.d = c1 * b + this.d * d;
}
this.tx = tx1 * a + this.ty * c + tx;
this.ty = tx1 * b + this.ty * d + ty;
return this;
}
/**
* append matrix
* @param a The value that affects the positioning of pixels along the x axis when scaling or rotating an image.
* @param b The value that affects the positioning of pixels along the y axis when rotating or skewing an image.
* @param c The value that affects the positioning of pixels along the x axis when rotating or skewing an image.
* @param d The value that affects the positioning of pixels along the y axis when scaling or rotating an image..
* @param tx The distance by which to translate each point along the x axis.
* @param ty The distance by which to translate each point along the y axis.
* @returns matrix
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 后置矩阵
* @param a 缩放或旋转图像时影响像素沿 x 轴定位的值
* @param b 缩放或旋转图像时影响像素沿 y 轴定位的值
* @param c 缩放或旋转图像时影响像素沿 x 轴定位的值
* @param d 缩放或旋转图像时影响像素沿 y 轴定位的值
* @param tx 沿 x 轴平移每个点的距离
* @param ty 沿 y 轴平移每个点的距离
* @returns 矩阵自身
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public append(a: number, b: number, c: number, d: number, tx: number, ty: number): Matrix {
let a1 = this.a;
let b1 = this.b;
let c1 = this.c;
let d1 = this.d;
if (a != 1 || b != 0 || c != 0 || d != 1) {
this.a = a * a1 + b * c1;
this.b = a * b1 + b * d1;
this.c = c * a1 + d * c1;
this.d = c * b1 + d * d1;
}
this.tx = tx * a1 + ty * c1 + this.tx;
this.ty = tx * b1 + ty * d1 + this.ty;
return this;
}
/**
* Given a point in the pretransform coordinate space, returns the coordinates of that point after the transformation occurs.
* Unlike the standard transformation applied using the transformPoint() method, the deltaTransformPoint() method's transformation does not consider the translation parameters tx and ty.
* @param point The point for which you want to get the result of the matrix transformation.
* @returns The point resulting from applying the matrix transformation.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 如果给定预转换坐标空间中的点,则此方法返回发生转换后该点的坐标。
* 与使用 transformPoint() 方法应用的标准转换不同,deltaTransformPoint() 方法的转换不考虑转换参数 tx 和 ty。
* @param point 想要获得其矩阵转换结果的点
* @returns 由应用矩阵转换所产生的点
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public deltaTransformPoint(point: Point): Point {
let self = this;
let x = self.a * point.x + self.c * point.y;
let y = self.b * point.x + self.d * point.y;
return new egret.Point(x, y);
}
/**
* Returns a text value listing the properties of the Matrix object.
* @returns A string containing the values of the properties of the Matrix object: a, b, c, d, tx, and ty.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 返回将 Matrix 对象表示的几何转换应用于指定点所产生的结果。
* @returns 一个字符串,它包含 Matrix 对象的属性值:a、b、c、d、tx 和 ty。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public toString(): string {
return "(a=" + this.a + ", b=" + this.b + ", c=" + this.c + ", d=" + this.d + ", tx=" + this.tx + ", ty=" + this.ty + ")";
}
/**
* Includes parameters for scaling, rotation, and translation. When applied to a matrix it sets the matrix's values based on those parameters.
* @param scaleX The factor by which to scale horizontally.
* @param scaleY The factor by which scale vertically.
* @param rotation The amount to rotate, in radians.
* @param tx The number of pixels to translate (move) to the right along the x axis.
* @param ty The number of pixels to translate (move) down along the y axis.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 包括用于缩放、旋转和转换的参数。当应用于矩阵时,该方法会基于这些参数设置矩阵的值。
* @param scaleX 水平缩放所用的系数
* @param scaleY 垂直缩放所用的系数
* @param rotation 旋转量(以弧度为单位)
* @param tx 沿 x 轴向右平移(移动)的像素数
* @param ty 沿 y 轴向下平移(移动)的像素数
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public createBox(scaleX: number, scaleY: number, rotation: number = 0, tx: number = 0, ty: number = 0): void {
let self = this;
if (rotation !== 0) {
rotation = rotation / DEG_TO_RAD;
let u = egret.NumberUtils.cos(rotation);
let v = egret.NumberUtils.sin(rotation);
self.a = u * scaleX;
self.b = v * scaleY;
self.c = -v * scaleX;
self.d = u * scaleY;
} else {
self.a = scaleX;
self.b = 0;
self.c = 0;
self.d = scaleY;
}
self.tx = tx;
self.ty = ty;
}
/**
* Creates the specific style of matrix expected by the beginGradientFill() and lineGradientStyle() methods of the Graphics class.
* Width and height are scaled to a scaleX/scaleY pair and the tx/ty values are offset by half the width and height.
* @param width The width of the gradient box.
* @param height The height of the gradient box.
* @param rotation The amount to rotate, in radians.
* @param tx The distance, in pixels, to translate to the right along the x axis. This value is offset by half of the width parameter.
* @param ty The distance, in pixels, to translate down along the y axis. This value is offset by half of the height parameter.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 创建 Graphics 类的 beginGradientFill() 和 lineGradientStyle() 方法所需的矩阵的特定样式。
* 宽度和高度被缩放为 scaleX/scaleY 对,而 tx/ty 值偏移了宽度和高度的一半。
* @param width 渐变框的宽度
* @param height 渐变框的高度
* @param rotation 旋转量(以弧度为单位)
* @param tx 沿 x 轴向右平移的距离(以像素为单位)。此值将偏移 width 参数的一半
* @param ty 沿 y 轴向下平移的距离(以像素为单位)。此值将偏移 height 参数的一半
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public createGradientBox(width: number, height: number, rotation: number = 0, tx: number = 0, ty: number = 0): void {
this.createBox(width / 1638.4, height / 1638.4, rotation, tx + width / 2, ty + height / 2);
}
/**
* @private
*/
$transformBounds(bounds: Rectangle): void {
let a = this.a;
let b = this.b;
let c = this.c;
let d = this.d;
let tx = this.tx;
let ty = this.ty;
let x = bounds.x;
let y = bounds.y;
let xMax = x + bounds.width;
let yMax = y + bounds.height;
let x0 = a * x + c * y + tx;
let y0 = b * x + d * y + ty;
let x1 = a * xMax + c * y + tx;
let y1 = b * xMax + d * y + ty;
let x2 = a * xMax + c * yMax + tx;
let y2 = b * xMax + d * yMax + ty;
let x3 = a * x + c * yMax + tx;
let y3 = b * x + d * yMax + ty;
let tmp = 0;
if (x0 > x1) {
tmp = x0;
x0 = x1;
x1 = tmp;
}
if (x2 > x3) {
tmp = x2;
x2 = x3;
x3 = tmp;
}
bounds.x = Math.floor(x0 < x2 ? x0 : x2);
bounds.width = Math.ceil((x1 > x3 ? x1 : x3) - bounds.x);
if (y0 > y1) {
tmp = y0;
y0 = y1;
y1 = tmp;
}
if (y2 > y3) {
tmp = y2;
y2 = y3;
y3 = tmp;
}
bounds.y = Math.floor(y0 < y2 ? y0 : y2);
bounds.height = Math.ceil((y1 > y3 ? y1 : y3) - bounds.y);
}
/**
* @private
*/
private getDeterminant() {
return this.a * this.d - this.b * this.c;
}
/**
* @private
*/
$getScaleX(): number {
let m = this;
if (m.b == 0) {
return m.a;
}
let result = Math.sqrt(m.a * m.a + m.b * m.b);
return this.getDeterminant() < 0 ? -result : result;
}
/**
* @private
*/
$getScaleY(): number {
let m = this;
if (m.c == 0) {
return m.d;
}
let result = Math.sqrt(m.c * m.c + m.d * m.d);
return this.getDeterminant() < 0 ? -result : result;
}
/**
* @private
*/
$getSkewX(): number {
if (this.d < 0) {
return Math.atan2(this.d, this.c) + (PI / 2);
}
else {
return Math.atan2(this.d, this.c) - (PI / 2);
}
}
/**
* @private
*/
$getSkewY(): number {
if(this.a < 0) {
return Math.atan2(this.b, this.a) - PI;
}
else {
return Math.atan2(this.b, this.a);
}
}
/**
* @private
*/
$updateScaleAndRotation(scaleX: number, scaleY: number, skewX: number, skewY: number) {
if ((skewX == 0 || skewX == TwoPI) && (skewY == 0 || skewY == TwoPI)) {
this.a = scaleX;
this.b = this.c = 0;
this.d = scaleY;
return;
}
skewX = skewX / DEG_TO_RAD;
skewY = skewY / DEG_TO_RAD;
let u = egret.NumberUtils.cos(skewX);
let v = egret.NumberUtils.sin(skewX);
if (skewX == skewY) {
this.a = u * scaleX;
this.b = v * scaleX;
} else {
this.a = egret.NumberUtils.cos(skewY) * scaleX;
this.b = egret.NumberUtils.sin(skewY) * scaleX;
}
this.c = -v * scaleY;
this.d = u * scaleY;
}
/**
* @private
* target = other * this
*/
$preMultiplyInto(other: Matrix, target: Matrix): void {
let a = other.a * this.a;
let b = 0.0;
let c = 0.0;
let d = other.d * this.d;
let tx = other.tx * this.a + this.tx;
let ty = other.ty * this.d + this.ty;
if (other.b !== 0.0 || other.c !== 0.0 || this.b !== 0.0 || this.c !== 0.0) {
a += other.b * this.c;
d += other.c * this.b;
b += other.a * this.b + other.b * this.d;
c += other.c * this.a + other.d * this.c;
tx += other.ty * this.c;
ty += other.tx * this.b;
}
target.a = a;
target.b = b;
target.c = c;
target.d = d;
target.tx = tx;
target.ty = ty;
}
}
/**
* @private
* 仅供框架内复用,要防止暴露引用到外部。
*/
export let $TempMatrix = new Matrix();
} | the_stack |
import cryptoRandomString from 'crypto-random-string';
import express from 'express';
import { GraphQLBoolean, GraphQLFloat, GraphQLList, GraphQLNonNull, GraphQLObjectType, GraphQLString } from 'graphql';
import { GraphQLJSON } from 'graphql-type-json';
import { cloneDeep, set } from 'lodash';
import plans from '../../../constants/plans';
import cache, { purgeAllCachesForAccount, purgeGQLCacheForCollective } from '../../../lib/cache';
import { purgeCacheForPage } from '../../../lib/cloudflare';
import { invalidateContributorsCache } from '../../../lib/contributors';
import { crypto } from '../../../lib/encryption';
import { mergeAccounts, simulateMergeAccounts } from '../../../lib/merge-accounts';
import { verifyTwoFactorAuthenticatorCode } from '../../../lib/two-factor-authentication';
import models, { sequelize } from '../../../models';
import { Forbidden, NotFound, Unauthorized, ValidationFailed } from '../../errors';
import { AccountCacheType } from '../enum/AccountCacheType';
import { AccountTypeToModelMapping } from '../enum/AccountType';
import { idDecode } from '../identifiers';
import { AccountReferenceInput, fetchAccountWithReference } from '../input/AccountReferenceInput';
import { AccountUpdateInput } from '../input/AccountUpdateInput';
import { Account } from '../interface/Account';
import { Host } from '../object/Host';
import { Individual } from '../object/Individual';
import { MergeAccountsResponse } from '../object/MergeAccountsResponse';
import AccountSettingsKey from '../scalar/AccountSettingsKey';
const AddTwoFactorAuthTokenToIndividualResponse = new GraphQLObjectType({
name: 'AddTwoFactorAuthTokenToIndividualResponse',
description: 'Response for the addTwoFactorAuthTokenToIndividual mutation',
fields: () => ({
account: {
type: new GraphQLNonNull(Individual),
description: 'The Individual that the 2FA has been enabled for',
},
recoveryCodes: {
type: new GraphQLList(GraphQLString),
description: 'The recovery codes for the Individual to write down',
},
}),
});
const accountMutations = {
editAccountSetting: {
type: new GraphQLNonNull(Account),
description: 'Edit the settings for the given account',
args: {
account: {
type: new GraphQLNonNull(AccountReferenceInput),
description: 'Account where the settings will be updated',
},
key: {
type: new GraphQLNonNull(AccountSettingsKey),
description: 'The key that you want to edit in settings',
},
value: {
type: new GraphQLNonNull(GraphQLJSON),
description: 'The value to set for this key',
},
},
async resolve(_: void, args, req: express.Request): Promise<Record<string, unknown>> {
if (!req.remoteUser) {
throw new Unauthorized();
}
return sequelize.transaction(async transaction => {
const account = await fetchAccountWithReference(args.account, {
dbTransaction: transaction,
lock: true,
throwIfMissing: true,
});
const isKeyEditableByHostAdmins = ['expenseTypes'].includes(args.key);
const permissionMethod = isKeyEditableByHostAdmins ? 'isAdminOfCollectiveOrHost' : 'isAdminOfCollective';
if (!req.remoteUser[permissionMethod](account)) {
throw new Forbidden();
}
if (
args.key === 'collectivePage' &&
![AccountTypeToModelMapping.FUND, AccountTypeToModelMapping.PROJECT].includes(account.type)
) {
const budgetSection = args.value.sections?.find(s => s.section === 'budget');
if (budgetSection && !budgetSection.isEnabled) {
throw new Forbidden();
}
}
const settings = account.settings ? cloneDeep(account.settings) : {};
set(settings, args.key, args.value);
return account.update({ settings }, { transaction });
});
},
},
editAccountFeeStructure: {
type: new GraphQLNonNull(Account),
description: 'An endpoint for hosts to edit the fees structure of their hosted accounts',
args: {
account: {
type: new GraphQLNonNull(AccountReferenceInput),
description: 'Account where the settings will be updated',
},
hostFeePercent: {
type: new GraphQLNonNull(GraphQLFloat),
description: 'The host fee percent to apply to this account',
},
isCustomFee: {
type: new GraphQLNonNull(GraphQLBoolean),
description: 'If using a custom fee, set this to true',
},
},
async resolve(_: void, args, req: express.Request): Promise<Record<string, unknown>> {
return sequelize.transaction(async dbTransaction => {
const account = await fetchAccountWithReference(args.account, {
throwIfMissing: true,
dbTransaction,
lock: true,
});
if (!account.HostCollectiveId) {
throw new ValidationFailed('Fees structure can only be edited for accounts that you are hosting');
} else if (!req.remoteUser?.isAdmin(account.HostCollectiveId)) {
throw new Forbidden(
'You need to be logged in as an host admin to change the fees structure of the hosted accounts',
);
} else if (!account.approvedAt) {
throw new ValidationFailed('The collective needs to be approved before you can change the fees structure');
}
return account.update(
{
hostFeePercent: args.hostFeePercent,
data: { ...account.data, useCustomHostFee: args.isCustomFee },
},
{ transaction: dbTransaction },
);
});
},
},
addTwoFactorAuthTokenToIndividual: {
type: new GraphQLNonNull(AddTwoFactorAuthTokenToIndividualResponse),
description: 'Add 2FA to the Individual if it does not have it',
args: {
account: {
type: new GraphQLNonNull(AccountReferenceInput),
description: 'Individual that will have 2FA added to it',
},
token: {
type: new GraphQLNonNull(GraphQLString),
description: 'The generated secret to save to the Individual',
},
},
async resolve(_: void, args, req: express.Request): Promise<Record<string, unknown>> {
if (!req.remoteUser) {
throw new Unauthorized();
}
const account = await fetchAccountWithReference(args.account);
if (!req.remoteUser.isAdminOfCollective(account)) {
throw new Forbidden();
}
const user = await models.User.findOne({ where: { CollectiveId: account.id } });
if (!user) {
throw new NotFound('Account not found.');
}
if (user.twoFactorAuthToken !== null) {
throw new Unauthorized('This account already has 2FA enabled.');
}
/*
check that base32 secret is only capital letters, numbers (2-7), 103 chars long;
Our secret is 64 ascii characters which is encoded into 104 base32 characters
(base32 should be divisible by 8). But the last character is an = to pad, and
speakeasy library cuts out any = padding
**/
const verifyToken = args.token.match(/([A-Z2-7]){103}/);
if (!verifyToken) {
throw new ValidationFailed('Invalid 2FA token');
}
const encryptedText = crypto.encrypt(args.token);
/** Generate recovery codes, hash and store them in the table, and return them to the user to write down */
const recoveryCodesArray = Array.from({ length: 6 }, () =>
cryptoRandomString({ length: 16, type: 'distinguishable' }),
);
const hashedRecoveryCodesArray = recoveryCodesArray.map(code => {
return crypto.hash(code);
});
await user.update({ twoFactorAuthToken: encryptedText, twoFactorAuthRecoveryCodes: hashedRecoveryCodesArray });
return { account: account, recoveryCodes: recoveryCodesArray };
},
},
removeTwoFactorAuthTokenFromIndividual: {
type: new GraphQLNonNull(Individual),
description: 'Remove 2FA from the Individual if it has been enabled',
args: {
account: {
type: new GraphQLNonNull(AccountReferenceInput),
description: 'Account that will have 2FA removed from it',
},
code: {
type: new GraphQLNonNull(GraphQLString),
description: 'The 6-digit 2FA code',
},
},
async resolve(_: void, args, req: express.Request): Promise<Record<string, unknown>> {
if (!req.remoteUser) {
throw new Unauthorized();
}
const account = await fetchAccountWithReference(args.account);
if (!req.remoteUser.isAdminOfCollective(account)) {
throw new Forbidden();
}
const user = await models.User.findOne({ where: { CollectiveId: account.id } });
if (!user) {
throw new NotFound('Account not found.');
}
if (!user.twoFactorAuthToken) {
throw new Unauthorized('This account already has 2FA disabled.');
}
const verified = verifyTwoFactorAuthenticatorCode(user.twoFactorAuthToken, args.code);
if (!verified) {
throw new Unauthorized('Two-factor authentication code failed. Please try again');
}
await user.update({ twoFactorAuthToken: null, twoFactorAuthRecoveryCodes: null });
return account;
},
},
editHostPlan: {
type: new GraphQLNonNull(Host),
description: 'Update the plan',
args: {
account: {
type: new GraphQLNonNull(AccountReferenceInput),
description: 'Account where the host plan will be edited.',
},
plan: {
type: new GraphQLNonNull(GraphQLString),
description: 'The name of the plan to subscribe to.',
},
},
async resolve(_: void, args, req: express.Request): Promise<Record<string, unknown>> {
if (!req.remoteUser) {
throw new Unauthorized();
}
const account = await fetchAccountWithReference(args.account);
if (!req.remoteUser.isAdminOfCollective(account)) {
throw new Forbidden();
}
if (!account.isHostAccount) {
throw new Error(`Only Fiscal Hosts can set their plan.`);
}
const plan = args.plan;
if (!plans[plan]) {
throw new Error(`Unknown plan: ${plan}`);
}
await account.update({ plan });
if (plan === 'start-plan-2021') {
// This should cascade to all Collectives
await account.updateHostFee(0, req.remoteUser);
}
if (plan === 'start-plan-2021' || plan === 'grow-plan-2021') {
// This should cascade to all Collectives
await account.updatePlatformFee(0, req.remoteUser);
// Make sure budget is activated
await account.activateBudget();
}
await cache.del(`plan_${account.id}`);
return account;
},
},
editAccount: {
type: new GraphQLNonNull(Host),
description: 'Edit key properties of an account.',
args: {
account: {
type: new GraphQLNonNull(AccountUpdateInput),
description: 'Account to edit.',
},
},
async resolve(_: void, args, req: express.Request): Promise<Record<string, unknown>> {
if (!req.remoteUser) {
throw new Unauthorized();
}
const id = idDecode(args.account.id, 'account');
const account = await req.loaders.Collective.byId.load(id);
if (!account) {
throw new NotFound('Account Not Found');
}
if (!req.remoteUser.isAdminOfCollective(account) && !req.remoteUser.isRoot()) {
throw new Forbidden();
}
for (const key of Object.keys(args.account)) {
switch (key) {
case 'currency':
await account.setCurrency(args.account[key]);
}
}
return account;
},
},
clearCacheForAccount: {
type: new GraphQLNonNull(Account),
description: '[Root only] Clears the cache for a given account',
args: {
account: {
type: new GraphQLNonNull(AccountReferenceInput),
description: 'Account to clear the cache for',
},
type: {
type: new GraphQLNonNull(new GraphQLList(AccountCacheType)),
description: 'Types of cache to clear',
defaultValue: ['CLOUDFLARE', 'GRAPHQL_QUERIES', 'CONTRIBUTORS'],
},
},
async resolve(_: void, args, req: express.Request): Promise<Record<string, unknown>> {
if (!req.remoteUser?.isRoot()) {
throw new Forbidden('Only root users can perform this action');
}
const account = await fetchAccountWithReference(args.account, { throwIfMissing: true });
if (args.type.includes('CLOUDFLARE')) {
purgeCacheForPage(`/${account.slug}`);
}
if (args.type.includes('GRAPHQL_QUERIES')) {
purgeGQLCacheForCollective(account.slug);
}
if (args.type.includes('CONTRIBUTORS')) {
await invalidateContributorsCache(account.id);
}
return account;
},
},
mergeAccounts: {
type: new GraphQLNonNull(MergeAccountsResponse),
description: '[Root only] Merge two accounts, returns the result account',
args: {
fromAccount: {
type: new GraphQLNonNull(AccountReferenceInput),
description: 'Account to merge from',
},
toAccount: {
type: new GraphQLNonNull(AccountReferenceInput),
description: 'Account to merge to',
},
dryRun: {
type: new GraphQLNonNull(GraphQLBoolean),
description: 'If true, the result will be simulated and summarized in the response message',
defaultValue: true,
},
},
async resolve(_: void, args, req: express.Request): Promise<Record<string, unknown>> {
if (!req.remoteUser?.isRoot()) {
throw new Forbidden('Only root users can perform this action');
}
const fromAccount = await fetchAccountWithReference(args.fromAccount, { throwIfMissing: true });
const toAccount = await fetchAccountWithReference(args.toAccount, { throwIfMissing: true });
if (args.dryRun) {
const message = await simulateMergeAccounts(fromAccount, toAccount);
return { account: toAccount, message };
} else {
const warnings = await mergeAccounts(fromAccount, toAccount, req.remoteUser.id);
await Promise.all([purgeAllCachesForAccount(fromAccount), purgeAllCachesForAccount(toAccount)]).catch(() => {
// Ignore errors
});
const message = warnings.join('\n');
return { account: await toAccount.reload(), message: message || null };
}
},
},
};
export default accountMutations; | the_stack |
import * as React from "react";
import { classNames, ClassValue } from "../util/ClassNames";
import {
CaretCoordinates,
getCaretCoordinates
} from "../util/TextAreaCaretPosition";
import { Suggestion } from "../types";
import { insertText } from "../util/InsertTextAtPosition";
import { mod } from "../util/Math";
import { SuggestionsDropdown } from "./SuggestionsDropdown";
import {
ButtonHTMLAttributes,
DetailedHTMLFactory,
TextareaHTMLAttributes
} from "react";
import { ComponentSimilarTo } from "../util/type-utils";
export interface MentionState {
status: "active" | "inactive" | "loading";
/**
* Selection start by the time the mention was activated
*/
startPosition?: number;
focusIndex?: number;
caret?: CaretCoordinates;
suggestions: Suggestion[];
/**
* The character that triggered the mention. Example: @
*/
triggeredBy?: string;
}
export interface TextAreaState {
mention: MentionState;
}
export interface TextAreaProps {
classes?: ClassValue;
suggestionsDropdownClasses?: ClassValue;
value: string;
onChange: (value: string) => void;
refObject?: React.RefObject<HTMLTextAreaElement>;
readOnly?: boolean;
height?: number;
heightUnits?: string;
suggestionTriggerCharacters?: string[];
suggestionsAutoplace?: boolean;
loadSuggestions?: (
text: string,
triggeredBy: string
) => Promise<Suggestion[]>;
onPaste: React.ClipboardEventHandler;
onDrop: React.DragEventHandler;
/**
* Custom textarea component. "textAreaComponent" can be any React component which
* props are a subset of the props of an HTMLTextAreaElement
*/
textAreaComponent?: ComponentSimilarTo<
HTMLTextAreaElement,
TextareaHTMLAttributes<HTMLTextAreaElement>
>;
toolbarButtonComponent?: ComponentSimilarTo<
HTMLButtonElement,
ButtonHTMLAttributes<HTMLButtonElement>
>;
textAreaProps?: Partial<
React.DetailedHTMLProps<
React.TextareaHTMLAttributes<HTMLTextAreaElement>,
HTMLTextAreaElement
>
>;
/**
* On keydown, the TextArea will trigger "onPossibleKeyCommand" as an opportunity for React-Mde to
* execute a command. If a command is executed, React-Mde should return true, otherwise, false.
*/
onPossibleKeyCommand?: (
e: React.KeyboardEvent<HTMLTextAreaElement>
) => boolean;
}
export class TextArea extends React.Component<TextAreaProps, TextAreaState> {
currentLoadSuggestionsPromise?: Promise<unknown> = Promise.resolve(undefined);
/**
* suggestionsPromiseIndex exists as a means to cancel what happens when the suggestions promise finishes loading.
*
* When the user is searching for suggestions, there is a promise that, when resolved, causes a re-render.
* However, in case there is another promise to be resolved after the current one, it does not make sense to re-render
* only to re-render again after the next one is complete.
*
* When there is a promise loading and the user cancels the suggestion, you don't want the status to go back to "active"
* when the promise resolves.
*
* suggestionsPromiseIndex increments every time the mentions query
*/
suggestionsPromiseIndex: number = 0;
constructor(props) {
super(props);
this.state = { mention: { status: "inactive", suggestions: [] } };
}
suggestionsEnabled() {
return (
this.props.suggestionTriggerCharacters &&
this.props.suggestionTriggerCharacters.length &&
this.props.loadSuggestions
);
}
getTextArea = (): HTMLTextAreaElement => {
return this.props.refObject.current;
};
handleOnChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
const { onChange } = this.props;
onChange(event.target.value);
};
handleBlur = () => {
const { mention } = this.state;
if (mention) {
this.setState({ mention: { status: "inactive", suggestions: [] } });
}
};
startLoadingSuggestions = (text: string) => {
const promiseIndex = ++this.suggestionsPromiseIndex;
const { loadSuggestions } = this.props;
this.currentLoadSuggestionsPromise = this.currentLoadSuggestionsPromise
.then(() => loadSuggestions(text, this.state.mention.triggeredBy))
.then(suggestions => {
if (this.state.mention.status === "inactive") {
// This means this promise resolved too late when the status has already been set to inactice
return;
} else if (this.suggestionsPromiseIndex === promiseIndex) {
if (!suggestions || !suggestions.length) {
this.setState({
mention: {
status: "inactive",
suggestions: []
}
});
} else {
this.setState({
mention: {
...this.state.mention,
status: "active",
suggestions,
focusIndex: 0
}
});
}
this.suggestionsPromiseIndex = 0;
}
return Promise.resolve();
});
};
loadEmptySuggestion = (target: HTMLTextAreaElement, key: string) => {
const caret = getCaretCoordinates(target, key);
this.startLoadingSuggestions("");
this.setState({
mention: {
status: "loading",
startPosition: target.selectionStart + 1,
caret: caret,
suggestions: [],
triggeredBy: key
}
});
};
handleSuggestionSelected = (index: number) => {
const { mention } = this.state;
this.getTextArea().selectionStart = mention.startPosition - 1;
const textForInsert = this.props.value.substr(
this.getTextArea().selectionStart,
this.getTextArea().selectionEnd - this.getTextArea().selectionStart
);
insertText(this.getTextArea(), mention.suggestions[index].value + " ");
this.setState({
mention: {
status: "inactive",
suggestions: []
}
});
};
handleKeyDown = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (this.props.onPossibleKeyCommand) {
const handled = this.props.onPossibleKeyCommand(event);
if (handled) {
event.preventDefault();
// If the keydown resulted in a command being executed, we will just close the suggestions if they are open.
// Resetting suggestionsPromiseIndex will cause any promise that is yet to be resolved to have no effect
// when they finish loading.
// TODO: The code below is duplicate, we need to clean this up
this.suggestionsPromiseIndex = 0;
this.setState({
mention: {
status: "inactive",
suggestions: []
}
});
return;
}
}
if (!this.suggestionsEnabled()) {
return;
}
const { key, shiftKey, currentTarget } = event;
const { selectionStart } = currentTarget;
const { mention } = this.state;
switch (mention.status) {
case "loading":
case "active":
if (
key === "Escape" ||
(key === "Backspace" &&
selectionStart <= this.state.mention.startPosition)
) {
// resetting suggestionsPromiseIndex will cause any promise that is yet to be resolved to have no effect
// when they finish loading.
this.suggestionsPromiseIndex = 0;
this.setState({
mention: {
status: "inactive",
suggestions: []
}
});
} else if (
mention.status === "active" &&
(key === "ArrowUp" || key === "ArrowDown") &&
!shiftKey
) {
event.preventDefault();
const focusDelta = key === "ArrowUp" ? -1 : 1;
this.setState({
mention: {
...mention,
focusIndex: mod(
mention.focusIndex + focusDelta,
mention.suggestions.length
)
}
});
} else if (
key === "Enter" &&
mention.status === "active" &&
mention.suggestions.length
) {
event.preventDefault();
this.handleSuggestionSelected(mention.focusIndex);
}
break;
default:
// Ignore
}
};
handleKeyUp = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
const { key } = event;
const { mention } = this.state;
const { suggestionTriggerCharacters, value } = this.props;
switch (mention.status) {
case "loading":
case "active":
if (key === "Backspace") {
const searchText = value.substr(
mention.startPosition,
this.getTextArea().selectionStart - mention.startPosition
);
this.startLoadingSuggestions(searchText);
if (mention.status !== "loading") {
this.setState({
mention: {
...this.state.mention,
status: "loading"
}
});
}
}
break;
case "inactive":
if (key === "Backspace") {
const prevChar = value.charAt(this.getTextArea().selectionStart - 1);
const isAtMention = suggestionTriggerCharacters.includes(
value.charAt(this.getTextArea().selectionStart - 1)
);
if (isAtMention) {
this.loadEmptySuggestion(event.currentTarget, prevChar);
}
}
break;
default:
// Ignore
}
};
handleKeyPress = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
const { suggestionTriggerCharacters, value } = this.props;
const { mention } = this.state;
const { key } = event;
switch (mention.status) {
case "loading":
case "active":
if (key === " ") {
this.setState({
mention: {
...this.state.mention,
status: "inactive"
}
});
return;
}
const searchText =
value.substr(
mention.startPosition,
this.getTextArea().selectionStart - mention.startPosition
) + key;
// In this case, the mentions box was open but the user typed something else
this.startLoadingSuggestions(searchText);
if (mention.status !== "loading") {
this.setState({
mention: {
...this.state.mention,
status: "loading"
}
});
}
break;
case "inactive":
if (
suggestionTriggerCharacters.indexOf(event.key) === -1 ||
!/\s|\(|\[|^.{0}$/.test(
value.charAt(this.getTextArea().selectionStart - 1)
)
) {
return;
}
this.loadEmptySuggestion(event.currentTarget, event.key);
break;
}
};
render() {
const {
classes,
readOnly,
textAreaProps,
height,
heightUnits,
value,
suggestionTriggerCharacters,
loadSuggestions,
suggestionsDropdownClasses,
textAreaComponent,
onPaste,
onDrop
} = this.props;
const suggestionsEnabled =
suggestionTriggerCharacters &&
suggestionTriggerCharacters.length &&
loadSuggestions;
const { mention } = this.state;
const TextAreaComponent = (textAreaComponent ||
"textarea") as DetailedHTMLFactory<
TextareaHTMLAttributes<HTMLTextAreaElement>,
HTMLTextAreaElement
>;
const heightVal = height && heightUnits ? height + heightUnits : height;
return (
<div className="mde-textarea-wrapper">
<TextAreaComponent
className={classNames("mde-text", classes)}
style={{ height: heightVal }}
ref={this.props.refObject}
readOnly={readOnly}
value={value}
data-testid="text-area"
{...textAreaProps}
onChange={event => {
textAreaProps?.onChange?.(event);
this.handleOnChange(event);
}}
onBlur={event => {
textAreaProps?.onBlur?.(event);
if (suggestionsEnabled) {
this.handleBlur();
}
}}
onKeyDown={event => {
textAreaProps?.onKeyDown?.(event);
this.handleKeyDown(event);
}}
onKeyUp={event => {
textAreaProps?.onKeyUp?.(event);
if (suggestionsEnabled) {
this.handleKeyUp(event);
}
}}
onKeyPress={event => {
textAreaProps?.onKeyPress?.(event);
if (suggestionsEnabled) {
this.handleKeyPress(event);
}
}}
onPaste={event => {
textAreaProps?.onPaste?.(event);
onPaste(event);
}}
onDragOver={event => {
event.preventDefault();
event.stopPropagation();
}}
onDrop={event => {
textAreaProps?.onDrop?.(event);
onDrop(event);
event.preventDefault();
}}
/>
{mention.status === "active" && mention.suggestions.length && (
<SuggestionsDropdown
classes={suggestionsDropdownClasses}
caret={mention.caret}
suggestions={mention.suggestions}
onSuggestionSelected={this.handleSuggestionSelected}
suggestionsAutoplace={this.props.suggestionsAutoplace}
focusIndex={mention.focusIndex}
textAreaRef={this.props.refObject}
/>
)}
</div>
);
}
} | the_stack |
import "../assets/main.css";
function createEl<K extends keyof HTMLElementTagNameMap>(
tag: K,
t?: string | DomElementInfo,
e?: HTMLElement
): HTMLElementTagNameMap[K] {
const i = document.createElement(tag);
"string" == typeof t &&
(t = {
cls: t
});
const r = t || {},
o = r.cls,
s = r.text,
a = r.attr,
l = r.title,
c = r.value,
u = r.type,
h = e ? e : r.parent,
p = r.prepend,
d = r.href;
return (
o &&
(Array.isArray(o)
? (i.className = o.join(" "))
: (i.className = o)),
s && (i.textContent = s),
a &&
Object.keys(a).forEach((t) => {
const n = a[t];
null !== n && i.setAttribute(t, String(n));
}),
l && (i.title = l),
c &&
(i instanceof HTMLInputElement ||
i instanceof HTMLSelectElement ||
i instanceof HTMLOptionElement) &&
(i.value = c),
/* u && i instanceof HTMLInputElement && (i.type = u), */
u && i instanceof HTMLStyleElement && i.setAttribute("type", u),
d &&
(i instanceof HTMLAnchorElement || i instanceof HTMLLinkElement) &&
(i.href = d),
h && (p ? h.insertBefore(i, h.firstChild) : h.appendChild(i)),
i
);
}
//@ts-ignore-line
const createDiv = function (
o?: string | DomElementInfo,
e?: HTMLElement
): HTMLDivElement {
return createEl("div", o, e);
};
Node.prototype.createDiv = function (
o?: string | DomElementInfo,
cb?: (el: HTMLDivElement) => void
): HTMLDivElement {
return createDiv(o, this);
};
Node.prototype.createEl = function <K extends keyof HTMLElementTagNameMap>(
tag: K,
o?: string | DomElementInfo,
cb?: (el: HTMLElementTagNameMap[K]) => void
): HTMLElementTagNameMap[K] {
return createEl(tag, o, this);
};
Element.prototype.addClass = function (...args) {
const e = [];
for (let t = 0; t < args.length; t++) e[t] = args[t];
this.addClasses(e);
};
Element.prototype.addClasses = function (e) {
for (let t = 0; t < e.length; t++) this.classList.add(e[t]);
};
function getAdmonitionElement(
type: string,
title: string,
icon: string,
color: string,
collapse?: string,
id?: string
): HTMLElement {
let admonition,
titleEl,
attrs: { style: string; open?: string } = {
style: `--admonition-color: ${color};`
};
if (collapse && collapse != "none") {
if (collapse === "open") {
attrs.open = "open";
}
admonition = createEl("details", {
cls: `admonition admonition-${type} admonition-plugin`,
attr: attrs
});
titleEl = admonition.createEl("summary", {
cls: `admonition-title ${!title?.trim().length ? "no-title" : ""}`
});
} else {
admonition = createDiv({
cls: `admonition admonition-${type} admonition-plugin`,
attr: attrs
});
titleEl = admonition.createDiv({
cls: `admonition-title ${!title?.trim().length ? "no-title" : ""}`
});
}
if (id) {
admonition.id = id;
}
if (title && title.trim().length) {
/**
* Title structure
* <div|summary>.admonition-title
* <element>.admonition-title-content - Rendered Markdown top-level element (e.g. H1/2/3 etc, p)
* div.admonition-title-icon
* svg
* div.admonition-title-markdown - Container of rendered markdown
* ...rendered markdown children...
*/
//get markdown
const markdownHolder = createDiv();
//MarkdownRenderer.renderMarkdown(title, markdownHolder, "", null);
//admonition-title-content is first child of rendered markdown
const admonitionTitleContent =
/* markdownHolder?.children[0]?.tagName === "P"
? createDiv()
: markdownHolder.children[0] ?? */ createDiv();
//get children of markdown element, then remove them
const markdownElements = Array.from(
markdownHolder.children[0]?.childNodes || []
);
admonitionTitleContent.innerHTML = "";
admonitionTitleContent.addClass("admonition-title-content");
//build icon element
const iconEl = admonitionTitleContent.createDiv(
"admonition-title-icon"
);
if (icon) {
iconEl.innerHTML = icon;
}
//add markdown children back
const admonitionTitleMarkdown = admonitionTitleContent.createDiv(
"admonition-title-markdown"
);
admonitionTitleMarkdown.innerText = title;
/* for (let i = 0; i < markdownElements.length; i++) {
admonitionTitleMarkdown.appendChild(markdownElements[i]);
} */
titleEl.appendChild(admonitionTitleContent || createDiv());
}
//add them to title element
if (collapse) {
titleEl.createDiv("collapser").createDiv("handle");
}
return admonition;
}
function startsWithAny(str: string, needles: string[]) {
for (let i = 0; i < needles.length; i++) {
if (str.startsWith(needles[i])) {
return i;
}
}
return false;
}
function getParametersFromSource(type: string, src: string) {
const keywordTokens = ["title:", "collapse:", "icon:", "color:"];
const keywords = ["title", "collapse", "icon", "color"];
let lines = src.split("\n");
let skipLines = 0;
let params: { [k: string]: string } = {};
for (let i = 0; i < lines.length; i++) {
let keywordIndex = startsWithAny(lines[i], keywordTokens);
if (keywordIndex === false) {
break;
}
let foundKeyword = keywords[keywordIndex];
if (params[foundKeyword] !== undefined) {
break;
}
params[foundKeyword] = lines[i]
.substr(keywordTokens[keywordIndex].length)
.trim();
++skipLines;
}
let {
title = type[0].toUpperCase() + type.slice(1).toLowerCase(),
collapse,
icon,
color
} = params;
let content = lines.slice(skipLines).join("\n");
/**
* If the admonition should collapse, but something other than open or closed was provided, set to closed.
*/
if (
collapse !== undefined &&
collapse !== "none" &&
collapse !== "open" &&
collapse !== "closed"
) {
collapse = "closed";
}
/**
* If the admonition should collapse, but title was blanked, set the default title.
*/
if (title.trim() === "" && collapse !== undefined && collapse !== "none") {
title = type[0].toUpperCase() + type.slice(1).toLowerCase();
return;
}
return { title, collapse, content, icon, color };
}
interface AdmonitionPublishDefinition {
icon: string;
color: string;
}
const blockSet: Set<HTMLPreElement> = new Set();
const ADMONITION_ICON_MAP: {
[admonitionType: string]: AdmonitionPublishDefinition;
} = {};
if (document.readyState === "complete") {
postprocess();
registerToProcess();
} else {
window.onload = () => {
postprocess();
registerToProcess();
};
}
function registerToProcess() {
const sizer = document.querySelector(".markdown-preview-sizer");
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.type == "childList" && mutation.addedNodes.length) {
mutation.addedNodes.forEach((node) => {
if (
node &&
node instanceof Element &&
node.children.length &&
node.firstElementChild?.tagName === "PRE"
) {
//postprocess(node);
preObserver.observe(node.firstChild, {
attributes: true,
childList: false,
characterData: false,
subtree: false
});
}
});
}
});
});
observer.observe(sizer, {
attributes: false,
childList: true,
subtree: false
});
const preObserver = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (
mutation.target instanceof HTMLPreElement &&
!blockSet.has(mutation.target) &&
mutation.type === "attributes" &&
mutation.attributeName === "class" &&
Array.from(mutation.target.classList).some((cls) =>
/language-ad-(\w+)/.test(cls)
)
) {
blockSet.add(mutation.target);
processAdmonitionBlock(mutation.target);
}
});
});
}
function processAdmonitionBlock(admonitionBlock: HTMLPreElement) {
const [, type] = admonitionBlock.classList
.toString()
.match(/language-ad-(\w+)/);
if (!type) return;
if (!(type in ADMONITION_ICON_MAP)) return;
let {
title = type[0].toUpperCase() + type.slice(1).toLowerCase(),
collapse,
content,
icon = ADMONITION_ICON_MAP[type].icon,
color = ADMONITION_ICON_MAP[type].color
} = getParametersFromSource(type, admonitionBlock.innerText);
let admonition = getAdmonitionElement(type, title, icon, color, collapse);
const contentHolder = admonition.createDiv("admonition-content-holder");
const admonitionContent = contentHolder.createDiv("admonition-content");
admonitionContent.innerText = content;
admonitionBlock.replaceWith(admonition);
}
function postprocess() {
//do work
const admonitions = document.querySelectorAll<HTMLPreElement>(
"pre[class*='language-ad']"
);
if (!admonitions.length) return;
for (let admonitionBlock of Array.from(admonitions)) {
blockSet.add(admonitionBlock);
const [, type] = admonitionBlock.classList
.toString()
.match(/language-ad-(\w+)/);
if (!type) continue;
if (!(type in ADMONITION_ICON_MAP)) continue;
let {
title = type[0].toUpperCase() + type.slice(1).toLowerCase(),
collapse,
content,
icon = ADMONITION_ICON_MAP[type].icon,
color = ADMONITION_ICON_MAP[type].color
} = getParametersFromSource(type, admonitionBlock.innerText);
let admonition = getAdmonitionElement(
type,
title,
icon,
color,
collapse
);
const contentHolder = admonition.createDiv("admonition-content-holder");
const admonitionContent = contentHolder.createDiv("admonition-content");
admonitionContent.innerText = content;
admonitionBlock.replaceWith(admonition);
}
} | the_stack |
import React, { FunctionComponent, useState } from "react";
import { observer } from "mobx-react-lite";
import { PageWithScrollView } from "../../components/page";
import { Platform, StyleSheet, Text, View, ViewStyle } from "react-native";
import { Card, CardBody, CardDivider } from "../../components/card";
import { useStyle } from "../../styles";
import { Button } from "../../components/button";
import { useStore } from "../../stores";
import { useRoute, RouteProp } from "@react-navigation/native";
import { LoadingSpinner } from "../../components/spinner";
import { Governance } from "@keplr-wallet/stores";
import { GovernanceProposalStatusChip } from "./card";
import { IntPretty } from "@keplr-wallet/unit";
import { useIntl } from "react-intl";
import { dateToLocalString } from "./utils";
import { registerModal } from "../../modals/base";
import { RectButton } from "../../components/rect-button";
import { useSmartNavigation } from "../../navigation";
export const TallyVoteInfoView: FunctionComponent<{
vote: "yes" | "no" | "abstain" | "noWithVeto";
percentage: IntPretty;
hightlight?: boolean;
}> = ({ vote, percentage, hightlight = false }) => {
const style = useStyle();
const text = (() => {
switch (vote) {
case "yes":
return "Yes";
case "no":
return "No";
case "abstain":
return "Abstain";
case "noWithVeto":
return "No with veto";
}
})();
return (
<View
style={style.flatten(
[
"height-56",
"padding-8",
"border-radius-4",
"border-width-1",
"border-color-border-white",
],
[hightlight && "background-color-primary-10"]
)}
>
<View style={style.flatten(["flex-row", "height-full"])}>
<View
style={style.flatten([
"width-4",
"background-color-primary",
"margin-right-8",
])}
/>
<View style={style.flatten(["justify-center"])}>
<Text
style={style.flatten([
"text-caption1",
"color-text-black-low",
"margin-bottom-2",
])}
>
{text}
</Text>
<Text
style={style.flatten(["text-button3", "color-text-black-medium"])}
>{`${percentage.trim(true).maxDecimals(1).toString()}%`}</Text>
</View>
</View>
</View>
);
};
export const GovernanceDetailsCardBody: FunctionComponent<{
containerStyle?: ViewStyle;
proposalId: string;
}> = observer(({ proposalId, containerStyle }) => {
const { chainStore, queriesStore, accountStore } = useStore();
const style = useStyle();
const account = accountStore.getAccount(chainStore.current.chainId);
const queries = queriesStore.get(chainStore.current.chainId);
const proposal = queries.cosmos.queryGovernance.getProposal(proposalId);
const voted = proposal
? queries.cosmos.queryProposalVote.getVote(
proposal.id,
account.bech32Address
).vote
: undefined;
const intl = useIntl();
return (
<CardBody>
{proposal ? (
<View style={containerStyle}>
<View
style={style.flatten([
"flex-row",
"items-center",
"margin-bottom-8",
])}
>
<Text
style={style.flatten(["h6", "color-text-black-high"])}
>{`#${proposal.id}`}</Text>
<View style={style.flatten(["flex-1"])} />
<GovernanceProposalStatusChip status={proposal.proposalStatus} />
</View>
<Text
style={style.flatten([
"h6",
"color-text-black-high",
"margin-bottom-16",
])}
// Text selection is only supported well in android.
// In IOS, the whole text would be selected, this process is somewhat strange, so it is disabled in IOS.
selectable={Platform.OS === "android"}
>
{proposal.title}
</Text>
<View style={style.flatten(["margin-bottom-12"])}>
<View
style={style.flatten([
"flex-row",
"items-center",
"margin-bottom-6",
])}
>
<Text style={style.flatten(["h7", "color-text-black-medium"])}>
Turnout
</Text>
<View style={style.flatten(["flex-1"])} />
<Text
style={style.flatten(["body3", "color-text-black-medium"])}
>{`${proposal.turnout
.trim(true)
.maxDecimals(1)
.toString()}%`}</Text>
</View>
<View
style={style.flatten([
"height-8",
"background-color-border-white",
"border-radius-32",
"overflow-hidden",
])}
>
<View
style={StyleSheet.flatten([
style.flatten([
"height-8",
"background-color-primary",
"border-radius-32",
]),
{
width: `${parseFloat(
proposal.turnout.toDec().toString(1)
)}%`,
},
])}
/>
</View>
</View>
<View>
<View style={style.flatten(["flex-row", "margin-bottom-8"])}>
<View style={style.flatten(["flex-1"])}>
<TallyVoteInfoView
vote="yes"
percentage={proposal.tallyRatio.yes}
hightlight={voted === "Yes"}
/>
</View>
<View style={style.flatten(["width-12"])} />
<View style={style.flatten(["flex-1"])}>
<TallyVoteInfoView
vote="no"
percentage={proposal.tallyRatio.no}
hightlight={voted === "No"}
/>
</View>
</View>
<View style={style.flatten(["flex-row"])}>
<View style={style.flatten(["flex-1"])}>
<TallyVoteInfoView
vote="noWithVeto"
percentage={proposal.tallyRatio.noWithVeto}
hightlight={voted === "NoWithVeto"}
/>
</View>
<View style={style.flatten(["width-12"])} />
<View style={style.flatten(["flex-1"])}>
<TallyVoteInfoView
vote="abstain"
percentage={proposal.tallyRatio.abstain}
hightlight={voted === "Abstain"}
/>
</View>
</View>
</View>
<CardDivider style={style.flatten(["margin-x-0", "margin-y-16"])} />
<View style={style.flatten(["flex-row", "margin-bottom-12"])}>
<View style={style.flatten(["flex-1"])}>
<Text style={style.flatten(["h7", "color-text-black-medium"])}>
Voting Start
</Text>
<Text style={style.flatten(["body3", "color-text-black-medium"])}>
{dateToLocalString(intl, proposal.raw.voting_start_time)}
</Text>
</View>
<View style={style.flatten(["flex-1"])}>
<Text style={style.flatten(["h7", "color-text-black-medium"])}>
Voting End
</Text>
<Text style={style.flatten(["body3", "color-text-black-medium"])}>
{dateToLocalString(intl, proposal.raw.voting_end_time)}
</Text>
</View>
</View>
<Text
style={style.flatten([
"h7",
"color-text-black-medium",
"margin-bottom-4",
])}
>
Description
</Text>
<Text
style={style.flatten(["body3", "color-text-black-medium"])}
// Text selection is only supported well in android.
// In IOS, the whole text would be selected, this process is somewhat strange, so it is disabled in IOS.
selectable={Platform.OS === "android"}
>
{proposal.description}
</Text>
</View>
) : (
<LoadingSpinner
color={style.flatten(["color-loading-spinner"]).color}
size={20}
/>
)}
</CardBody>
);
});
export const GovernanceVoteModal: FunctionComponent<{
isOpen: boolean;
close: () => void;
proposalId: string;
// Modal can't use the `useSmartNavigation` hook directly.
// So need to get the props from the parent.
smartNavigation: ReturnType<typeof useSmartNavigation>;
}> = registerModal(
observer(({ proposalId, close, smartNavigation }) => {
const {
chainStore,
accountStore,
queriesStore,
analyticsStore,
} = useStore();
const account = accountStore.getAccount(chainStore.current.chainId);
const queries = queriesStore.get(chainStore.current.chainId);
const proposal = queries.cosmos.queryGovernance.getProposal(proposalId);
const style = useStyle();
const [vote, setVote] = useState<
"Yes" | "No" | "NoWithVeto" | "Abstain" | "Unspecified"
>("Unspecified");
const renderBall = (selected: boolean) => {
if (selected) {
return (
<View
style={style.flatten([
"width-24",
"height-24",
"border-radius-32",
"background-color-primary",
"items-center",
"justify-center",
])}
>
<View
style={style.flatten([
"width-12",
"height-12",
"border-radius-32",
"background-color-white",
])}
/>
</View>
);
} else {
return (
<View
style={style.flatten([
"width-24",
"height-24",
"border-radius-32",
"background-color-white",
"border-width-1",
"border-color-text-black-very-low",
])}
/>
);
}
};
return (
<View style={style.flatten(["padding-page"])}>
<View
style={style.flatten([
"border-radius-8",
"overflow-hidden",
"background-color-white",
])}
>
<RectButton
style={style.flatten(
[
"height-64",
"padding-left-36",
"padding-right-28",
"flex-row",
"items-center",
"justify-between",
],
[vote === "Yes" && "background-color-primary-10"]
)}
onPress={() => setVote("Yes")}
>
<Text
style={style.flatten(["subtitle1", "color-text-black-medium"])}
>
Yes
</Text>
{renderBall(vote === "Yes")}
</RectButton>
<View
style={style.flatten(["height-1", "background-color-divider"])}
/>
<RectButton
style={style.flatten(
[
"height-64",
"padding-left-36",
"padding-right-28",
"flex-row",
"items-center",
"justify-between",
],
[vote === "No" && "background-color-primary-10"]
)}
onPress={() => setVote("No")}
>
<Text
style={style.flatten(["subtitle1", "color-text-black-medium"])}
>
No
</Text>
{renderBall(vote === "No")}
</RectButton>
<View
style={style.flatten(["height-1", "background-color-divider"])}
/>
<RectButton
style={style.flatten(
[
"height-64",
"padding-left-36",
"padding-right-28",
"flex-row",
"items-center",
"justify-between",
],
[vote === "NoWithVeto" && "background-color-primary-10"]
)}
onPress={() => setVote("NoWithVeto")}
>
<Text
style={style.flatten(["subtitle1", "color-text-black-medium"])}
>
No with veto
</Text>
{renderBall(vote === "NoWithVeto")}
</RectButton>
<View
style={style.flatten(["height-1", "background-color-divider"])}
/>
<RectButton
style={style.flatten(
[
"height-64",
"padding-left-36",
"padding-right-28",
"flex-row",
"items-center",
"justify-between",
],
[vote === "Abstain" && "background-color-primary-10"]
)}
onPress={() => setVote("Abstain")}
>
<Text
style={style.flatten(["subtitle1", "color-text-black-medium"])}
>
Abstain
</Text>
{renderBall(vote === "Abstain")}
</RectButton>
</View>
<Button
containerStyle={style.flatten(["margin-top-12"])}
text="Vote"
size="large"
disabled={vote === "Unspecified" || !account.isReadyToSendMsgs}
loading={account.isSendingMsg === "govVote"}
onPress={async () => {
if (vote !== "Unspecified" && account.isReadyToSendMsgs) {
try {
await account.cosmos.sendGovVoteMsg(
proposalId,
vote,
"",
{},
{},
{
onBroadcasted: (txHash) => {
analyticsStore.logEvent("Vote tx broadcasted", {
chainId: chainStore.current.chainId,
chainName: chainStore.current.chainName,
proposalId,
proposalTitle: proposal?.title,
});
smartNavigation.pushSmart("TxPendingResult", {
txHash: Buffer.from(txHash).toString("hex"),
});
},
}
);
close();
} catch (e) {
if (e?.message === "Request rejected") {
return;
}
console.log(e);
smartNavigation.navigateSmart("Home", {});
}
}
}}
/>
</View>
);
})
);
export const GovernanceDetailsScreen: FunctionComponent = observer(() => {
const { chainStore, queriesStore, accountStore } = useStore();
const style = useStyle();
const smartNavigation = useSmartNavigation();
const route = useRoute<
RouteProp<
Record<
string,
{
proposalId: string;
}
>,
string
>
>();
const proposalId = route.params.proposalId;
const queries = queriesStore.get(chainStore.current.chainId);
const account = accountStore.getAccount(chainStore.current.chainId);
const proposal = queries.cosmos.queryGovernance.getProposal(proposalId);
const voteEnabled =
proposal?.proposalStatus === Governance.ProposalStatus.VOTING_PERIOD;
const voteText = (() => {
if (!proposal) {
return "Loading...";
}
switch (proposal.proposalStatus) {
case Governance.ProposalStatus.DEPOSIT_PERIOD:
return "Vote Not Started";
case Governance.ProposalStatus.VOTING_PERIOD:
return "Vote";
default:
return "Vote Ended";
}
})();
const [isModalOpen, setIsModalOpen] = useState(false);
return (
<PageWithScrollView
fixed={
<View
style={style.flatten(["flex-1", "padding-page"])}
pointerEvents="box-none"
>
<View style={style.flatten(["flex-1"])} pointerEvents="box-none" />
{!isModalOpen ? (
<Button
text={voteText}
size="large"
disabled={!voteEnabled || !account.isReadyToSendMsgs}
onPress={() => {
setIsModalOpen(true);
}}
/>
) : null}
</View>
}
>
<GovernanceVoteModal
isOpen={isModalOpen}
close={() => setIsModalOpen(false)}
proposalId={proposalId}
smartNavigation={smartNavigation}
/>
<Card style={style.flatten(["margin-top-card-gap"])}>
<GovernanceDetailsCardBody
proposalId={proposalId}
containerStyle={(() => {
let marginBottom = 0;
const buttonHeight = style.get("height-button-large").height;
if (typeof buttonHeight === "string") {
marginBottom += parseFloat(buttonHeight);
} else {
marginBottom += buttonHeight;
}
const padding = style.get("padding-page").paddingBottom;
if (typeof padding === "string") {
marginBottom += parseFloat(padding);
} else {
marginBottom += padding;
}
return {
marginBottom,
};
})()}
/>
</Card>
</PageWithScrollView>
);
}); | the_stack |
import * as utf8 from './utf8'
export const
MaxRune = 0x10FFFF // Maximum valid Unicode code point
, MaxASCII = 0x007F // maximum ASCII value
, MaxLatin1 = 0x00FF // maximum Latin-1 value
, ReplacementChar = 0xFFFD // Represents invalid code points
const fmt4 = '0000'
export function repr(cp :int) :string {
let s = cp.toString(16)
if (cp <= 0xFFFF) {
s = fmt4.substr(0, fmt4.length - s.length) + s
}
let str = JSON.stringify(utf8.encodeAsString(cp))
str = str.substr(1, str.length-2)
return `U+${s} '${str}'`
}
export function isValid(c :int) :bool {
return c >= 0 && c <= MaxRune
}
export function isSurrogate(c :int) :bool {
return 0xD800 <= c && c <= 0xDFFF
}
export function isPrivateUse(c :int) :bool {
return 0xE000 <= c && c <= 0xF8FF
}
// the remaining functions' data was generated by misc/gen-unicode-data.js
export function isWhitespace(c :int) :bool {
return (
0x0 <= c && c <= 0x3000 && ( // <control>..IDEOGRAPHIC SPACE
(0x0 <= c && c <= 0x20) || // <control>..SPACE
(0x7F <= c && c <= 0xA0) || // <control>..NO-BREAK SPACE
c == 0x1680 || // OGHAM SPACE MARK
(0x2000 <= c && c <= 0x200A) || // EN QUAD..HAIR SPACE
(0x2028 <= c && c <= 0x2029) || // LINE SEPARATOR..PARAGRAPH SEPARATOR
c == 0x202F || // NARROW NO-BREAK SPACE
c == 0x205F || // MEDIUM MATHEMATICAL SPACE
c == 0x3000 // IDEOGRAPHIC SPACE
))
}
export function isLetter(c :int) :bool {
return (
0x41 <= c && c <= 0x1E943 && ( // LATIN CAPITAL LETTER A..ADLAM SMALL LETTER SHA
(0x41 <= c && c <= 0x5A) || // LATIN CAPITAL LETTER A..LATIN CAPITAL LETTER Z
(0x61 <= c && c <= 0x7A) || // LATIN SMALL LETTER A..LATIN SMALL LETTER Z
c == 0xB5 || // MICRO SIGN
(0xC0 <= c && c <= 0xD6) || // LATIN CAPITAL LETTER A WITH GRAVE..LATIN CAPITAL LETTER O WITH DIAERESIS
(0xD8 <= c && c <= 0xF6) || // LATIN CAPITAL LETTER O WITH STROKE..LATIN SMALL LETTER O WITH DIAERESIS
(0xF8 <= c && c <= 0x1BA) || // LATIN SMALL LETTER O WITH STROKE..LATIN SMALL LETTER EZH WITH TAIL
(0x1BC <= c && c <= 0x1BF) || // LATIN CAPITAL LETTER TONE FIVE..LATIN LETTER WYNN
c == 0x1C4 || // LATIN CAPITAL LETTER DZ WITH CARON
(0x1C6 <= c && c <= 0x1C7) || // LATIN SMALL LETTER DZ WITH CARON..LATIN CAPITAL LETTER LJ
(0x1C9 <= c && c <= 0x1CA) || // LATIN SMALL LETTER LJ..LATIN CAPITAL LETTER NJ
(0x1CC <= c && c <= 0x1F1) || // LATIN SMALL LETTER NJ..LATIN CAPITAL LETTER DZ
(0x1F3 <= c && c <= 0x293) || // LATIN SMALL LETTER DZ..LATIN SMALL LETTER EZH WITH CURL
(0x295 <= c && c <= 0x2AF) || // LATIN LETTER PHARYNGEAL VOICED FRICATIVE..LATIN SMALL LETTER TURNED H WITH FISHHOOK AND TAIL
(0x370 <= c && c <= 0x373) || // GREEK CAPITAL LETTER HETA..GREEK SMALL LETTER ARCHAIC SAMPI
(0x376 <= c && c <= 0x377) || // GREEK CAPITAL LETTER PAMPHYLIAN DIGAMMA..GREEK SMALL LETTER PAMPHYLIAN DIGAMMA
(0x37B <= c && c <= 0x37D) || // GREEK SMALL REVERSED LUNATE SIGMA SYMBOL..GREEK SMALL REVERSED DOTTED LUNATE SIGMA SYMBOL
c == 0x37F || // GREEK CAPITAL LETTER YOT
c == 0x386 || // GREEK CAPITAL LETTER ALPHA WITH TONOS
(0x388 <= c && c <= 0x38A) || // GREEK CAPITAL LETTER EPSILON WITH TONOS..GREEK CAPITAL LETTER IOTA WITH TONOS
c == 0x38C || // GREEK CAPITAL LETTER OMICRON WITH TONOS
(0x38E <= c && c <= 0x3A1) || // GREEK CAPITAL LETTER UPSILON WITH TONOS..GREEK CAPITAL LETTER RHO
(0x3A3 <= c && c <= 0x3F5) || // GREEK CAPITAL LETTER SIGMA..GREEK LUNATE EPSILON SYMBOL
(0x3F7 <= c && c <= 0x481) || // GREEK CAPITAL LETTER SHO..CYRILLIC SMALL LETTER KOPPA
(0x48A <= c && c <= 0x52F) || // CYRILLIC CAPITAL LETTER SHORT I WITH TAIL..CYRILLIC SMALL LETTER EL WITH DESCENDER
(0x531 <= c && c <= 0x556) || // ARMENIAN CAPITAL LETTER AYB..ARMENIAN CAPITAL LETTER FEH
(0x560 <= c && c <= 0x588) || // ARMENIAN SMALL LETTER TURNED AYB..ARMENIAN SMALL LETTER YI WITH STROKE
(0x10A0 <= c && c <= 0x10C5) || // GEORGIAN CAPITAL LETTER AN..GEORGIAN CAPITAL LETTER HOE
c == 0x10C7 || // GEORGIAN CAPITAL LETTER YN
c == 0x10CD || // GEORGIAN CAPITAL LETTER AEN
(0x10D0 <= c && c <= 0x10FA) || // GEORGIAN LETTER AN..GEORGIAN LETTER AIN
(0x10FD <= c && c <= 0x10FF) || // GEORGIAN LETTER AEN..GEORGIAN LETTER LABIAL SIGN
(0x13A0 <= c && c <= 0x13F5) || // CHEROKEE LETTER A..CHEROKEE LETTER MV
(0x13F8 <= c && c <= 0x13FD) || // CHEROKEE SMALL LETTER YE..CHEROKEE SMALL LETTER MV
(0x1C80 <= c && c <= 0x1C88) || // CYRILLIC SMALL LETTER ROUNDED VE..CYRILLIC SMALL LETTER UNBLENDED UK
(0x1C90 <= c && c <= 0x1CBA) || // GEORGIAN MTAVRULI CAPITAL LETTER AN..GEORGIAN MTAVRULI CAPITAL LETTER AIN
(0x1CBD <= c && c <= 0x1CBF) || // GEORGIAN MTAVRULI CAPITAL LETTER AEN..GEORGIAN MTAVRULI CAPITAL LETTER LABIAL SIGN
(0x1D00 <= c && c <= 0x1D2B) || // LATIN LETTER SMALL CAPITAL A..CYRILLIC LETTER SMALL CAPITAL EL
(0x1D6B <= c && c <= 0x1D77) || // LATIN SMALL LETTER UE..LATIN SMALL LETTER TURNED G
(0x1D79 <= c && c <= 0x1D9A) || // LATIN SMALL LETTER INSULAR G..LATIN SMALL LETTER EZH WITH RETROFLEX HOOK
(0x1E00 <= c && c <= 0x1F15) || // LATIN CAPITAL LETTER A WITH RING BELOW..GREEK SMALL LETTER EPSILON WITH DASIA AND OXIA
(0x1F18 <= c && c <= 0x1F1D) || // GREEK CAPITAL LETTER EPSILON WITH PSILI..GREEK CAPITAL LETTER EPSILON WITH DASIA AND OXIA
(0x1F20 <= c && c <= 0x1F45) || // GREEK SMALL LETTER ETA WITH PSILI..GREEK SMALL LETTER OMICRON WITH DASIA AND OXIA
(0x1F48 <= c && c <= 0x1F4D) || // GREEK CAPITAL LETTER OMICRON WITH PSILI..GREEK CAPITAL LETTER OMICRON WITH DASIA AND OXIA
(0x1F50 <= c && c <= 0x1F57) || // GREEK SMALL LETTER UPSILON WITH PSILI..GREEK SMALL LETTER UPSILON WITH DASIA AND PERISPOMENI
c == 0x1F59 || // GREEK CAPITAL LETTER UPSILON WITH DASIA
c == 0x1F5B || // GREEK CAPITAL LETTER UPSILON WITH DASIA AND VARIA
c == 0x1F5D || // GREEK CAPITAL LETTER UPSILON WITH DASIA AND OXIA
(0x1F5F <= c && c <= 0x1F7D) || // GREEK CAPITAL LETTER UPSILON WITH DASIA AND PERISPOMENI..GREEK SMALL LETTER OMEGA WITH OXIA
(0x1F80 <= c && c <= 0x1F87) || // GREEK SMALL LETTER ALPHA WITH PSILI AND YPOGEGRAMMENI..GREEK SMALL LETTER ALPHA WITH DASIA AND PERISPOMENI AND YPOGEGRAMMENI
(0x1F90 <= c && c <= 0x1F97) || // GREEK SMALL LETTER ETA WITH PSILI AND YPOGEGRAMMENI..GREEK SMALL LETTER ETA WITH DASIA AND PERISPOMENI AND YPOGEGRAMMENI
(0x1FA0 <= c && c <= 0x1FA7) || // GREEK SMALL LETTER OMEGA WITH PSILI AND YPOGEGRAMMENI..GREEK SMALL LETTER OMEGA WITH DASIA AND PERISPOMENI AND YPOGEGRAMMENI
(0x1FB0 <= c && c <= 0x1FB4) || // GREEK SMALL LETTER ALPHA WITH VRACHY..GREEK SMALL LETTER ALPHA WITH OXIA AND YPOGEGRAMMENI
(0x1FB6 <= c && c <= 0x1FBB) || // GREEK SMALL LETTER ALPHA WITH PERISPOMENI..GREEK CAPITAL LETTER ALPHA WITH OXIA
c == 0x1FBE || // GREEK PROSGEGRAMMENI
(0x1FC2 <= c && c <= 0x1FC4) || // GREEK SMALL LETTER ETA WITH VARIA AND YPOGEGRAMMENI..GREEK SMALL LETTER ETA WITH OXIA AND YPOGEGRAMMENI
(0x1FC6 <= c && c <= 0x1FCB) || // GREEK SMALL LETTER ETA WITH PERISPOMENI..GREEK CAPITAL LETTER ETA WITH OXIA
(0x1FD0 <= c && c <= 0x1FD3) || // GREEK SMALL LETTER IOTA WITH VRACHY..GREEK SMALL LETTER IOTA WITH DIALYTIKA AND OXIA
(0x1FD6 <= c && c <= 0x1FDB) || // GREEK SMALL LETTER IOTA WITH PERISPOMENI..GREEK CAPITAL LETTER IOTA WITH OXIA
(0x1FE0 <= c && c <= 0x1FEC) || // GREEK SMALL LETTER UPSILON WITH VRACHY..GREEK CAPITAL LETTER RHO WITH DASIA
(0x1FF2 <= c && c <= 0x1FF4) || // GREEK SMALL LETTER OMEGA WITH VARIA AND YPOGEGRAMMENI..GREEK SMALL LETTER OMEGA WITH OXIA AND YPOGEGRAMMENI
(0x1FF6 <= c && c <= 0x1FFB) || // GREEK SMALL LETTER OMEGA WITH PERISPOMENI..GREEK CAPITAL LETTER OMEGA WITH OXIA
c == 0x2102 || // DOUBLE-STRUCK CAPITAL C
c == 0x2107 || // EULER CONSTANT
(0x210A <= c && c <= 0x2113) || // SCRIPT SMALL G..SCRIPT SMALL L
c == 0x2115 || // DOUBLE-STRUCK CAPITAL N
(0x2119 <= c && c <= 0x211D) || // DOUBLE-STRUCK CAPITAL P..DOUBLE-STRUCK CAPITAL R
c == 0x2124 || // DOUBLE-STRUCK CAPITAL Z
c == 0x2126 || // OHM SIGN
c == 0x2128 || // BLACK-LETTER CAPITAL Z
(0x212A <= c && c <= 0x212D) || // KELVIN SIGN..BLACK-LETTER CAPITAL C
(0x212F <= c && c <= 0x2134) || // SCRIPT SMALL E..SCRIPT SMALL O
c == 0x2139 || // INFORMATION SOURCE
(0x213C <= c && c <= 0x213F) || // DOUBLE-STRUCK SMALL PI..DOUBLE-STRUCK CAPITAL PI
(0x2145 <= c && c <= 0x2149) || // DOUBLE-STRUCK ITALIC CAPITAL D..DOUBLE-STRUCK ITALIC SMALL J
c == 0x214E || // TURNED SMALL F
(0x2183 <= c && c <= 0x2184) || // ROMAN NUMERAL REVERSED ONE HUNDRED..LATIN SMALL LETTER REVERSED C
(0x2C00 <= c && c <= 0x2C2E) || // GLAGOLITIC CAPITAL LETTER AZU..GLAGOLITIC CAPITAL LETTER LATINATE MYSLITE
(0x2C30 <= c && c <= 0x2C5E) || // GLAGOLITIC SMALL LETTER AZU..GLAGOLITIC SMALL LETTER LATINATE MYSLITE
(0x2C60 <= c && c <= 0x2C7B) || // LATIN CAPITAL LETTER L WITH DOUBLE BAR..LATIN LETTER SMALL CAPITAL TURNED E
(0x2C7E <= c && c <= 0x2CE4) || // LATIN CAPITAL LETTER S WITH SWASH TAIL..COPTIC SYMBOL KAI
(0x2CEB <= c && c <= 0x2CEE) || // COPTIC CAPITAL LETTER CRYPTOGRAMMIC SHEI..COPTIC SMALL LETTER CRYPTOGRAMMIC GANGIA
(0x2CF2 <= c && c <= 0x2CF3) || // COPTIC CAPITAL LETTER BOHAIRIC KHEI..COPTIC SMALL LETTER BOHAIRIC KHEI
(0x2D00 <= c && c <= 0x2D25) || // GEORGIAN SMALL LETTER AN..GEORGIAN SMALL LETTER HOE
c == 0x2D27 || // GEORGIAN SMALL LETTER YN
c == 0x2D2D || // GEORGIAN SMALL LETTER AEN
(0xA640 <= c && c <= 0xA66D) || // CYRILLIC CAPITAL LETTER ZEMLYA..CYRILLIC SMALL LETTER DOUBLE MONOCULAR O
(0xA680 <= c && c <= 0xA69B) || // CYRILLIC CAPITAL LETTER DWE..CYRILLIC SMALL LETTER CROSSED O
(0xA722 <= c && c <= 0xA76F) || // LATIN CAPITAL LETTER EGYPTOLOGICAL ALEF..LATIN SMALL LETTER CON
(0xA771 <= c && c <= 0xA787) || // LATIN SMALL LETTER DUM..LATIN SMALL LETTER INSULAR T
(0xA78B <= c && c <= 0xA78E) || // LATIN CAPITAL LETTER SALTILLO..LATIN SMALL LETTER L WITH RETROFLEX HOOK AND BELT
(0xA790 <= c && c <= 0xA7BF) || // LATIN CAPITAL LETTER N WITH DESCENDER..LATIN SMALL LETTER GLOTTAL U
(0xA7C2 <= c && c <= 0xA7C6) || // LATIN CAPITAL LETTER ANGLICANA W..LATIN CAPITAL LETTER Z WITH PALATAL HOOK
c == 0xA7FA || // LATIN LETTER SMALL CAPITAL TURNED M
(0xAB30 <= c && c <= 0xAB5A) || // LATIN SMALL LETTER BARRED ALPHA..LATIN SMALL LETTER Y WITH SHORT RIGHT LEG
(0xAB60 <= c && c <= 0xAB67) || // LATIN SMALL LETTER SAKHA YAT..LATIN SMALL LETTER TS DIGRAPH WITH RETROFLEX HOOK
(0xAB70 <= c && c <= 0xABBF) || // CHEROKEE SMALL LETTER A..CHEROKEE SMALL LETTER YA
(0xFB00 <= c && c <= 0xFB06) || // LATIN SMALL LIGATURE FF..LATIN SMALL LIGATURE ST
(0xFB13 <= c && c <= 0xFB17) || // ARMENIAN SMALL LIGATURE MEN NOW..ARMENIAN SMALL LIGATURE MEN XEH
(0xFF21 <= c && c <= 0xFF3A) || // FULLWIDTH LATIN CAPITAL LETTER A..FULLWIDTH LATIN CAPITAL LETTER Z
(0xFF41 <= c && c <= 0xFF5A) || // FULLWIDTH LATIN SMALL LETTER A..FULLWIDTH LATIN SMALL LETTER Z
(0x10400 <= c && c <= 0x1044F) || // DESERET CAPITAL LETTER LONG I..DESERET SMALL LETTER EW
(0x104B0 <= c && c <= 0x104D3) || // OSAGE CAPITAL LETTER A..OSAGE CAPITAL LETTER ZHA
(0x104D8 <= c && c <= 0x104FB) || // OSAGE SMALL LETTER A..OSAGE SMALL LETTER ZHA
(0x10C80 <= c && c <= 0x10CB2) || // OLD HUNGARIAN CAPITAL LETTER A..OLD HUNGARIAN CAPITAL LETTER US
(0x10CC0 <= c && c <= 0x10CF2) || // OLD HUNGARIAN SMALL LETTER A..OLD HUNGARIAN SMALL LETTER US
(0x118A0 <= c && c <= 0x118DF) || // WARANG CITI CAPITAL LETTER NGAA..WARANG CITI SMALL LETTER VIYO
(0x16E40 <= c && c <= 0x16E7F) || // MEDEFAIDRIN CAPITAL LETTER M..MEDEFAIDRIN SMALL LETTER Y
(0x1D400 <= c && c <= 0x1D454) || // MATHEMATICAL BOLD CAPITAL A..MATHEMATICAL ITALIC SMALL G
(0x1D456 <= c && c <= 0x1D49C) || // MATHEMATICAL ITALIC SMALL I..MATHEMATICAL SCRIPT CAPITAL A
(0x1D49E <= c && c <= 0x1D49F) || // MATHEMATICAL SCRIPT CAPITAL C..MATHEMATICAL SCRIPT CAPITAL D
c == 0x1D4A2 || // MATHEMATICAL SCRIPT CAPITAL G
(0x1D4A5 <= c && c <= 0x1D4A6) || // MATHEMATICAL SCRIPT CAPITAL J..MATHEMATICAL SCRIPT CAPITAL K
(0x1D4A9 <= c && c <= 0x1D4AC) || // MATHEMATICAL SCRIPT CAPITAL N..MATHEMATICAL SCRIPT CAPITAL Q
(0x1D4AE <= c && c <= 0x1D4B9) || // MATHEMATICAL SCRIPT CAPITAL S..MATHEMATICAL SCRIPT SMALL D
c == 0x1D4BB || // MATHEMATICAL SCRIPT SMALL F
(0x1D4BD <= c && c <= 0x1D4C3) || // MATHEMATICAL SCRIPT SMALL H..MATHEMATICAL SCRIPT SMALL N
(0x1D4C5 <= c && c <= 0x1D505) || // MATHEMATICAL SCRIPT SMALL P..MATHEMATICAL FRAKTUR CAPITAL B
(0x1D507 <= c && c <= 0x1D50A) || // MATHEMATICAL FRAKTUR CAPITAL D..MATHEMATICAL FRAKTUR CAPITAL G
(0x1D50D <= c && c <= 0x1D514) || // MATHEMATICAL FRAKTUR CAPITAL J..MATHEMATICAL FRAKTUR CAPITAL Q
(0x1D516 <= c && c <= 0x1D51C) || // MATHEMATICAL FRAKTUR CAPITAL S..MATHEMATICAL FRAKTUR CAPITAL Y
(0x1D51E <= c && c <= 0x1D539) || // MATHEMATICAL FRAKTUR SMALL A..MATHEMATICAL DOUBLE-STRUCK CAPITAL B
(0x1D53B <= c && c <= 0x1D53E) || // MATHEMATICAL DOUBLE-STRUCK CAPITAL D..MATHEMATICAL DOUBLE-STRUCK CAPITAL G
(0x1D540 <= c && c <= 0x1D544) || // MATHEMATICAL DOUBLE-STRUCK CAPITAL I..MATHEMATICAL DOUBLE-STRUCK CAPITAL M
c == 0x1D546 || // MATHEMATICAL DOUBLE-STRUCK CAPITAL O
(0x1D54A <= c && c <= 0x1D550) || // MATHEMATICAL DOUBLE-STRUCK CAPITAL S..MATHEMATICAL DOUBLE-STRUCK CAPITAL Y
(0x1D552 <= c && c <= 0x1D6A5) || // MATHEMATICAL DOUBLE-STRUCK SMALL A..MATHEMATICAL ITALIC SMALL DOTLESS J
(0x1D6A8 <= c && c <= 0x1D6C0) || // MATHEMATICAL BOLD CAPITAL ALPHA..MATHEMATICAL BOLD CAPITAL OMEGA
(0x1D6C2 <= c && c <= 0x1D6DA) || // MATHEMATICAL BOLD SMALL ALPHA..MATHEMATICAL BOLD SMALL OMEGA
(0x1D6DC <= c && c <= 0x1D6FA) || // MATHEMATICAL BOLD EPSILON SYMBOL..MATHEMATICAL ITALIC CAPITAL OMEGA
(0x1D6FC <= c && c <= 0x1D714) || // MATHEMATICAL ITALIC SMALL ALPHA..MATHEMATICAL ITALIC SMALL OMEGA
(0x1D716 <= c && c <= 0x1D734) || // MATHEMATICAL ITALIC EPSILON SYMBOL..MATHEMATICAL BOLD ITALIC CAPITAL OMEGA
(0x1D736 <= c && c <= 0x1D74E) || // MATHEMATICAL BOLD ITALIC SMALL ALPHA..MATHEMATICAL BOLD ITALIC SMALL OMEGA
(0x1D750 <= c && c <= 0x1D76E) || // MATHEMATICAL BOLD ITALIC EPSILON SYMBOL..MATHEMATICAL SANS-SERIF BOLD CAPITAL OMEGA
(0x1D770 <= c && c <= 0x1D788) || // MATHEMATICAL SANS-SERIF BOLD SMALL ALPHA..MATHEMATICAL SANS-SERIF BOLD SMALL OMEGA
(0x1D78A <= c && c <= 0x1D7A8) || // MATHEMATICAL SANS-SERIF BOLD EPSILON SYMBOL..MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL OMEGA
(0x1D7AA <= c && c <= 0x1D7C2) || // MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL ALPHA..MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL OMEGA
(0x1D7C4 <= c && c <= 0x1D7CB) || // MATHEMATICAL SANS-SERIF BOLD ITALIC EPSILON SYMBOL..MATHEMATICAL BOLD SMALL DIGAMMA
(0x1E900 <= c && c <= 0x1E943) // ADLAM CAPITAL LETTER ALIF..ADLAM SMALL LETTER SHA
))
}
export function isDigit(c :int) :bool {
return (
0x30 <= c && c <= 0x1E959 && ( // DIGIT ZERO..ADLAM DIGIT NINE
(0x30 <= c && c <= 0x39) || // DIGIT ZERO..DIGIT NINE
(0x660 <= c && c <= 0x669) || // ARABIC-INDIC DIGIT ZERO..ARABIC-INDIC DIGIT NINE
(0x6F0 <= c && c <= 0x6F9) || // EXTENDED ARABIC-INDIC DIGIT ZERO..EXTENDED ARABIC-INDIC DIGIT NINE
(0x7C0 <= c && c <= 0x7C9) || // NKO DIGIT ZERO..NKO DIGIT NINE
(0x966 <= c && c <= 0x96F) || // DEVANAGARI DIGIT ZERO..DEVANAGARI DIGIT NINE
(0x9E6 <= c && c <= 0x9EF) || // BENGALI DIGIT ZERO..BENGALI DIGIT NINE
(0xA66 <= c && c <= 0xA6F) || // GURMUKHI DIGIT ZERO..GURMUKHI DIGIT NINE
(0xAE6 <= c && c <= 0xAEF) || // GUJARATI DIGIT ZERO..GUJARATI DIGIT NINE
(0xB66 <= c && c <= 0xB6F) || // ORIYA DIGIT ZERO..ORIYA DIGIT NINE
(0xBE6 <= c && c <= 0xBEF) || // TAMIL DIGIT ZERO..TAMIL DIGIT NINE
(0xC66 <= c && c <= 0xC6F) || // TELUGU DIGIT ZERO..TELUGU DIGIT NINE
(0xCE6 <= c && c <= 0xCEF) || // KANNADA DIGIT ZERO..KANNADA DIGIT NINE
(0xD66 <= c && c <= 0xD6F) || // MALAYALAM DIGIT ZERO..MALAYALAM DIGIT NINE
(0xDE6 <= c && c <= 0xDEF) || // SINHALA LITH DIGIT ZERO..SINHALA LITH DIGIT NINE
(0xE50 <= c && c <= 0xE59) || // THAI DIGIT ZERO..THAI DIGIT NINE
(0xED0 <= c && c <= 0xED9) || // LAO DIGIT ZERO..LAO DIGIT NINE
(0xF20 <= c && c <= 0xF29) || // TIBETAN DIGIT ZERO..TIBETAN DIGIT NINE
(0x1040 <= c && c <= 0x1049) || // MYANMAR DIGIT ZERO..MYANMAR DIGIT NINE
(0x1090 <= c && c <= 0x1099) || // MYANMAR SHAN DIGIT ZERO..MYANMAR SHAN DIGIT NINE
(0x17E0 <= c && c <= 0x17E9) || // KHMER DIGIT ZERO..KHMER DIGIT NINE
(0x1810 <= c && c <= 0x1819) || // MONGOLIAN DIGIT ZERO..MONGOLIAN DIGIT NINE
(0x1946 <= c && c <= 0x194F) || // LIMBU DIGIT ZERO..LIMBU DIGIT NINE
(0x19D0 <= c && c <= 0x19D9) || // NEW TAI LUE DIGIT ZERO..NEW TAI LUE DIGIT NINE
(0x1A80 <= c && c <= 0x1A89) || // TAI THAM HORA DIGIT ZERO..TAI THAM HORA DIGIT NINE
(0x1A90 <= c && c <= 0x1A99) || // TAI THAM THAM DIGIT ZERO..TAI THAM THAM DIGIT NINE
(0x1B50 <= c && c <= 0x1B59) || // BALINESE DIGIT ZERO..BALINESE DIGIT NINE
(0x1BB0 <= c && c <= 0x1BB9) || // SUNDANESE DIGIT ZERO..SUNDANESE DIGIT NINE
(0x1C40 <= c && c <= 0x1C49) || // LEPCHA DIGIT ZERO..LEPCHA DIGIT NINE
(0x1C50 <= c && c <= 0x1C59) || // OL CHIKI DIGIT ZERO..OL CHIKI DIGIT NINE
(0xA620 <= c && c <= 0xA629) || // VAI DIGIT ZERO..VAI DIGIT NINE
(0xA8D0 <= c && c <= 0xA8D9) || // SAURASHTRA DIGIT ZERO..SAURASHTRA DIGIT NINE
(0xA900 <= c && c <= 0xA909) || // KAYAH LI DIGIT ZERO..KAYAH LI DIGIT NINE
(0xA9D0 <= c && c <= 0xA9D9) || // JAVANESE DIGIT ZERO..JAVANESE DIGIT NINE
(0xA9F0 <= c && c <= 0xA9F9) || // MYANMAR TAI LAING DIGIT ZERO..MYANMAR TAI LAING DIGIT NINE
(0xAA50 <= c && c <= 0xAA59) || // CHAM DIGIT ZERO..CHAM DIGIT NINE
(0xABF0 <= c && c <= 0xABF9) || // MEETEI MAYEK DIGIT ZERO..MEETEI MAYEK DIGIT NINE
(0xFF10 <= c && c <= 0xFF19) || // FULLWIDTH DIGIT ZERO..FULLWIDTH DIGIT NINE
(0x104A0 <= c && c <= 0x104A9) || // OSMANYA DIGIT ZERO..OSMANYA DIGIT NINE
(0x10D30 <= c && c <= 0x10D39) || // HANIFI ROHINGYA DIGIT ZERO..HANIFI ROHINGYA DIGIT NINE
(0x11066 <= c && c <= 0x1106F) || // BRAHMI DIGIT ZERO..BRAHMI DIGIT NINE
(0x110F0 <= c && c <= 0x110F9) || // SORA SOMPENG DIGIT ZERO..SORA SOMPENG DIGIT NINE
(0x11136 <= c && c <= 0x1113F) || // CHAKMA DIGIT ZERO..CHAKMA DIGIT NINE
(0x111D0 <= c && c <= 0x111D9) || // SHARADA DIGIT ZERO..SHARADA DIGIT NINE
(0x112F0 <= c && c <= 0x112F9) || // KHUDAWADI DIGIT ZERO..KHUDAWADI DIGIT NINE
(0x11450 <= c && c <= 0x11459) || // NEWA DIGIT ZERO..NEWA DIGIT NINE
(0x114D0 <= c && c <= 0x114D9) || // TIRHUTA DIGIT ZERO..TIRHUTA DIGIT NINE
(0x11650 <= c && c <= 0x11659) || // MODI DIGIT ZERO..MODI DIGIT NINE
(0x116C0 <= c && c <= 0x116C9) || // TAKRI DIGIT ZERO..TAKRI DIGIT NINE
(0x11730 <= c && c <= 0x11739) || // AHOM DIGIT ZERO..AHOM DIGIT NINE
(0x118E0 <= c && c <= 0x118E9) || // WARANG CITI DIGIT ZERO..WARANG CITI DIGIT NINE
(0x11C50 <= c && c <= 0x11C59) || // BHAIKSUKI DIGIT ZERO..BHAIKSUKI DIGIT NINE
(0x11D50 <= c && c <= 0x11D59) || // MASARAM GONDI DIGIT ZERO..MASARAM GONDI DIGIT NINE
(0x11DA0 <= c && c <= 0x11DA9) || // GUNJALA GONDI DIGIT ZERO..GUNJALA GONDI DIGIT NINE
(0x16A60 <= c && c <= 0x16A69) || // MRO DIGIT ZERO..MRO DIGIT NINE
(0x16B50 <= c && c <= 0x16B59) || // PAHAWH HMONG DIGIT ZERO..PAHAWH HMONG DIGIT NINE
(0x1D7CE <= c && c <= 0x1D7FF) || // MATHEMATICAL BOLD DIGIT ZERO..MATHEMATICAL MONOSPACE DIGIT NINE
(0x1E140 <= c && c <= 0x1E149) || // NYIAKENG PUACHUE HMONG DIGIT ZERO..NYIAKENG PUACHUE HMONG DIGIT NINE
(0x1E2F0 <= c && c <= 0x1E2F9) || // WANCHO DIGIT ZERO..WANCHO DIGIT NINE
(0x1E950 <= c && c <= 0x1E959) // ADLAM DIGIT ZERO..ADLAM DIGIT NINE
))
}
export function isEmojiPresentation(c :int) :bool {
return (
0x231A <= c && c <= 0x1FA95 && ( // WATCH..BANJO
(0x231A <= c && c <= 0x231B) || // WATCH..HOURGLASS
(0x23E9 <= c && c <= 0x23EC) || // BLACK RIGHT-POINTING DOUBLE TRIANGLE..BLACK DOWN-POINTING DOUBLE TRIANGLE
c == 0x23F0 || // <unknown>
c == 0x23F3 || // <unknown>
(0x25FD <= c && c <= 0x25FE) || // WHITE MEDIUM SMALL SQUARE..BLACK MEDIUM SMALL SQUARE
(0x2614 <= c && c <= 0x2615) || // UMBRELLA WITH RAIN DROPS..HOT BEVERAGE
(0x2648 <= c && c <= 0x2653) || // ARIES..PISCES
c == 0x267F || // <unknown>
c == 0x2693 || // <unknown>
c == 0x26A1 || // <unknown>
(0x26AA <= c && c <= 0x26AB) || // MEDIUM WHITE CIRCLE..MEDIUM BLACK CIRCLE
(0x26BD <= c && c <= 0x26BE) || // SOCCER BALL..BASEBALL
(0x26C4 <= c && c <= 0x26C5) || // SNOWMAN WITHOUT SNOW..SUN BEHIND CLOUD
c == 0x26CE || // <unknown>
c == 0x26D4 || // <unknown>
c == 0x26EA || // <unknown>
(0x26F2 <= c && c <= 0x26F3) || // FOUNTAIN..FLAG IN HOLE
c == 0x26F5 || // <unknown>
c == 0x26FA || // <unknown>
c == 0x26FD || // <unknown>
c == 0x2705 || // <unknown>
(0x270A <= c && c <= 0x270B) || // RAISED FIST..RAISED HAND
c == 0x2728 || // <unknown>
c == 0x274C || // <unknown>
c == 0x274E || // <unknown>
(0x2753 <= c && c <= 0x2755) || // BLACK QUESTION MARK ORNAMENT..WHITE EXCLAMATION MARK ORNAMENT
c == 0x2757 || // <unknown>
(0x2795 <= c && c <= 0x2797) || // HEAVY PLUS SIGN..HEAVY DIVISION SIGN
c == 0x27B0 || // <unknown>
c == 0x27BF || // <unknown>
(0x2B1B <= c && c <= 0x2B1C) || // BLACK LARGE SQUARE..WHITE LARGE SQUARE
c == 0x2B50 || // <unknown>
c == 0x2B55 || // <unknown>
c == 0x1F004 || // <unknown>
c == 0x1F0CF || // <unknown>
c == 0x1F18E || // <unknown>
(0x1F191 <= c && c <= 0x1F19A) || // SQUARED CL..SQUARED VS
(0x1F1E6 <= c && c <= 0x1F1FF) || // REGIONAL INDICATOR SYMBOL LETTER A..REGIONAL INDICATOR SYMBOL LETTER Z
c == 0x1F201 || // <unknown>
c == 0x1F21A || // <unknown>
c == 0x1F22F || // <unknown>
(0x1F232 <= c && c <= 0x1F236) || // SQUARED CJK UNIFIED IDEOGRAPH-7981..SQUARED CJK UNIFIED IDEOGRAPH-6709
(0x1F238 <= c && c <= 0x1F23A) || // SQUARED CJK UNIFIED IDEOGRAPH-7533..SQUARED CJK UNIFIED IDEOGRAPH-55B6
(0x1F250 <= c && c <= 0x1F251) || // CIRCLED IDEOGRAPH ADVANTAGE..CIRCLED IDEOGRAPH ACCEPT
(0x1F300 <= c && c <= 0x1F320) || // CYCLONE..SHOOTING STAR
(0x1F32D <= c && c <= 0x1F335) || // HOT DOG..CACTUS
(0x1F337 <= c && c <= 0x1F37C) || // TULIP..BABY BOTTLE
(0x1F37E <= c && c <= 0x1F393) || // BOTTLE WITH POPPING CORK..GRADUATION CAP
(0x1F3A0 <= c && c <= 0x1F3C4) || // CAROUSEL HORSE..SURFER
c == 0x1F3C5 || // <unknown>
(0x1F3C6 <= c && c <= 0x1F3CA) || // TROPHY..SWIMMER
(0x1F3CF <= c && c <= 0x1F3D3) || // CRICKET BAT AND BALL..TABLE TENNIS PADDLE AND BALL
(0x1F3E0 <= c && c <= 0x1F3F0) || // HOUSE BUILDING..EUROPEAN CASTLE
c == 0x1F3F4 || // <unknown>
(0x1F3F8 <= c && c <= 0x1F43E) || // BADMINTON RACQUET AND SHUTTLECOCK..PAW PRINTS
c == 0x1F440 || // <unknown>
(0x1F442 <= c && c <= 0x1F4F7) || // EAR..CAMERA
c == 0x1F4F8 || // <unknown>
(0x1F4F9 <= c && c <= 0x1F4FC) || // VIDEO CAMERA..VIDEOCASSETTE
c == 0x1F4FF || // <unknown>
(0x1F500 <= c && c <= 0x1F53D) || // TWISTED RIGHTWARDS ARROWS..DOWN-POINTING SMALL RED TRIANGLE
(0x1F54B <= c && c <= 0x1F54E) || // KAABA..MENORAH WITH NINE BRANCHES
(0x1F550 <= c && c <= 0x1F567) || // CLOCK FACE ONE OCLOCK..CLOCK FACE TWELVE-THIRTY
c == 0x1F57A || // <unknown>
(0x1F595 <= c && c <= 0x1F596) || // REVERSED HAND WITH MIDDLE FINGER EXTENDED..RAISED HAND WITH PART BETWEEN MIDDLE AND RING FINGERS
c == 0x1F5A4 || // <unknown>
(0x1F5FB <= c && c <= 0x1F5FF) || // MOUNT FUJI..MOYAI
c == 0x1F600 || // <unknown>
(0x1F601 <= c && c <= 0x1F610) || // GRINNING FACE WITH SMILING EYES..NEUTRAL FACE
c == 0x1F611 || // <unknown>
(0x1F612 <= c && c <= 0x1F614) || // UNAMUSED FACE..PENSIVE FACE
c == 0x1F615 || // <unknown>
c == 0x1F616 || // <unknown>
c == 0x1F617 || // <unknown>
c == 0x1F618 || // <unknown>
c == 0x1F619 || // <unknown>
c == 0x1F61A || // <unknown>
c == 0x1F61B || // <unknown>
(0x1F61C <= c && c <= 0x1F61E) || // FACE WITH STUCK-OUT TONGUE AND WINKING EYE..DISAPPOINTED FACE
c == 0x1F61F || // <unknown>
(0x1F620 <= c && c <= 0x1F62B) || // ANGRY FACE..TIRED FACE
c == 0x1F62C || // <unknown>
c == 0x1F62D || // <unknown>
(0x1F62E <= c && c <= 0x1F633) || // FACE WITH OPEN MOUTH..FLUSHED FACE
c == 0x1F634 || // <unknown>
(0x1F635 <= c && c <= 0x1F64F) || // DIZZY FACE..PERSON WITH FOLDED HANDS
(0x1F680 <= c && c <= 0x1F6C5) || // ROCKET..LEFT LUGGAGE
c == 0x1F6CC || // <unknown>
c == 0x1F6D0 || // <unknown>
(0x1F6D1 <= c && c <= 0x1F6D2) || // OCTAGONAL SIGN..SHOPPING TROLLEY
c == 0x1F6D5 || // <unknown>
(0x1F6EB <= c && c <= 0x1F6EC) || // AIRPLANE DEPARTURE..AIRPLANE ARRIVING
(0x1F6F4 <= c && c <= 0x1F6F8) || // SCOOTER..FLYING SAUCER
c == 0x1F6F9 || // <unknown>
c == 0x1F6FA || // <unknown>
(0x1F7E0 <= c && c <= 0x1F7EB) || // LARGE ORANGE CIRCLE..LARGE BROWN SQUARE
(0x1F90D <= c && c <= 0x1F91E) || // WHITE HEART..HAND WITH INDEX AND MIDDLE FINGERS CROSSED
c == 0x1F91F || // <unknown>
(0x1F920 <= c && c <= 0x1F92F) || // FACE WITH COWBOY HAT..SHOCKED FACE WITH EXPLODING HEAD
c == 0x1F930 || // <unknown>
(0x1F931 <= c && c <= 0x1F93A) || // BREAST-FEEDING..FENCER
(0x1F93C <= c && c <= 0x1F93E) || // WRESTLERS..HANDBALL
c == 0x1F93F || // <unknown>
(0x1F940 <= c && c <= 0x1F945) || // WILTED FLOWER..GOAL NET
(0x1F947 <= c && c <= 0x1F94B) || // FIRST PLACE MEDAL..MARTIAL ARTS UNIFORM
c == 0x1F94C || // <unknown>
(0x1F94D <= c && c <= 0x1F970) || // LACROSSE STICK AND BALL..SMILING FACE WITH SMILING EYES AND THREE HEARTS
c == 0x1F971 || // <unknown>
(0x1F973 <= c && c <= 0x1F976) || // FACE WITH PARTY HORN AND PARTY HAT..FREEZING FACE
c == 0x1F97A || // <unknown>
c == 0x1F97B || // <unknown>
(0x1F97C <= c && c <= 0x1F9A2) || // LAB COAT..SWAN
(0x1F9A5 <= c && c <= 0x1F9AA) || // SLOTH..OYSTER
(0x1F9AE <= c && c <= 0x1F9BF) || // GUIDE DOG..MECHANICAL LEG
c == 0x1F9C0 || // <unknown>
(0x1F9C1 <= c && c <= 0x1F9CA) || // CUPCAKE..ICE CUBE
(0x1F9CD <= c && c <= 0x1F9FF) || // STANDING PERSON..NAZAR AMULET
(0x1FA70 <= c && c <= 0x1FA73) || // BALLET SHOES..SHORTS
(0x1FA78 <= c && c <= 0x1FA7A) || // DROP OF BLOOD..STETHOSCOPE
(0x1FA80 <= c && c <= 0x1FA82) || // YO-YO..PARACHUTE
(0x1FA90 <= c && c <= 0x1FA95) // RINGED PLANET..BANJO
))
}
export function isEmojiModifierBase(c :int) :bool {
return (
0x261D <= c && c <= 0x1F9DD && ( // <unknown>..ELF
c == 0x261D || // <unknown>
c == 0x26F9 || // <unknown>
(0x270A <= c && c <= 0x270D) || // RAISED FIST..WRITING HAND
c == 0x1F385 || // <unknown>
(0x1F3C2 <= c && c <= 0x1F3C4) || // SNOWBOARDER..SURFER
c == 0x1F3C7 || // <unknown>
c == 0x1F3CA || // <unknown>
(0x1F3CB <= c && c <= 0x1F3CC) || // WEIGHT LIFTER..GOLFER
(0x1F442 <= c && c <= 0x1F443) || // EAR..NOSE
(0x1F446 <= c && c <= 0x1F450) || // WHITE UP POINTING BACKHAND INDEX..OPEN HANDS SIGN
(0x1F466 <= c && c <= 0x1F478) || // BOY..PRINCESS
c == 0x1F47C || // <unknown>
(0x1F481 <= c && c <= 0x1F483) || // INFORMATION DESK PERSON..DANCER
(0x1F485 <= c && c <= 0x1F487) || // NAIL POLISH..HAIRCUT
c == 0x1F48F || // <unknown>
c == 0x1F491 || // <unknown>
c == 0x1F4AA || // <unknown>
(0x1F574 <= c && c <= 0x1F575) || // MAN IN BUSINESS SUIT LEVITATING..SLEUTH OR SPY
c == 0x1F57A || // <unknown>
c == 0x1F590 || // <unknown>
(0x1F595 <= c && c <= 0x1F596) || // REVERSED HAND WITH MIDDLE FINGER EXTENDED..RAISED HAND WITH PART BETWEEN MIDDLE AND RING FINGERS
(0x1F645 <= c && c <= 0x1F647) || // FACE WITH NO GOOD GESTURE..PERSON BOWING DEEPLY
(0x1F64B <= c && c <= 0x1F64F) || // HAPPY PERSON RAISING ONE HAND..PERSON WITH FOLDED HANDS
c == 0x1F6A3 || // <unknown>
(0x1F6B4 <= c && c <= 0x1F6B6) || // BICYCLIST..PEDESTRIAN
c == 0x1F6C0 || // <unknown>
c == 0x1F6CC || // <unknown>
c == 0x1F90F || // <unknown>
c == 0x1F918 || // <unknown>
(0x1F919 <= c && c <= 0x1F91E) || // CALL ME HAND..HAND WITH INDEX AND MIDDLE FINGERS CROSSED
c == 0x1F91F || // <unknown>
c == 0x1F926 || // <unknown>
c == 0x1F930 || // <unknown>
(0x1F931 <= c && c <= 0x1F939) || // BREAST-FEEDING..JUGGLING
(0x1F93C <= c && c <= 0x1F93E) || // WRESTLERS..HANDBALL
(0x1F9B5 <= c && c <= 0x1F9B6) || // LEG..FOOT
(0x1F9B8 <= c && c <= 0x1F9B9) || // SUPERHERO..SUPERVILLAIN
c == 0x1F9BB || // <unknown>
(0x1F9CD <= c && c <= 0x1F9CF) || // STANDING PERSON..DEAF PERSON
(0x1F9D1 <= c && c <= 0x1F9DD) // ADULT..ELF
))
}
export function isEmojiModifier(c :int) :bool {
return (
(0x1F3FB <= c && c <= 0x1F3FF) // EMOJI MODIFIER FITZPATRICK TYPE-1-2..EMOJI MODIFIER FITZPATRICK TYPE-6
)
} | the_stack |
import { LanguageKeys } from '#lib/i18n/languageKeys';
import type { PokedexEmbedDataReturn } from '#lib/i18n/languageKeys/keys/commands/Pokemon';
import { PaginatedMessageCommand, SkyraPaginatedMessage } from '#lib/structures';
import type { GuildMessage } from '#lib/types';
import {
fetchGraphQLPokemon,
getFuzzyPokemon,
GetPokemonSpriteParameters,
getSpriteKey,
parseBulbapediaURL,
resolveColour
} from '#utils/APIs/Pokemon';
import { CdnUrls, Emojis } from '#utils/constants';
import { formatNumber } from '#utils/functions';
import { formatBoolean } from '#utils/functions/booleans';
import { sendLoadingMessage } from '#utils/util';
import type { Abilities, EvYields, Gender, Pokemon, Stats } from '@favware/graphql-pokemon';
import { ApplyOptions } from '@sapphire/decorators';
import { filterNullish, isNullish, toTitleCase } from '@sapphire/utilities';
import { MessageEmbed } from 'discord.js';
import type { TFunction } from 'i18next';
enum StatsEnum {
hp = 'HP',
attack = 'ATK',
defense = 'DEF',
specialattack = 'SPA',
specialdefense = 'SPD',
speed = 'SPE'
}
@ApplyOptions<PaginatedMessageCommand.Options>({
aliases: ['pokemon', 'dex', 'mon', 'poke', 'dexter'],
description: LanguageKeys.Commands.Pokemon.PokedexDescription,
detailedDescription: LanguageKeys.Commands.Pokemon.PokedexExtended,
flags: ['shiny', 'back']
})
export class UserPaginatedMessageCommand extends PaginatedMessageCommand {
public async messageRun(message: GuildMessage, args: PaginatedMessageCommand.Args) {
const { t } = args;
const response = await sendLoadingMessage(message, t);
const pokemon = (await args.rest('string')).toLowerCase();
const backSprite = args.getFlags('back');
const shinySprite = args.getFlags('shiny');
const pokeDetails = await this.fetchAPI(pokemon.toLowerCase(), { backSprite, shinySprite });
await this.buildDisplay(pokeDetails, t, { backSprite, shinySprite }).run(response, message.author);
return response;
}
private async fetchAPI(pokemon: string, getSpriteParams: GetPokemonSpriteParameters) {
try {
const {
data: { getFuzzyPokemon: result }
} = await fetchGraphQLPokemon<'getFuzzyPokemon'>(getFuzzyPokemon(getSpriteParams), { pokemon });
if (!result.length) {
this.error(LanguageKeys.Commands.Pokemon.PokedexQueryFail, { pokemon });
}
return result[0];
} catch {
this.error(LanguageKeys.Commands.Pokemon.PokedexQueryFail, { pokemon });
}
}
/**
* Constructs a link in the evolution chain
* @param species Name of the pokemon that the evolution goes to
* @param level Level the evolution happens
* @param evoChain The current evolution chain
* @param isEvo Whether this is an evolution or pre-evolution
*/
private constructEvoLink(species: Pokemon['species'], level: Pokemon['evolutionLevel'], evoChain: string, isEvo = true) {
if (isEvo) {
return `${evoChain} → \`${toTitleCase(species)}\` ${level ? `(${level})` : ''}`;
}
return `\`${toTitleCase(species)}\` ${level ? `(${level})` : ''} → ${evoChain}`;
}
/**
* Parse the gender ratios to an embeddable format
*/
private parseGenderRatio(genderRatio: Gender) {
if (genderRatio.male === '0%' && genderRatio.female === '0%') {
return 'Genderless';
}
return `${genderRatio.male} ${Emojis.MaleSignEmoji} | ${genderRatio.female} ${Emojis.FemaleSignEmoji}`;
}
/**
* Parses abilities to an embeddable format
* @remark required to distinguish hidden abilities from regular abilities
* @returns an array of abilities
*/
private getAbilities(abilitiesData: Abilities): string[] {
const abilities: string[] = [];
for (const [type, ability] of Object.entries(abilitiesData)) {
if (!ability) continue;
abilities.push(type === 'hidden' ? `*${ability}*` : ability);
}
return abilities;
}
/**
* Parses base stats to an embeddable format
* @returns an array of stats with their keys and values
*/
private getBaseStats(statsData: Stats): string[] {
const baseStats: string[] = [];
for (const [stat, value] of Object.entries(statsData)) {
baseStats.push(`${StatsEnum[stat as keyof Omit<Stats, '__typename'>]}: **${value}**`);
}
return baseStats;
}
/**
* Parses EV yields to an embeddable format
* @returns an array of ev yields with their keys and values
*/
private getEvYields(evYieldsData: EvYields): string[] {
const evYields: string[] = [];
for (const [stat, value] of Object.entries(evYieldsData)) {
evYields.push(`${StatsEnum[stat as keyof Omit<EvYields, '__typename'>]}: **${value}**`);
}
return evYields;
}
/**
* Parses the evolution chain to an embeddable format
* @returns The evolution chain for the Pokémon
*/
private getEvoChain(pokeDetails: Pokemon): string {
// Set evochain if there are no evolutions
let evoChain = `**${toTitleCase(pokeDetails.species)} ${pokeDetails.evolutionLevel ? `(${pokeDetails.evolutionLevel})` : ''}**` as string;
if (!pokeDetails.evolutions?.length && !pokeDetails.preevolutions?.length) {
evoChain += ' (No Evolutions)';
}
// Parse pre-evolutions and add to evochain
if (pokeDetails.preevolutions?.length) {
const { evolutionLevel } = pokeDetails.preevolutions[0];
evoChain = this.constructEvoLink(pokeDetails.preevolutions[0].species, evolutionLevel, evoChain, false);
// If the direct pre-evolution has another pre-evolution (charizard -> charmeleon -> charmander)
if (pokeDetails.preevolutions[0].preevolutions?.length) {
evoChain = this.constructEvoLink(pokeDetails.preevolutions[0].preevolutions[0].species, null, evoChain, false);
}
}
// Parse evolution chain and add to evochain
if (pokeDetails.evolutions?.length) {
evoChain = this.constructEvoLink(pokeDetails.evolutions[0].species, pokeDetails.evolutions[0].evolutionLevel, evoChain);
// In case there are multiple evolutionary paths
const otherFormeEvos = pokeDetails.evolutions.slice(1);
if (otherFormeEvos.length) {
evoChain = `${evoChain}, ${otherFormeEvos.map((oevo) => `\`${oevo.species}\` (${oevo.evolutionLevel})`).join(', ')}`;
}
// If the direct evolution has another evolution (charmander -> charmeleon -> charizard)
if (pokeDetails.evolutions[0].evolutions?.length) {
evoChain = this.constructEvoLink(
pokeDetails.evolutions[0].evolutions[0].species,
pokeDetails.evolutions[0].evolutions[0].evolutionLevel,
evoChain
);
}
}
return evoChain;
}
private buildDisplay(pokeDetails: Pokemon, t: TFunction, getSpriteParams: GetPokemonSpriteParameters) {
const abilities = this.getAbilities(pokeDetails.abilities);
const baseStats = this.getBaseStats(pokeDetails.baseStats);
const evYields = this.getEvYields(pokeDetails.evYields);
const evoChain = this.getEvoChain(pokeDetails);
const spriteToGet = getSpriteKey(getSpriteParams);
const embedTranslations = t(LanguageKeys.Commands.Pokemon.PokedexEmbedData, {
otherFormes: pokeDetails.otherFormes ?? [],
cosmeticFormes: pokeDetails.cosmeticFormes ?? [],
count: pokeDetails.types.length
});
return this.parsePokemon({ pokeDetails, abilities, baseStats, evYields, evoChain, embedTranslations, t, spriteToGet });
}
private parsePokemon({
t,
pokeDetails,
abilities,
baseStats,
evYields,
evoChain,
embedTranslations,
spriteToGet
}: PokemonToDisplayArgs): SkyraPaginatedMessage {
const externalResources = t(LanguageKeys.System.PokedexExternalResource);
const externalResourceData = [
this.isMissingno(pokeDetails)
? '[Bulbapedia](https://bulbapedia.bulbagarden.net/wiki/MissingNo.)'
: `[Bulbapedia](${parseBulbapediaURL(pokeDetails.bulbapediaPage)} )`,
this.isMissingno(pokeDetails) ? '[Serebii](https://www.serebii.net/pokedex/000.shtml)' : `[Serebii](${pokeDetails.serebiiPage})`,
this.isMissingno(pokeDetails) ? undefined : `[Smogon](${pokeDetails.smogonPage})`
]
.filter(filterNullish)
.join(' | ');
const display = new SkyraPaginatedMessage({
template: new MessageEmbed()
.setColor(resolveColour(pokeDetails.color))
.setAuthor(`#${pokeDetails.num} - ${toTitleCase(pokeDetails.species)}`, CdnUrls.Pokedex)
.setThumbnail(pokeDetails[spriteToGet])
});
display.addPageEmbed((embed) => {
embed
.addField(embedTranslations.types, pokeDetails.types.join(', '), true)
.addField(embedTranslations.abilities, t(LanguageKeys.Globals.AndListValue, { value: abilities }), true)
.addField(embedTranslations.genderRatio, this.parseGenderRatio(pokeDetails.gender), true)
.addField(embedTranslations.evolutionaryLine, evoChain)
.addField(
embedTranslations.baseStats,
`${baseStats.join(', ')} (*${embedTranslations.baseStatsTotal}*: **${pokeDetails.baseStatsTotal}**)`
);
if (!this.isCapPokemon(pokeDetails)) {
embed.addField(externalResources, externalResourceData);
}
return embed;
});
display.addPageEmbed((embed) => {
embed
.addField(embedTranslations.height, `${formatNumber(t, pokeDetails.height)}m`, true)
.addField(embedTranslations.weight, `${formatNumber(t, pokeDetails.weight)}kg`, true);
if (this.isRegularPokemon(pokeDetails)) {
if (pokeDetails.levellingRate) {
embed.addField(embedTranslations.levellingRate, pokeDetails.levellingRate, true);
}
}
if (!this.isMissingno(pokeDetails)) {
embed.addField(embedTranslations.eggGroups, pokeDetails.eggGroups?.join(', ') || '', true);
}
if (this.isRegularPokemon(pokeDetails)) {
embed.addField(embedTranslations.isEggObtainable, formatBoolean(t, pokeDetails.isEggObtainable), true);
if (!isNullish(pokeDetails.minimumHatchTime) && !isNullish(pokeDetails.maximumHatchTime)) {
embed
.addField(embedTranslations.minimumHatchingTime, formatNumber(t, pokeDetails.minimumHatchTime), true)
.addField(embedTranslations.maximumHatchTime, formatNumber(t, pokeDetails.maximumHatchTime), true);
}
embed.addField(externalResources, externalResourceData);
}
return embed;
});
if (!this.isMissingno(pokeDetails)) {
display.addPageEmbed((embed) => {
embed //
.addField(embedTranslations.smogonTier, pokeDetails.smogonTier)
.addField(embedTranslations.evYields, `${evYields.join(', ')}`);
if (this.isRegularPokemon(pokeDetails)) {
embed.addField(externalResources, externalResourceData);
}
return embed;
});
}
if (!this.isCapPokemon(pokeDetails)) {
if (pokeDetails.flavorTexts.length) {
display.addPageEmbed((embed) => {
for (const flavor of pokeDetails.flavorTexts) {
embed.addField(embedTranslations.flavourText, `\`(${flavor.game})\` ${flavor.flavor}`);
}
return embed.addField(externalResources, externalResourceData);
});
}
}
if (!this.isMissingno(pokeDetails)) {
// If there are any cosmetic formes or other formes then add a page for them
// If the pokémon doesn't have the formes then the API will default them to `null`
if (pokeDetails.cosmeticFormes || pokeDetails.otherFormes) {
display.addPageEmbed((embed) => {
// If the pokémon has other formes
if (pokeDetails.otherFormes) {
embed.addField(embedTranslations.otherFormesTitle, embedTranslations.otherFormesList);
}
// If the pokémon has cosmetic formes
if (pokeDetails.cosmeticFormes) {
embed.addField(embedTranslations.cosmeticFormesTitle, embedTranslations.cosmeticFormesList);
}
// Add the external resource field
embed.addField(externalResources, externalResourceData);
return embed;
});
}
}
return display;
}
private isCapPokemon(pokeDetails: Pokemon) {
return pokeDetails.num < 0;
}
private isRegularPokemon(pokeDetails: Pokemon) {
return pokeDetails.num > 0;
}
private isMissingno(pokeDetails: Pokemon) {
return pokeDetails.num === 0;
}
}
interface PokemonToDisplayArgs {
pokeDetails: Pokemon;
abilities: string[];
baseStats: string[];
evYields: string[];
evoChain: string;
t: TFunction;
embedTranslations: PokedexEmbedDataReturn;
spriteToGet: ReturnType<typeof getSpriteKey>;
} | the_stack |
* 网赚防刷相关参数
*/
export interface CrowdAntiRushInfo {
/**
* 助力场景建议填写:活动发起人微信OpenID。
*/
SponsorOpenId?: string
/**
* 助力场景建议填写:发起人设备号。
*/
SponsorDeviceNumber?: string
/**
* 助力场景建议填写:发起人手机号。
*/
SponsorPhone?: string
/**
* 助力场景建议填写:发起人IP。
*/
SponsorIp?: string
/**
* 助力场景建议填写:活动链接。
*/
CampaignUrl?: string
}
/**
* QueryActivityAntiRush返回参数结构体
*/
export interface QueryActivityAntiRushResponse {
/**
* 操作时间戳,单位:秒。
注意:此字段可能返回 null,表示取不到有效值。
*/
PostTime?: string
/**
* 用户操作的真实外网 IP。
注意:此字段可能返回 null,表示取不到有效值。
*/
UserIp?: string
/**
* 0:表示无恶意。
1 - 4:恶意等级由低到高。
*/
Level?: number
/**
* 风险类型。
账号风险:
1,账号信用低,账号近期存在因恶意被处罚历史,网络低活跃,被举报等因素;
2,垃圾账号,疑似批量注册小号,近期存在严重违规或大量举报;
3,无效账号,送检账号参数无法成功解析,请检查微信openid是否有误 ,QQopenid是否与appidU对应,手机号是否有误。
4,黑名单,该账号在业务侧有过拉黑记录
5,白名单,该账号在业务侧有过加白名单记录
行为风险:
101,批量操作,存在ip/设备/环境等因素的聚集性异常;
102,自动机,疑似自动机批量请求;
104,微信登录态无效,检查wxToken参数,是否已经失效;
环境风险:
201,环境异常,操作ip/设备/环境存在异常。当前ip为非常用ip或恶意ip段;
205,非公网有效ip,传进来的IP地址为内网ip地址或者ip保留地址;
206,设备异常,该设备存在异常的使用行为
*/
RiskType?: Array<number>
/**
* accountType是QQ或微信开放账号时,用于标识QQ或微信用户登录后关联业务自身的账号ID
注意:此字段可能返回 null,表示取不到有效值。
*/
AssociateAccount?: string
/**
* 用户ID
accountType不同对应不同的用户ID。如果是QQ或微信用户则填入对应的openId
注意:此字段可能返回 null,表示取不到有效值。
*/
Uid?: string
/**
* 用户操作的目的ID
比如:点赞,该字段就是被点 赞的消息 id,如果是投票,就是被投号码的 ID
注意:此字段可能返回 null,表示取不到有效值。
*/
RootId?: string
/**
* 业务侧错误码。成功时返回Success,错误时返回具体业务错误原因。
注意:此字段可能返回 null,表示取不到有效值。
*/
CodeDesc?: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 活动防刷高级版业务出参。
*/
export interface OutputActivityAntiRushAdvancedValue {
/**
* 账号ID。对应输入参数:
AccountType是1时,对应QQ的OpenID。
AccountType是2时,对应微信的OpenID/UnionID。
AccountType是4时,对应手机号。
AccountType是8时,对应imei、idfa、imeiMD5或者idfaMD5。
AccountType是0时,对应账号信息。
AccountType是10004时,对应手机号的MD5。
*/
UserId: string
/**
* 操作时间戳,单位秒(对应输入参数)。
*/
PostTime: number
/**
* AccountType 是 QQ 或微信开放账号时,用于标识 QQ 或微信用户登录后关联业务自身的账号ID(对应输入参数)。
注意:此字段可能返回 null,表示取不到有效值。
*/
AssociateAccount: string
/**
* 操作来源的外网IP(对应输入参数)。
*/
UserIp: string
/**
* 风险值:
0:表示无恶意。
1~4:恶意等级由低到高。
*/
Level: number
/**
* 风险类型,详情请参见下文RiskType详细说明。
注意:此字段可能返回 null,表示取不到有效值。
*/
RiskType: Array<number>
}
/**
* QQ账号信息。
*/
export interface QQAccountInfo {
/**
* QQ的OpenID。
*/
QQOpenId: string
/**
* QQ分配给网站或应用的AppId,用来唯一标识网站或应用。
*/
AppIdUser: string
/**
* 用于标识QQ用户登录后所关联业务自身的账号ID。
*/
AssociateAccount?: string
/**
* 账号绑定的手机号。
*/
MobilePhone?: string
/**
* 用户设备号。
*/
DeviceId?: string
}
/**
* ManageMarketingRisk请求参数结构体
*/
export interface ManageMarketingRiskRequest {
/**
* 业务入参
*/
BusinessSecurityData: InputManageMarketingRisk
}
/**
* 影响风控出参
*/
export interface OutputManageMarketingRisk {
/**
* 返回码。0表示成功,非0标识失败错误码。
注意:此字段可能返回 null,表示取不到有效值。
*/
Code: number
/**
* UTF-8编码,出错消息。
注意:此字段可能返回 null,表示取不到有效值。
*/
Message: string
/**
* 业务详情。
注意:此字段可能返回 null,表示取不到有效值。
*/
Value: OutputManageMarketingRiskValue
}
/**
* 诈骗信息。
*/
export interface OnlineScamInfo {
/**
* 内容标签。
*/
ContentLabel?: string
/**
* 内容风险等级:
0:正常。
1:可疑。
*/
ContentRiskLevel?: number
/**
* 内容产生形式:
0:对话。
1:广播。
*/
ContentType?: number
/**
* 诈骗账号类型:
1:11位手机号。
2:QQ账号。
*/
FraudType?: number
/**
* 诈骗账号,手机号或QQ账号。
*/
FraudAccount?: string
}
/**
* 营销风控入参
*/
export interface InputManageMarketingRisk {
/**
* 账号信息。
*/
Account: AccountInfo
/**
* 登录来源的外网IP
*/
UserIp: string
/**
* 用户操作时间戳,单位秒(格林威治时间精确到秒,如1501590972)。
*/
PostTime: number
/**
* 场景类型。(后续不再支持,请使用SceneCode字段)
1:活动防刷
2:登录保护
3:注册保护
4:活动防刷高级版(网赚)
*/
SceneType?: number
/**
* 用户唯一标识。
*/
UserId?: string
/**
* 设备指纹token。
*/
DeviceToken?: string
/**
* 设备指纹BusinessId
*/
DeviceBusinessId?: number
/**
* 业务ID。网站或应用在多个业务中使用此服务,通过此ID区分统计数据。
*/
BusinessId?: number
/**
* 昵称,UTF-8 编码。
*/
Nickname?: string
/**
* 用户邮箱地址(非系统自动生成)。
*/
EmailAddress?: string
/**
* 是否识别设备异常:
0:不识别。
1:识别。
*/
CheckDevice?: number
/**
* 用户HTTP请求中的Cookie进行2次hash的值,只要保证相同Cookie的hash值一致即可。
*/
CookieHash?: string
/**
* 用户HTTP请求的Referer值。
*/
Referer?: string
/**
* 用户HTTP请求的User-Agent值。
*/
UserAgent?: string
/**
* 用户HTTP请求的X-Forwarded-For值。
*/
XForwardedFor?: string
/**
* MAC地址或设备唯一标识。
*/
MacAddress?: string
/**
* 网赚防刷相关信息。SceneType为4时填写。
*/
CrowdAntiRush?: CrowdAntiRushInfo
/**
* 场景Code,控制台上获取
*/
SceneCode?: string
/**
* 详细信息
*/
Details?: Array<InputDetails>
/**
* 设备类型:
1:Android
2:IOS
*/
DeviceType?: number
}
/**
* 活动防刷高级版业务入参。
*/
export interface InputActivityAntiRushAdvanced {
/**
* 账号信息。
*/
Account: AccountInfo
/**
* 用户IP(外网有效IP地址)。
*/
UserIp: string
/**
* 用户操作时间戳,单位秒(格林威治时间精确到秒,如1501590972)。
*/
PostTime: number
/**
* 可选填写。详情请跳转至SponsorInfo查看。
*/
Sponsor?: SponsorInfo
/**
* 可选填写。详情请跳转至OnlineScamInfo查看。
*/
OnlineScam?: OnlineScamInfo
/**
* 业务ID。网站或应用在多个业务中使用此服务,通过此ID区分统计数据。
*/
BusinessId?: number
/**
* 昵称,UTF-8 编码。
*/
Nickname?: string
/**
* 用户邮箱地址(非系统自动生成)。
*/
EmailAddress?: string
/**
* 是否识别设备异常:
0:不识别。
1:识别。
*/
CheckDevice?: number
/**
* 用户HTTP请求中的Cookie进行2次hash的值,只要保证相同Cookie的hash值一致即可。
*/
CookieHash?: string
/**
* 用户HTTP请求的Referer值。
*/
Referer?: string
/**
* 用户HTTP请求的User-Agent值。
*/
UserAgent?: string
/**
* 用户HTTP请求的X-Forwarded-For值。
*/
XForwardedFor?: string
/**
* MAC地址或设备唯一标识。
*/
MacAddress?: string
/**
* 手机制造商ID,如果手机注册,请带上此信息。
*/
VendorId?: string
}
/**
* 其它账号信息。
*/
export interface OtherAccountInfo {
/**
* 其它账号信息:
AccountType是4时,填入真实的手机号(如13123456789)。
AccountType是8时,支持 imei、idfa、imeiMD5、idfaMD5 入参。
AccountType是0时,填入账号信息。
AccountType是10004时,填入手机号的MD5值。
注:imeiMd5 加密方式为:imei 明文小写后,进行 MD5 加密,加密后取小写值。IdfaMd5 加密方式为:idfa 明文大写后,进行 MD5 加密,加密后取小写值。
*/
AccountId: string
/**
* 手机号,若 AccountType 是4(手机号)、或10004(手机号 MD5),则无需重复填写,否则填入对应的手机号(如13123456789)。
*/
MobilePhone?: string
/**
* 用户设备号。若 AccountType 是8(设备号),则无需重复填写,否则填入对应的设备号。
*/
DeviceId?: string
}
/**
* 账号信息。
*/
export interface AccountInfo {
/**
* 用户账号类型(默认开通 QQ 开放账号、手机号,手机 MD5 账号类型查询。如需使用微信开放账号,则需要 提交工单 由腾讯云进行资格审核,审核通过后方可正常使用微信开放账号):
1:QQ开放账号。
2:微信开放账号。
4:手机号(暂仅支持国内手机号)。
8:设备号(imei/imeiMD5/idfa/idfaMd5)。
0:其他。
10004:手机号MD5(标准中国大陆手机号11位,MD5后取32位小写值)
*/
AccountType: number
/**
* QQ账号信息,AccountType是1时,该字段必填。
*/
QQAccount?: QQAccountInfo
/**
* 微信账号信息,AccountType是2时,该字段必填。
*/
WeChatAccount?: WeChatAccountInfo
/**
* 其它账号信息,AccountType是0、4、8或10004时,该字段必填。
*/
OtherAccount?: OtherAccountInfo
}
/**
* QueryActivityAntiRushAdvanced返回参数结构体
*/
export interface QueryActivityAntiRushAdvancedResponse {
/**
* 结果信息
*/
Data?: OutputActivityAntiRushAdvanced
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ManageMarketingRisk返回参数结构体
*/
export interface ManageMarketingRiskResponse {
/**
* 业务出参
注意:此字段可能返回 null,表示取不到有效值。
*/
Data?: OutputManageMarketingRisk
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 微信账号信息。
*/
export interface WeChatAccountInfo {
/**
* 微信的OpenID/UnionID 。
*/
WeChatOpenId: string
/**
* 微信开放账号类型:
1:微信公众号/微信第三方登录。
2:微信小程序。
*/
WeChatSubType?: number
/**
* 随机串。如果WeChatSubType是2,该字段必填。Token签名随机数,建议16个字符。
*/
RandStr?: string
/**
* 如果WeChatSubType是1,填入授权的access_token(注意:不是普通access_token,详情请参阅官方说明文档。获取网页版本的access_token时,scope字段必需填写snsapi_userinfo。
如果WeChatSubType是2,填入以session_key为密钥签名随机数RandStr(hmac_sha256签名算法)得到的字符串。
*/
WeChatAccessToken?: string
/**
* 用于标识微信用户登录后所关联业务自身的账号ID。
*/
AssociateAccount?: string
/**
* 账号绑定的手机号。
*/
MobilePhone?: string
/**
* 用户设备号。
*/
DeviceId?: string
}
/**
* 助力场景信息
*/
export interface SponsorInfo {
/**
* 助力场景建议填写:活动发起人微信OpenID。
*/
SponsorOpenId?: string
/**
* 助力场景建议填写:发起人设备号。
*/
SponsorDeviceId?: string
/**
* 助力场景建议填写:发起人手机号。
*/
SponsorPhone?: string
/**
* 助力场景建议填写:发起人IP。
*/
SponsorIp?: string
/**
* 助力场景建议填写:活动链接。
*/
CampaignUrl?: string
}
/**
* QueryActivityAntiRush请求参数结构体
*/
export interface QueryActivityAntiRushRequest {
/**
* 用户账号类型(默认开通 QQ 开放账号、手机号,手机 MD5 账号类型查询。如需使用微信开放账号,则需要 提交工单 由腾讯云进行资格审核,审核通过后方可正常使用微信开放账号):
1:QQ 开放帐号。
2:微信开放账号。
4:手机号。
0:其他。
10004:手机号 MD5。
*/
AccountType: string
/**
* 用户 ID 不同的 accountType 对应不同的用户 ID。如果是 QQ,则填入对应的 openid,微信用户则填入对应的 openid/unionid,手机号则填入对应真实用户手机号(如13123456789)。
*/
Uid: string
/**
* 用户的真实外网 IP。若填入非外网有效ip,会返回level=0的风控结果,risktype中会有205的风险码返回作为标识
*/
UserIp: string
/**
* 用户操作时间戳。
*/
PostTime: string
/**
* accountType 是QQ开放账号时,该参数必填,表示 QQ 开放平台分配给网站或应用的 AppID,用来唯一标识网站或应用。
*/
AppIdU?: string
/**
* 昵称,UTF-8 编码。
*/
NickName?: string
/**
* 手机号。若 accountType 选4(手机号)、或10004(手机号 MD5),则无需重复填写。否则填入对应的手机号(如15912345687)。accountType为1或2时,该字段支持MD5值;
*/
PhoneNumber?: string
/**
* 用户邮箱地址。
*/
EmailAddress?: string
/**
* 注册时间戳。
*/
RegisterTime?: string
/**
* 注册来源的外网 IP。
*/
RegisterIp?: string
/**
* 用户 HTTP 请求中的 cookie 进行2次 hash 的值,只要保证相同 cookie 的 hash 值一致即可。
*/
CookieHash?: string
/**
* 地址。
*/
Address?: string
/**
* 登录来源:
0:其他。
1:PC 网页。
2:移动页面。
3:App。
4:微信公众号。
*/
LoginSource?: string
/**
* 登录方式:
0:其他。
1:手动账号密码输入。
2:动态短信密码登录。
3:二维码扫描登录。
*/
LoginType?: string
/**
* 登录耗时,单位:秒。
*/
LoginSpend?: string
/**
* 用户操作的目的 ID,如点赞等,该字段就是被点赞的消息 ID,如果是投票,则为被投号码的 ID。
*/
RootId?: string
/**
* 用户 HTTP 请求的 referer 值。
*/
Referer?: string
/**
* 登录成功后跳转页面。
*/
JumpUrl?: string
/**
* 用户 HTTP 请求的 userAgent。
*/
UserAgent?: string
/**
* 用户 HTTP 请求中的 x_forward_for。
*/
XForwardedFor?: string
/**
* 用户操作过程中鼠标单击次数。
*/
MouseClickCount?: string
/**
* 用户操作过程中键盘单击次数。
*/
KeyboardClickCount?: string
/**
* MAC 地址或设备唯一标识。
*/
MacAddress?: string
/**
* 手机制造商 ID,如果手机注册,请带上此信息。
*/
VendorId?: string
/**
* 手机设备号。支持以下格式:
1.imei明文
2.idfa明文,
3.imei小写后MD5值小写
4.idfa大写后MD5值小写
*/
Imei?: string
/**
* App 客户端版本。
*/
AppVersion?: string
/**
* 业务 ID 网站或应用在多个业务中使用此服务,通过此 ID 区分统计数据。
*/
BusinessId?: string
/**
* 1:微信公众号。
2:微信小程序。
*/
WxSubType?: string
/**
* Token 签名随机数,WxSubType为微信小程序时必填,建议16个字符。
*/
RandNum?: string
/**
* 如果 accountType为2而且wxSubType有填,该字段必选,否则不需要填写;
如果是微信小程序(WxSubType=2),该字段为以ssesion_key为key去签名随机数radnNum得到的值( hmac_sha256签名算法);如果是微信公众号或第三方登录,则为授权的access_token(网页版本的access_Token,而且获取token的scope字段必需填写snsapi_userinfo;)
*/
WxToken?: string
/**
* 是否识别设备异常:
0:不识别。
1:识别。
*/
CheckDevice?: string
}
/**
* 入参的详细参数信息
*/
export interface InputDetails {
/**
* 字段名称
*/
FieldName: string
/**
* 字段值
*/
FieldValue: string
}
/**
* 营销风控出参值
*/
export interface OutputManageMarketingRiskValue {
/**
* 账号ID。对应输入参数:
AccountType是1时,对应QQ的OpenID。
AccountType是2时,对应微信的OpenID/UnionID。
AccountType是4时,对应手机号。
AccountType是8时,对应imei、idfa、imeiMD5或者idfaMD5。
AccountType是0时,对应账号信息。
AccountType是10004时,对应手机号的MD5。
注意:此字段可能返回 null,表示取不到有效值。
*/
UserId: string
/**
* 操作时间戳,单位秒(对应输入参数)。
注意:此字段可能返回 null,表示取不到有效值。
*/
PostTime: number
/**
* 对应输入参数,AccountType 是 QQ 或微信开放账号时,用于标识 QQ 或微信用户登录后关联业务自身的账号ID。
注意:此字段可能返回 null,表示取不到有效值。
*/
AssociateAccount: string
/**
* 操作来源的外网IP(对应输入参数)。
注意:此字段可能返回 null,表示取不到有效值。
*/
UserIp: string
/**
* 风险值
pass : 无恶意
review:需要人工审核
reject:拒绝,高风险恶意
注意:此字段可能返回 null,表示取不到有效值。
*/
RiskLevel: string
/**
* 风险类型,请参考官网风险类型
注意:此字段可能返回 null,表示取不到有效值。
*/
RiskType: Array<number>
}
/**
* 活动防刷高级版业务出参。
*/
export interface OutputActivityAntiRushAdvanced {
/**
* 返回码。0表示成功,非0标识失败错误码。
*/
Code: number
/**
* UTF-8编码,出错消息。
*/
Message: string
/**
* 服务调用结果。
*/
Value: OutputActivityAntiRushAdvancedValue
}
/**
* QueryActivityAntiRushAdvanced请求参数结构体
*/
export interface QueryActivityAntiRushAdvancedRequest {
/**
* 业务入参
*/
BusinessSecurityData: InputActivityAntiRushAdvanced
} | the_stack |
import {assert} from '../platform/assert-web.js';
import {ArcInspector, ArcInspectorFactory} from './arc-inspector.js';
import {FakePecFactory} from './fake-pec-factory.js';
import {Id, IdGenerator} from './id.js';
import {Loader} from '../platform/loader.js';
import {CapabilitiesResolver} from './capabilities-resolver.js';
import {Dictionary, Runnable, compareComparables} from '../utils/lib-utils.js';
import {MessagePort} from './message-channel.js';
import {Modality} from './arcs-types/modality.js';
import {ParticleExecutionHost} from './particle-execution-host.js';
import {ParticleSpec} from './arcs-types/particle-spec.js';
import {Particle, Slot, Handle} from './recipe/lib-recipe.js';
import {SlotComposer} from './slot-composer.js';
import {InterfaceType, Type} from '../types/lib-types.js';
import {PecFactory} from './particle-execution-context.js';
import {VolatileMemory, VolatileStorageDriverProvider, VolatileStorageKey} from './storage/drivers/volatile.js';
import {DriverFactory} from './storage/drivers/driver-factory.js';
import {Exists} from './storage/drivers/driver.js';
import {StorageKey} from './storage/storage-key.js';
import {ArcSerializer, ArcInterface} from './arc-serializer.js';
import {ReferenceModeStorageKey} from './storage/reference-mode-storage-key.js';
import {SystemTrace} from '../tracelib/systrace.js';
import {StorageKeyParser} from './storage/storage-key-parser.js';
import {SingletonInterfaceHandle, TypeToCRDTTypeRecord} from './storage/storage.js';
import {StoreInfo} from './storage/store-info.js';
import {ActiveStore} from './storage/active-store.js';
import {StorageService} from './storage/storage-service.js';
import {ArcInfo} from './arc-info.js';
import {Allocator} from './allocator.js';
import {ArcHost} from './arc-host.js';
export type ArcOptions = Readonly<{
arcInfo: ArcInfo,
storageService: StorageService;
pecFactories?: PecFactory[];
allocator?: Allocator;
host?: ArcHost;
slotComposer?: SlotComposer;
loader: Loader;
storageKey?: StorageKey;
stub?: boolean;
inspectorFactory?: ArcInspectorFactory;
ports?: MessagePort[];
driverFactory: DriverFactory;
storageKeyParser: StorageKeyParser;
}>;
@SystemTrace
export class Arc implements ArcInterface {
private readonly pecFactories: PecFactory[];
public get isSpeculative(): boolean { return this.arcInfo.isSpeculative; }
public get isInnerArc(): boolean { return this.arcInfo.isInnerArc; }
public readonly isStub: boolean;
// Public for debug access
public readonly _loader: Loader;
private readonly dataChangeCallbacks = new Map<object, Runnable>();
// storage keys for referenced handles
public get storeInfoById(): Dictionary<StoreInfo<Type>> { return this.arcInfo.storeInfoById; }
public readonly storageKey?: StorageKey;
public get capabilitiesResolver(): CapabilitiesResolver { return this.arcInfo.capabilitiesResolver; }
// Map from each store ID to a set of tags. public for debug access
public get storeTagsById() { return this.arcInfo.storeTagsById; }
// Map from each store to its description (originating in the manifest).
get storeDescriptions() { return this.arcInfo.storeDescriptions; }
private waitForIdlePromise: Promise<void> | null;
private readonly inspectorFactory?: ArcInspectorFactory;
public readonly inspector?: ArcInspector;
readonly innerArcs: Arc[]= [];
readonly arcInfo: ArcInfo;
public get id(): Id { return this.arcInfo.id; }
public get idGenerator(): IdGenerator { return this.arcInfo.idGenerator; }
loadedParticleInfo = new Map<string, {spec: ParticleSpec, stores: Map<string, StoreInfo<Type>>}>();
readonly peh: ParticleExecutionHost;
public readonly storageService: StorageService;
public readonly driverFactory: DriverFactory;
public readonly storageKeyParser: StorageKeyParser;
// Volatile storage local to this Arc instance.
readonly volatileMemory = new VolatileMemory();
private readonly volatileStorageDriverProvider: VolatileStorageDriverProvider;
constructor({arcInfo, storageService, pecFactories, allocator, host, slotComposer, loader, storageKey, stub, inspectorFactory, driverFactory, storageKeyParser} : ArcOptions) {
this.driverFactory = driverFactory;
this.storageKeyParser = storageKeyParser;
// TODO: pecFactories should not be optional. update all callers and fix here.
this.pecFactories = pecFactories && pecFactories.length > 0 ? pecFactories.slice() : [FakePecFactory(loader).bind(null)];
this.arcInfo = arcInfo;
this.isStub = !!stub;
this._loader = loader;
this.inspectorFactory = inspectorFactory;
this.inspector = inspectorFactory && inspectorFactory.create(this);
this.storageKey = storageKey;
const ports = this.pecFactories.map(f => f(this.generateID(), this.idGenerator, this.storageKeyParser));
this.peh = new ParticleExecutionHost({slotComposer, arc: this, ports, allocator, host});
this.volatileStorageDriverProvider = new VolatileStorageDriverProvider(this);
this.driverFactory.register(this.volatileStorageDriverProvider);
this.storageService = storageService;
// TODO(sjmiles): currently some UiBrokers need to recover arc from composer in order to forward events
if (slotComposer && !slotComposer['arc']) {
slotComposer['arc'] = this.arcInfo;
slotComposer['peh'] = this.peh;
}
}
get loader(): Loader {
return this._loader;
}
get modality(): Modality {
return this.arcInfo.modality;
}
dispose(): void {
// TODO: disconnect all associated store event handlers
this.peh.stop();
this.peh.close();
// Slot contexts and consumers from inner and outer arcs can be interwoven. Slot composer
// is therefore disposed in its entirety with an outer Arc's disposal.
if (!this.isInnerArc && this.peh.slotComposer) {
this.peh.slotComposer.dispose();
}
this.driverFactory.unregister(this.volatileStorageDriverProvider);
}
// Returns a promise that spins sending a single `AwaitIdle` message until it
// sees no other messages were sent.
async _waitForIdle(): Promise<void> {
// eslint-disable-next-line no-constant-condition
while (true) {
const messageCount = this.peh.messageCount;
const innerArcsLength = this.innerArcs.length;
// tslint:disable-next-line: no-any
await Promise.all([this.peh.idle as Promise<any>, ...this.innerArcs.map(async arc => arc.idle)]);
// We're idle if no new inner arcs appeared and this.pec had exactly 2 messages,
// one requesting the idle status, and one answering it.
if (this.innerArcs.length === innerArcsLength
&& this.peh.messageCount === messageCount + 2) break;
}
}
// Work around a bug in the way we track idleness. It could be:
// - in the new storage stack
// - in DomMultiplexer
// - in the idleness detection code.
get idle(): Promise<void> {
return this._idle.then(async () => this._idle);
}
get _idle(): Promise<void> {
if (this.waitForIdlePromise) {
return this.waitForIdlePromise;
}
// Store one active completion promise for use by any subsequent callers.
// We explicitly want to avoid, for example, multiple simultaneous
// attempts to identify idle state each sending their own `AwaitIdle`
// message and expecting settlement that will never arrive.
const promise =
this._waitForIdle().then(() => this.waitForIdlePromise = null);
this.waitForIdlePromise = promise;
return promise;
}
addInnerArc(innerArc: Arc) {
this.innerArcs.push(innerArc);
}
async serialize(): Promise<string> {
await this.idle;
return new ArcSerializer(this).serialize();
}
// Writes `serialization` to the ArcInfo child key under the Arc's storageKey.
// This does not directly use serialize() as callers may want to modify the
// contents of the serialized arc before persisting.
async persistSerialization(serialization: string): Promise<void> {
throw new Error('persistSerialization unimplemented, pending synthetic type support in new storage stack');
}
get context() {
return this.arcInfo.context;
}
get activeRecipe() { return this.arcInfo.activeRecipe; }
get recipeDeltas() { return this.arcInfo.recipeDeltas; }
loadedParticleSpecs() {
return [...this.loadedParticleInfo.values()].map(({spec}) => spec);
}
async _instantiateParticle(recipeParticle: Particle, reinstantiate: boolean) {
if (!recipeParticle.id) {
recipeParticle.id = this.generateID('particle');
}
const info = await this._getParticleInstantiationInfo(recipeParticle);
await this.peh.instantiate(recipeParticle, info.stores, info.storeMuxers, reinstantiate);
}
async _getParticleInstantiationInfo(recipeParticle: Particle): Promise<{spec: ParticleSpec, stores: Map<string, StoreInfo<Type>>, storeMuxers: Map<string, StoreInfo<Type>>}> {
const info = {spec: recipeParticle.spec, stores: new Map<string, StoreInfo<Type>>(), storeMuxers: new Map<string, StoreInfo<Type>>()};
this.loadedParticleInfo.set(recipeParticle.id.toString(), info);
// if supported, provide particle caching via a BlobUrl representing spec.implFile
await this._provisionSpecUrl(recipeParticle.spec);
for (const [name, connection] of Object.entries(recipeParticle.connections)) {
if (connection.handle.fate !== '`slot') {
const store = this.findStoreById(connection.handle.id);
assert(store, `can't find store of id ${connection.handle.id}`);
assert(info.spec.handleConnectionMap.get(name) !== undefined, 'can\'t connect handle to a connection that doesn\'t exist');
if (store.isMuxEntityStore()) {
info.storeMuxers.set(name, store);
} else {
info.stores.set(name, store);
}
}
}
return info;
}
private async _provisionSpecUrl(spec: ParticleSpec): Promise<void> {
// if supported, construct spec.implBlobUrl for spec.implFile
if (spec.implFile && !spec.implBlobUrl) {
if (this.loader) {
const url = await this.loader.provisionObjectUrl(spec.implFile);
if (url) {
spec.setImplBlobUrl(url);
}
}
}
}
generateID(component: string = ''): Id {
return this.arcInfo.generateID(component);
}
get stores(): StoreInfo<Type>[] {
return this.arcInfo.stores;
}
async getActiveStore<T extends Type>(storeInfo: StoreInfo<T>): Promise<ActiveStore<TypeToCRDTTypeRecord<T>>> {
return this.storageService.getActiveStore(storeInfo);
}
/**
* Instantiates the given recipe in the Arc.
*
* Executes the following steps:
*
* - Populates missing slots.
* - Processes the Handles and creates stores for them.
* - Instantiates the new Particles
* - Passes these particles for initialization in the PEC
*
* Waits for completion of an existing Instantiate before returning.
*/
async instantiate(particles: Particle[], handles: Handle[], reinstantiate: boolean = false): Promise<void> {
for (const recipeHandle of handles) {
const fate = recipeHandle.originalFate && recipeHandle.originalFate !== '?'
? recipeHandle.originalFate : recipeHandle.fate;
const newStore = this.storeInfoById[recipeHandle.id];
assert(newStore);
if (recipeHandle.immediateValue) {
const particleSpec = recipeHandle.immediateValue;
const type = recipeHandle.type;
if (newStore.isSingletonInterfaceStore()) {
assert(type instanceof InterfaceType && type.interfaceInfo.particleMatches(particleSpec));
await this.getActiveStore(newStore);
const handle: SingletonInterfaceHandle = await this.storageService.handleForStoreInfo(
newStore, this.arcInfo.generateID().toString(), this.arcInfo.idGenerator, {ttl: recipeHandle.getTtl()}) as SingletonInterfaceHandle;
await handle.set(particleSpec.clone());
} else {
throw new Error(`Can't currently store immediate values in non-singleton stores`);
}
continue;
}
if (fate === 'map') {
await this.createActiveStore(newStore);
} else if (['copy', 'create'].includes(fate)) {
await this.createStoreInternal(newStore);
if (fate === 'copy') {
const copiedStoreRef = this.context.findStoreById(recipeHandle.originalId);
const copiedActiveStore = await this.getActiveStore(copiedStoreRef);
assert(copiedActiveStore, `Cannot find store ${recipeHandle.originalId}`);
const activeStore = await this.getActiveStore(newStore);
await activeStore.cloneFrom(copiedActiveStore);
}
}
}
await Promise.all(particles.map(recipeParticle => this._instantiateParticle(recipeParticle, reinstantiate)));
if (this.inspector) {
await this.inspector.recipeInstantiated(particles, this.activeRecipe.toString());
}
}
private async createStoreInternal<T extends Type>(storeInfo: StoreInfo<T>): Promise<void> {
await this.createActiveStore(storeInfo);
if (storeInfo.storageKey instanceof ReferenceModeStorageKey) {
const containerStoreInfo = this.arcInfo.findStoreInfoByStorageKey(storeInfo.storageKey.storageKey);
assert(containerStoreInfo);
await this.createStoreInternal(containerStoreInfo);
const backingStoreInfo = this.arcInfo.findStoreInfoByStorageKey(storeInfo.storageKey.backingKey);
assert(backingStoreInfo);
await this.createStoreInternal(backingStoreInfo);
}
}
private async createActiveStore(store: StoreInfo<Type>): Promise<void> {
const activeStore = await this.getActiveStore(store);
activeStore.on(async () => this._onDataChange());
}
_onDataChange(): void {
for (const callback of this.dataChangeCallbacks.values()) {
callback();
}
}
onDataChange(callback: Runnable, registration: object): void {
this.dataChangeCallbacks.set(registration, callback);
}
clearDataChange(registration: object): void {
this.dataChangeCallbacks.delete(registration);
}
findStoresByType<T extends Type>(type: T, options?: {tags: string[]}): StoreInfo<T>[] {
return this.arcInfo.findStoresByType(type, options);
}
findStoreById(id: string): StoreInfo<Type> {
return this.arcInfo.findStoreById(id);
}
toContextString(): string {
const results: string[] = [];
const storeInfos = Object.values(this.storeInfoById).sort(compareComparables);
storeInfos.forEach(storeInfo => {
results.push(storeInfo.toManifestString({handleTags: [...this.storeTagsById[storeInfo.id]]}));
});
// TODO: include stores entities
// TODO: include (remote) slots?
if (!this.activeRecipe.isEmpty()) {
results.push(this.activeRecipe.toString());
}
return results.join('\n');
}
get apiChannelMappingId() {
return this.id.toString();
}
} | the_stack |
import * as mume from "@shd101wyy/mume";
import { MarkdownEngine } from "@shd101wyy/mume";
import { useExternalAddFileProtocolFunction } from "@shd101wyy/mume/out/src/utility";
import * as fs from "fs";
import { tmpdir } from "os";
import * as path from "path";
import * as vscode from "vscode";
import { TextEditor, Uri } from "vscode";
import { MarkdownPreviewEnhancedConfig } from "./config";
// http://www.typescriptlang.org/play/
// https://github.com/Microsoft/vscode/blob/master/extensions/markdown/media/main.js
// https://github.com/Microsoft/vscode/tree/master/extensions/markdown/src
// https://github.com/tomoki1207/gfm-preview/blob/master/src/gfmProvider.ts
// https://github.com/cbreeden/vscode-markdownit
export class MarkdownPreviewEnhancedView {
private waiting: boolean = false;
/**
* The key is markdown file fsPath
* value is MarkdownEngine
*/
private engineMaps: { [key: string]: MarkdownEngine } = {};
/**
* The key is markdown file fspath
* value is Preview (vscode.Webview) object
*/
private previewMaps: { [key: string]: vscode.WebviewPanel } = {};
private preview2EditorMap: Map<
vscode.WebviewPanel,
vscode.TextEditor
> = new Map();
private singlePreviewPanel: vscode.WebviewPanel;
private singlePreviewPanelSourceUriTarget: Uri;
/**
* The key is markdown file fsPath
* value is JSAndCssFiles
*/
private jsAndCssFilesMaps: { [key: string]: string[] } = {};
private config: MarkdownPreviewEnhancedConfig;
public constructor(private context: vscode.ExtensionContext) {
this.config = MarkdownPreviewEnhancedConfig.getCurrentConfig();
mume
.init(this.config.configPath) // init markdown-preview-enhanced
.then(() => {
mume.onDidChangeConfigFile(this.refreshAllPreviews.bind(this));
MarkdownEngine.onModifySource(this.modifySource.bind(this));
useExternalAddFileProtocolFunction(
(filePath: string, preview: vscode.WebviewPanel) => {
if (preview) {
return preview.webview
.asWebviewUri(vscode.Uri.file(filePath))
.toString(true)
.replace(/%3F/gi, "?")
.replace(/%23/g, "#");
} else {
if (!filePath.startsWith("file://")) {
filePath = "file:///" + filePath;
}
filePath = filePath.replace(/^file\:\/+/, "file:///");
return filePath;
}
},
);
const extensionVersion = require(path.resolve(
this.context.extensionPath,
"./package.json",
))["version"];
if (extensionVersion !== mume.configs.config["vscode_mpe_version"]) {
const config = Object.assign({}, mume.configs.config, {
vscode_mpe_version: extensionVersion,
});
fs.writeFileSync(
path.resolve(mume.getExtensionConfigPath(), "config.json"),
JSON.stringify(config),
);
if (!mume.configs.config["vscode_mpe_version"]) {
// Only show once
const actions = ["Open GitHub Sponsors", "I already sponsored"];
vscode.window
.showInformationMessage(
"If you like using markdown-preview-enhanced, please consider sponsoring the developer to help make this project better 😊.",
...actions,
)
.then((value) => {
if (value === actions[0]) {
mume.utility.openFile(
"https://github.com/sponsors/shd101wyy",
);
} else if (value === actions[1]) {
config["already_sponsored"] = true;
fs.writeFileSync(
path.resolve(mume.getExtensionConfigPath(), "config.json"),
JSON.stringify(config),
);
}
});
}
}
})
.catch((error) => {
vscode.window.showErrorMessage(error.toString());
});
}
private refreshAllPreviews() {
// clear caches
for (const key in this.engineMaps) {
if (this.engineMaps.hasOwnProperty(key)) {
const engine = this.engineMaps[key];
if (engine) {
// No need to resetConfig.
// Otherwiser when user change settings like `previewTheme`, the preview won't change immediately.
// engine.resetConfig();
engine.clearCaches();
}
}
}
// refresh iframes
if (useSinglePreview()) {
this.refreshPreviewPanel(this.singlePreviewPanelSourceUriTarget);
} else {
for (const key in this.previewMaps) {
if (this.previewMaps.hasOwnProperty(key)) {
this.refreshPreviewPanel(vscode.Uri.file(key));
}
}
}
}
/**
* modify markdown source, append `result` after corresponding code chunk.
* @param codeChunkData
* @param result
* @param filePath
*/
private async modifySource(
codeChunkData: mume.CodeChunkData,
result: string,
filePath: string,
): Promise<string> {
function insertResult(i: number, editor: TextEditor) {
const lineCount = editor.document.lineCount;
let start = 0;
// find <!-- code_chunk_output -->
for (let j = i + 1; j < i + 6 && j < lineCount; j++) {
if (
editor.document
.lineAt(j)
.text.startsWith("<!-- code_chunk_output -->")
) {
start = j;
break;
}
}
if (start) {
// found
// TODO: modify exited output
let end = start + 1;
while (end < lineCount) {
if (
editor.document
.lineAt(end)
.text.startsWith("<!-- /code_chunk_output -->")
) {
break;
}
end += 1;
}
// if output not changed, then no need to modify editor buffer
let r = "";
for (let i2 = start + 2; i2 < end - 1; i2++) {
r += editor.document.lineAt(i2).text + "\n";
}
if (r === result + "\n") {
return "";
} // no need to modify output
editor.edit((edit) => {
edit.replace(
new vscode.Range(
new vscode.Position(start + 2, 0),
new vscode.Position(end - 1, 0),
),
result + "\n",
);
});
return "";
} else {
editor.edit((edit) => {
edit.insert(
new vscode.Position(i + 1, 0),
`\n<!-- code_chunk_output -->\n\n${result}\n\n<!-- /code_chunk_output -->\n`,
);
});
return "";
}
}
const visibleTextEditors = vscode.window.visibleTextEditors;
for (let i = 0; i < visibleTextEditors.length; i++) {
const editor = visibleTextEditors[i];
if (this.formatPathIfNecessary(editor.document.uri.fsPath) === filePath) {
let codeChunkOffset = 0;
const targetCodeChunkOffset =
codeChunkData.normalizedInfo.attributes["code_chunk_offset"];
const lineCount = editor.document.lineCount;
for (let i2 = 0; i2 < lineCount; i2++) {
const line = editor.document.lineAt(i2);
if (line.text.match(/^```(.+)\"?cmd\"?\s*[=\s}]/)) {
if (codeChunkOffset === targetCodeChunkOffset) {
i2 = i2 + 1;
while (i2 < lineCount) {
if (editor.document.lineAt(i2).text.match(/^\`\`\`\s*/)) {
break;
}
i2 += 1;
}
return insertResult(i2, editor);
} else {
codeChunkOffset++;
}
} else if (line.text.match(/\@import\s+(.+)\"?cmd\"?\s*[=\s}]/)) {
if (codeChunkOffset === targetCodeChunkOffset) {
return insertResult(i2, editor);
} else {
codeChunkOffset++;
}
}
}
break;
}
}
return "";
}
/**
* return markdown engine of sourceUri
* @param sourceUri
*/
public getEngine(sourceUri: Uri): MarkdownEngine {
return this.engineMaps[sourceUri.fsPath];
}
/**
* return markdown preview of sourceUri
* @param sourceUri
*/
public getPreview(sourceUri: Uri): vscode.WebviewPanel {
if (useSinglePreview()) {
return this.singlePreviewPanel;
} else {
return this.previewMaps[sourceUri.fsPath];
}
}
/**
* check if the markdown preview is on for the textEditor
* @param textEditor
*/
public isPreviewOn(sourceUri: Uri) {
if (useSinglePreview()) {
return !!this.singlePreviewPanel;
} else {
return !!this.getPreview(sourceUri);
}
}
public destroyPreview(sourceUri: Uri) {
if (useSinglePreview()) {
this.singlePreviewPanel = null;
this.singlePreviewPanelSourceUriTarget = null;
this.preview2EditorMap = new Map();
this.previewMaps = {};
} else {
const previewPanel = this.getPreview(sourceUri);
if (previewPanel) {
this.preview2EditorMap.delete(previewPanel);
delete this.previewMaps[sourceUri.fsPath];
}
}
}
/**
* remove engine from this.engineMaps
* @param sourceUri
*/
public destroyEngine(sourceUri: Uri) {
if (useSinglePreview()) {
return (this.engineMaps = {});
}
const engine = this.getEngine(sourceUri);
if (engine) {
delete this.engineMaps[sourceUri.fsPath]; // destroy engine
}
}
/**
* Format pathString if it is on Windows. Convert `c:\` like string to `C:\`
* @param pathString
*/
private formatPathIfNecessary(pathString: string) {
if (process.platform === "win32") {
pathString = pathString.replace(
/^([a-zA-Z])\:\\/,
(_, $1) => `${$1.toUpperCase()}:\\`,
);
}
return pathString;
}
private getProjectDirectoryPath(
sourceUri: Uri,
workspaceFolders: readonly vscode.WorkspaceFolder[] = [],
) {
const possibleWorkspaceFolders = workspaceFolders.filter(
(workspaceFolder) => {
return (
path
.dirname(sourceUri.path.toUpperCase())
.indexOf(workspaceFolder.uri.path.toUpperCase()) >= 0
);
},
);
let projectDirectoryPath;
if (possibleWorkspaceFolders.length) {
// We pick the workspaceUri that has the longest path
const workspaceFolder = possibleWorkspaceFolders.sort(
(x, y) => y.uri.fsPath.length - x.uri.fsPath.length,
)[0];
projectDirectoryPath = workspaceFolder.uri.fsPath;
} else {
projectDirectoryPath = "";
}
return this.formatPathIfNecessary(projectDirectoryPath);
}
private getFilePath(sourceUri: Uri) {
return this.formatPathIfNecessary(sourceUri.fsPath);
}
/**
* Initialize MarkdownEngine for this markdown file
*/
public initMarkdownEngine(sourceUri: Uri): MarkdownEngine {
let engine = this.getEngine(sourceUri);
if (!engine) {
engine = new MarkdownEngine({
filePath: this.getFilePath(sourceUri),
projectDirectoryPath: this.getProjectDirectoryPath(
sourceUri,
vscode.workspace.workspaceFolders,
),
config: this.config,
});
this.engineMaps[sourceUri.fsPath] = engine;
this.jsAndCssFilesMaps[sourceUri.fsPath] = [];
}
return engine;
}
public async initPreview(
sourceUri: vscode.Uri,
editor: vscode.TextEditor,
viewOptions: { viewColumn: vscode.ViewColumn; preserveFocus?: boolean },
) {
const isUsingSinglePreview = useSinglePreview();
let previewPanel: vscode.WebviewPanel;
if (isUsingSinglePreview && this.singlePreviewPanel) {
const oldResourceRoot =
this.getProjectDirectoryPath(
this.singlePreviewPanelSourceUriTarget,
vscode.workspace.workspaceFolders,
) || path.dirname(this.singlePreviewPanelSourceUriTarget.fsPath);
const newResourceRoot =
this.getProjectDirectoryPath(
sourceUri,
vscode.workspace.workspaceFolders,
) || path.dirname(sourceUri.fsPath);
if (oldResourceRoot !== newResourceRoot) {
this.singlePreviewPanel.dispose();
return this.initPreview(sourceUri, editor, viewOptions);
} else {
previewPanel = this.singlePreviewPanel;
this.singlePreviewPanelSourceUriTarget = sourceUri;
}
} else if (this.previewMaps[sourceUri.fsPath]) {
previewPanel = this.previewMaps[sourceUri.fsPath];
} else {
const localResourceRoots = [
vscode.Uri.file(this.context.extensionPath),
vscode.Uri.file(mume.utility.extensionDirectoryPath),
vscode.Uri.file(mume.getExtensionConfigPath()),
vscode.Uri.file(tmpdir()),
vscode.Uri.file(
this.getProjectDirectoryPath(
sourceUri,
vscode.workspace.workspaceFolders,
) || path.dirname(sourceUri.fsPath),
),
];
previewPanel = vscode.window.createWebviewPanel(
"markdown-preview-enhanced",
`Preview ${path.basename(sourceUri.fsPath)}`,
viewOptions,
{
enableFindWidget: true,
localResourceRoots,
enableScripts: true, // TODO: This might be set by enableScriptExecution config. But for now we just enable it.
},
);
previewPanel.iconPath = vscode.Uri.file(
path.join(this.context.extensionPath, "media", "preview.svg"),
);
// register previewPanel message events
previewPanel.webview.onDidReceiveMessage(
(message) => {
vscode.commands.executeCommand(
`_mume.${message.command}`,
...message.args,
);
},
null,
this.context.subscriptions,
);
// unregister previewPanel
previewPanel.onDidDispose(
() => {
this.destroyPreview(sourceUri);
this.destroyEngine(sourceUri);
},
null,
this.context.subscriptions,
);
if (isUsingSinglePreview) {
this.singlePreviewPanel = previewPanel;
this.singlePreviewPanelSourceUriTarget = sourceUri;
}
}
// register previewPanel
this.previewMaps[sourceUri.fsPath] = previewPanel;
this.preview2EditorMap.set(previewPanel, editor);
// set title
previewPanel.title = `Preview ${path.basename(sourceUri.fsPath)}`;
// init markdown engine
let initialLine: number | undefined;
if (editor && editor.document.uri.fsPath === sourceUri.fsPath) {
initialLine = await new Promise((resolve, reject) => {
// Hack: sometimes we only get 0. I couldn't find API to wait for editor getting loaded.
setTimeout(() => {
return resolve(editor.selections[0].active.line || 0);
}, 100);
});
}
const text = editor.document.getText();
let engine = this.getEngine(sourceUri);
if (!engine) {
engine = this.initMarkdownEngine(sourceUri);
}
engine
.generateHTMLTemplateForPreview({
inputString: text,
config: {
sourceUri: sourceUri.toString(),
initialLine,
vscode: true,
},
contentSecurityPolicy: "",
vscodePreviewPanel: previewPanel,
})
.then((html) => {
previewPanel.webview.html = html;
});
}
/**
* Close all previews
*/
public closeAllPreviews(singlePreview: boolean) {
if (singlePreview) {
if (this.singlePreviewPanel) {
this.singlePreviewPanel.dispose();
}
} else {
const previewPanels = [];
for (const key in this.previewMaps) {
if (this.previewMaps.hasOwnProperty(key)) {
const previewPanel = this.previewMaps[key];
if (previewPanel) {
previewPanels.push(previewPanel);
}
}
}
previewPanels.forEach((previewPanel) => previewPanel.dispose());
}
this.previewMaps = {};
this.preview2EditorMap = new Map();
this.engineMaps = {};
this.singlePreviewPanel = null;
this.singlePreviewPanelSourceUriTarget = null;
}
public previewPostMessage(sourceUri: Uri, message: any) {
const preview = this.getPreview(sourceUri);
if (preview) {
preview.webview.postMessage(message);
}
}
public previewHasTheSameSingleSourceUri(sourceUri: Uri) {
if (!this.singlePreviewPanelSourceUriTarget) {
return false;
} else {
return this.singlePreviewPanelSourceUriTarget.fsPath === sourceUri.fsPath;
}
}
public updateMarkdown(sourceUri: Uri, triggeredBySave?: boolean) {
const engine = this.getEngine(sourceUri);
if (!engine) {
return;
}
const previewPanel = this.getPreview(sourceUri);
if (!previewPanel) {
return;
}
// presentation mode
if (engine.isPreviewInPresentationMode) {
return this.refreshPreview(sourceUri);
}
// not presentation mode
vscode.workspace.openTextDocument(sourceUri).then((document) => {
const text = document.getText();
this.previewPostMessage(sourceUri, {
command: "startParsingMarkdown",
});
const preview = this.getPreview(sourceUri);
engine
.parseMD(text, {
isForPreview: true,
useRelativeFilePath: false,
hideFrontMatter: false,
triggeredBySave,
vscodePreviewPanel: preview,
})
.then(({ markdown, html, tocHTML, JSAndCssFiles, yamlConfig }) => {
// check JSAndCssFiles
if (
JSON.stringify(JSAndCssFiles) !==
JSON.stringify(this.jsAndCssFilesMaps[sourceUri.fsPath]) ||
yamlConfig["isPresentationMode"]
) {
this.jsAndCssFilesMaps[sourceUri.fsPath] = JSAndCssFiles;
// restart iframe
this.refreshPreview(sourceUri);
} else {
this.previewPostMessage(sourceUri, {
command: "updateHTML",
html,
tocHTML,
totalLineCount: document.lineCount,
sourceUri: sourceUri.toString(),
id: yamlConfig.id || "",
class: yamlConfig.class || "",
});
}
});
});
}
public refreshPreviewPanel(sourceUri: Uri) {
this.preview2EditorMap.forEach((editor, previewPanel) => {
if (
previewPanel &&
editor &&
editor.document &&
isMarkdownFile(editor.document) &&
editor.document.uri &&
editor.document.uri.fsPath === sourceUri.fsPath
) {
this.initPreview(sourceUri, editor, {
viewColumn: previewPanel.viewColumn,
preserveFocus: true,
});
}
});
}
public refreshPreview(sourceUri: Uri) {
const engine = this.getEngine(sourceUri);
if (engine) {
engine.clearCaches();
// restart iframe
this.refreshPreviewPanel(sourceUri);
}
}
public openInBrowser(sourceUri: Uri) {
const engine = this.getEngine(sourceUri);
if (engine) {
engine.openInBrowser({}).catch((error) => {
vscode.window.showErrorMessage(error.toString());
});
}
}
public htmlExport(sourceUri: Uri, offline: boolean) {
const engine = this.getEngine(sourceUri);
if (engine) {
engine
.htmlExport({ offline })
.then((dest) => {
vscode.window.showInformationMessage(
`File ${path.basename(dest)} was created at path: ${dest}`,
);
})
.catch((error) => {
vscode.window.showErrorMessage(error.toString());
});
}
}
public chromeExport(sourceUri: Uri, type: string) {
const engine = this.getEngine(sourceUri);
if (engine) {
engine
.chromeExport({ fileType: type, openFileAfterGeneration: true })
.then((dest) => {
vscode.window.showInformationMessage(
`File ${path.basename(dest)} was created at path: ${dest}`,
);
})
.catch((error) => {
vscode.window.showErrorMessage(error.toString());
});
}
}
public princeExport(sourceUri: Uri) {
const engine = this.getEngine(sourceUri);
if (engine) {
engine
.princeExport({ openFileAfterGeneration: true })
.then((dest) => {
if (dest.endsWith("?print-pdf")) {
// presentation pdf
vscode.window.showInformationMessage(
`Please copy and open the link: { ${dest.replace(
/\_/g,
"\\_",
)} } in Chrome then Print as Pdf.`,
);
} else {
vscode.window.showInformationMessage(
`File ${path.basename(dest)} was created at path: ${dest}`,
);
}
})
.catch((error) => {
vscode.window.showErrorMessage(error.toString());
});
}
}
public eBookExport(sourceUri: Uri, fileType: string) {
const engine = this.getEngine(sourceUri);
if (engine) {
engine
.eBookExport({ fileType, runAllCodeChunks: false })
.then((dest) => {
vscode.window.showInformationMessage(
`eBook ${path.basename(dest)} was created as path: ${dest}`,
);
})
.catch((error) => {
vscode.window.showErrorMessage(error.toString());
});
}
}
public pandocExport(sourceUri) {
const engine = this.getEngine(sourceUri);
if (engine) {
engine
.pandocExport({ openFileAfterGeneration: true })
.then((dest) => {
vscode.window.showInformationMessage(
`Document ${path.basename(dest)} was created as path: ${dest}`,
);
})
.catch((error) => {
vscode.window.showErrorMessage(error.toString());
});
}
}
public markdownExport(sourceUri) {
const engine = this.getEngine(sourceUri);
if (engine) {
engine
.markdownExport({})
.then((dest) => {
vscode.window.showInformationMessage(
`Document ${path.basename(dest)} was created as path: ${dest}`,
);
})
.catch((error) => {
vscode.window.showErrorMessage(error.toString());
});
}
}
/*
public cacheSVG(sourceUri: Uri, code:string, svg:string) {
const engine = this.getEngine(sourceUri)
if (engine) {
engine.cacheSVG(code, svg)
}
}
*/
public cacheCodeChunkResult(sourceUri: Uri, id: string, result: string) {
const engine = this.getEngine(sourceUri);
if (engine) {
engine.cacheCodeChunkResult(id, result);
}
}
public runCodeChunk(sourceUri: Uri, codeChunkId: string) {
const engine = this.getEngine(sourceUri);
if (engine) {
engine.runCodeChunk(codeChunkId).then(() => {
this.updateMarkdown(sourceUri);
});
}
}
public runAllCodeChunks(sourceUri) {
const engine = this.getEngine(sourceUri);
if (engine) {
engine.runCodeChunks().then(() => {
this.updateMarkdown(sourceUri);
});
}
}
public update(sourceUri: Uri) {
if (!this.config.liveUpdate || !this.getPreview(sourceUri)) {
return;
}
if (!this.waiting) {
this.waiting = true;
setTimeout(() => {
this.waiting = false;
// this._onDidChange.fire(uri);
this.updateMarkdown(sourceUri);
}, 300);
}
}
public updateConfiguration() {
const newConfig = MarkdownPreviewEnhancedConfig.getCurrentConfig();
if (!this.config.isEqualTo(newConfig)) {
// if `singlePreview` setting is changed, close all previews.
if (this.config.singlePreview !== newConfig.singlePreview) {
this.closeAllPreviews(this.config.singlePreview);
this.config = newConfig;
} else {
this.config = newConfig;
for (const fsPath in this.engineMaps) {
if (this.engineMaps.hasOwnProperty(fsPath)) {
const engine = this.engineMaps[fsPath];
engine.updateConfiguration(newConfig);
}
}
// update all generated md documents
this.refreshAllPreviews();
}
}
}
public openImageHelper(sourceUri: Uri) {
if (sourceUri.scheme === "markdown-preview-enhanced") {
return vscode.window.showWarningMessage("Please focus a markdown file.");
} else if (!this.isPreviewOn(sourceUri)) {
return vscode.window.showWarningMessage("Please open preview first.");
} else {
return this.previewPostMessage(sourceUri, {
command: "openImageHelper",
});
}
}
}
/**
* check whehter to use only one preview or not
*/
export function useSinglePreview() {
const config = vscode.workspace.getConfiguration("markdown-preview-enhanced");
return config.get<boolean>("singlePreview");
}
export function getPreviewUri(uri: vscode.Uri) {
if (uri.scheme === "markdown-preview-enhanced") {
return uri;
}
let previewUri: Uri;
if (useSinglePreview()) {
previewUri = uri.with({
scheme: "markdown-preview-enhanced",
path: "single-preview.rendered",
});
} else {
previewUri = uri.with({
scheme: "markdown-preview-enhanced",
path: uri.path + ".rendered",
query: uri.toString(),
});
}
return previewUri;
}
export function isMarkdownFile(document: vscode.TextDocument) {
return (
document.languageId === "markdown" &&
document.uri.scheme !== "markdown-preview-enhanced"
); // prevent processing of own documents
} | the_stack |
import { strict as assert } from "assert";
import { IFluidHandle } from "@fluidframework/core-interfaces";
import { IFluidDataStoreRuntime } from "@fluidframework/datastore-definitions";
import { ISharedMap, SharedMap } from "@fluidframework/map";
import {
ConsensusRegisterCollection,
IConsensusRegisterCollection,
ReadPolicy,
} from "@fluidframework/register-collection";
import { requestFluidObject } from "@fluidframework/runtime-utils";
import {
ITestObjectProvider,
ITestContainerConfig,
DataObjectFactoryType,
ITestFluidObject,
ChannelFactoryRegistry,
} from "@fluidframework/test-utils";
import { describeFullCompat } from "@fluidframework/test-version-utils";
interface ISharedObjectConstructor<T> {
create(runtime: IFluidDataStoreRuntime, id?: string): T;
}
const mapId = "mapKey";
const registry: ChannelFactoryRegistry = [
[mapId, SharedMap.getFactory()],
[undefined, ConsensusRegisterCollection.getFactory()],
];
const testContainerConfig: ITestContainerConfig = {
fluidDataObjectType: DataObjectFactoryType.Test,
registry,
};
function generate(name: string, ctor: ISharedObjectConstructor<IConsensusRegisterCollection>) {
describeFullCompat(name, (getTestObjectProvider) => {
let provider: ITestObjectProvider;
beforeEach(() => {
provider = getTestObjectProvider();
});
let dataStore1: ITestFluidObject;
let sharedMap1: ISharedMap;
let sharedMap2: ISharedMap;
let sharedMap3: ISharedMap;
beforeEach(async () => {
// Create a Container for the first client.
const container1 = await provider.makeTestContainer(testContainerConfig);
dataStore1 = await requestFluidObject<ITestFluidObject>(container1, "default");
sharedMap1 = await dataStore1.getSharedObject<SharedMap>(mapId);
// Load the Container that was created by the first client.
const container2 = await provider.loadTestContainer(testContainerConfig);
const dataStore2 = await requestFluidObject<ITestFluidObject>(container2, "default");
sharedMap2 = await dataStore2.getSharedObject<SharedMap>(mapId);
// Load the Container that was created by the first client.
const container3 = await provider.loadTestContainer(testContainerConfig);
const dataStore3 = await requestFluidObject<ITestFluidObject>(container3, "default");
sharedMap3 = await dataStore3.getSharedObject<SharedMap>(mapId);
});
it("Basic functionality", async () => {
const collection1 = ctor.create(dataStore1.runtime);
sharedMap1.set("collection", collection1.handle);
await collection1.write("key1", "value1");
await collection1.write("key2", "value2");
const [collection2Handle, collection3Handle] = await Promise.all([
sharedMap2.wait<IFluidHandle<IConsensusRegisterCollection>>("collection"),
sharedMap3.wait<IFluidHandle<IConsensusRegisterCollection>>("collection"),
]);
assert(collection2Handle);
assert(collection3Handle);
const collection2 = await collection2Handle.get();
const collection3 = await collection3Handle.get();
await provider.ensureSynchronized();
assert.strictEqual(collection1.read("key1"), "value1", "Collection not initialize in document 1");
assert.strictEqual(collection2.read("key1"), "value1", "Collection not initialize in document 2");
assert.strictEqual(collection3.read("key1"), "value1", "Collection not initialize in document 3");
assert.strictEqual(collection1.read("key2"), "value2", "Collection not initialize in document 1");
assert.strictEqual(collection2.read("key2"), "value2", "Collection not initialize in document 2");
assert.strictEqual(collection3.read("key2"), "value2", "Collection not initialize in document 3");
assert.strictEqual(collection1.read("key3"), undefined, "Reading non existent key should be undefined");
assert.strictEqual(collection2.read("key3"), undefined, "Reading non existent key should be undefined");
assert.strictEqual(collection3.read("key3"), undefined, "Reading non existent key should be undefined");
});
it("Should store all concurrent writings on a key in sequenced order", async () => {
const collection1 = ctor.create(dataStore1.runtime);
sharedMap1.set("collection", collection1.handle);
const [collection2Handle, collection3Handle] = await Promise.all([
sharedMap2.wait<IFluidHandle<IConsensusRegisterCollection>>("collection"),
sharedMap3.wait<IFluidHandle<IConsensusRegisterCollection>>("collection"),
]);
assert(collection2Handle);
assert(collection3Handle);
const collection2 = await collection2Handle.get();
const collection3 = await collection3Handle.get();
// Force processOutgoing for the following write to make sure the op is sequence in the right order
const write1P = collection1.write("key1", "value1");
await provider.opProcessingController.processOutgoing();
const write2P = collection2.write("key1", "value2");
await provider.opProcessingController.processOutgoing();
const write3P = collection3.write("key1", "value3");
await provider.opProcessingController.processOutgoing();
// Resume normal processing now that we have done ordering our action
provider.opProcessingController.resumeProcessing();
await Promise.all([write1P, write2P, write3P]);
await provider.ensureSynchronized();
const versions = collection1.readVersions("key1");
assert(versions);
assert.strictEqual(versions.length, 3, "Concurrent updates were not preserved");
assert.strictEqual(versions[0], "value1", "Incorrect update sequence");
assert.strictEqual(versions[1], "value2", "Incorrect update sequence");
assert.strictEqual(versions[2], "value3", "Incorrect update sequence");
assert.strictEqual(collection1.read("key1"), "value1", "Default read policy is atomic");
assert.strictEqual(collection1.read("key1", ReadPolicy.Atomic), "value1", "Atomic policy should work");
assert.strictEqual(collection1.read("key1", ReadPolicy.LWW), "value3", "LWW policy should work");
});
it("Happened after updates should overwrite previous versions", async () => {
const collection1 = ctor.create(dataStore1.runtime);
sharedMap1.set("collection", collection1.handle);
const [collection2Handle, collection3Handle] = await Promise.all([
sharedMap2.wait<IFluidHandle<IConsensusRegisterCollection>>("collection"),
sharedMap3.wait<IFluidHandle<IConsensusRegisterCollection>>("collection"),
]);
assert(collection2Handle);
assert(collection3Handle);
const collection2 = await collection2Handle.get();
const collection3 = await collection3Handle.get();
const write1P = collection1.write("key1", "value1");
const write2P = collection2.write("key1", "value2");
const write3P = collection3.write("key1", "value3");
await Promise.all([write1P, write2P, write3P]);
await provider.ensureSynchronized();
const versions = collection1.readVersions("key1");
assert(versions);
assert.strictEqual(versions.length, 3, "Concurrent updates were not preserved");
await collection3.write("key1", "value4");
await provider.ensureSynchronized();
const versions2 = collection1.readVersions("key1");
assert(versions2);
assert.strictEqual(versions2.length, 1, "Happened after value did not overwrite");
assert.strictEqual(versions2[0], "value4", "Happened after value did not overwrite");
await collection2.write("key1", "value5");
await provider.ensureSynchronized();
const versions3 = collection1.readVersions("key1");
assert(versions3);
assert.strictEqual(versions3.length, 1, "Happened after value did not overwrite");
assert.strictEqual(versions3[0], "value5", "Happened after value did not overwrite");
await collection1.write("key1", "value6");
await provider.ensureSynchronized();
const versions4 = collection1.readVersions("key1");
assert(versions4);
assert.strictEqual(versions4.length, 1, "Happened after value did not overwrite");
assert.strictEqual(versions4[0], "value6", "Happened after value did not overwrite");
// Force processOutgoing for the following write to make sure the op is sequence in the right order
const write7P = collection1.write("key1", "value7");
await provider.opProcessingController.processOutgoing();
const write8P = collection2.write("key1", "value8");
await provider.opProcessingController.processOutgoing();
const write9P = collection3.write("key1", "value9");
await provider.opProcessingController.processOutgoing();
// Resume normal processing now that we have done ordering our action
provider.opProcessingController.resumeProcessing();
await Promise.all([write7P, write8P, write9P]);
await provider.ensureSynchronized();
const versions5 = collection3.readVersions("key1");
assert(versions5);
assert.strictEqual(versions5.length, 3, "Concurrent happened after updates should overwrite and preserve");
assert.strictEqual(versions5[0], "value7", "Incorrect update sequence");
assert.strictEqual(versions5[1], "value8", "Incorrect update sequence");
assert.strictEqual(versions5[2], "value9", "Incorrect update sequence");
await collection2.write("key1", "value10");
const versions6 = collection2.readVersions("key1");
assert(versions6);
assert.strictEqual(versions6.length, 1, "Happened after value did not overwrite");
assert.strictEqual(versions6[0], "value10", "Happened after value did not overwrite");
});
it("Can store handles", async () => {
// Set up the collection with two handles and add it to the map so other containers can find it
const collection1 = ctor.create(dataStore1.runtime);
sharedMap1.set("test", "sampleValue");
sharedMap1.set("collection", collection1.handle);
await collection1.write("handleA", sharedMap1.handle);
await collection1.write("handleB", sharedMap1.handle);
// Pull the collection off of the 2nd container
const collection2Handle =
await sharedMap2.wait<IFluidHandle<IConsensusRegisterCollection>>("collection");
assert(collection2Handle);
const collection2 = await collection2Handle.get();
// acquire one handle in each container
const sharedMap1HandleB = collection1.read("handleB") as IFluidHandle<ISharedMap>;
const sharedMap1Prime = await sharedMap1HandleB.get();
const sharedMap2HandleA = collection2.read("handleA") as IFluidHandle<ISharedMap>;
const sharedMap2Prime = await sharedMap2HandleA.get();
assert.equal(sharedMap1Prime.get("test"), "sampleValue");
assert.equal(sharedMap2Prime.get("test"), "sampleValue");
});
});
}
generate("ConsensusRegisterCollection", ConsensusRegisterCollection); | the_stack |
import { basename } from '@waiting/shared-core'
import * as assert from 'power-assert'
import {
settingsDefault,
_UNICODE_HOLDER,
_WIN64_HOLDER,
} from '../src/lib/config'
import {
DataTypes,
FnParam,
LoadSettings,
MacroDef,
MacroMap,
} from '../src/lib/ffi.model'
import * as H from '../src/lib/helper'
import { macroMap } from '../src/lib/marcomap'
import * as WD from '../src/lib/windef'
import rewire = require('rewire')
const filename = basename(__filename)
const mods = rewire('../src/lib/helper')
describe(filename + ' :parse_param_placeholder(param, settings?) ', () => {
const fnName = 'parse_param_placeholder'
const fn = mods.__get__(fnName)
it(`Should ${fnName} handle value of settings correctly)`, () => {
const st = { ...settingsDefault } as LoadSettings
try {
const p: any = null
fn(p, st)
assert(false, 'should throw Error by invalid param, but not')
}
catch (ex) {
assert(true)
}
})
it(`Should ${fnName} handle value of param correctly)`, () => {
const st = { ...settingsDefault } as LoadSettings
try {
const p: MacroDef = ['invalid_placeholder', 'int64', 'int32']
fn(p, st)
assert(false, 'should throw Error by invalid param, but not')
}
catch (ex) {
assert(true)
}
})
it(`Should ${fnName} handle value of settings for arch of nodejs correctly)`, () => {
const p1 = 'debug_int64'
const p2 = 'debug_int32'
const p: MacroDef = [_WIN64_HOLDER, p1, p2]
const st = { ...settingsDefault }
const str1 = fn(p, { ...st, _WIN64: true })
assert(str1 === p1, `result should be "${p1}", got ${str1}`)
const str2 = fn(p, { ...st, _WIN64: false })
assert(str2 === p2, `result should be "${p2}", got ${str2}`)
})
it(`Should ${fnName} handle value of settings for ANSI/UNICODE correctly)`, () => {
const LPTSTR: MacroDef = [_UNICODE_HOLDER, WD.LPWSTR, 'uint8*']
const st = { ...settingsDefault }
const str1 = fn(LPTSTR, { ...st, _UNICODE: true })
assert(str1 === LPTSTR[1], `result should be "${LPTSTR[1]}", got ${str1}`)
const str2 = fn(LPTSTR, { ...st, _UNICODE: false })
assert(str2 === LPTSTR[2], `result should be "${LPTSTR[2]}", got ${str2}`)
})
it(`Should ${fnName} handle invalid length of param correctly)`, () => {
const LPTSTR = [_UNICODE_HOLDER, WD.LPWSTR]
const st = { ...settingsDefault }
try {
fn(LPTSTR as [string, string, string], { ...st, _UNICODE: true })
assert(false, 'shout throw error but NOT')
}
catch (ex) {
assert(true)
}
})
it(`Should ${fnName} handle blank of param correctly)`, () => {
const LPTSTR = ''
const st = { ...settingsDefault }
try {
fn(LPTSTR, { ...st, _UNICODE: true })
assert(false, 'shout throw error but NOT')
}
catch (ex) {
assert(true)
}
})
})
describe(filename + ' :parse_placeholder_arch(param, _WIN64)', () => {
const fnName = 'parse_placeholder_arch'
const fn = mods.__get__(fnName)
it(`Should ${fnName} handle value of param correctly)`, () => {
const p: any = 'test'
const res = fn(p, true)
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
assert(res === p, `should ${p} got ${res}`)
})
it(`Should ${fnName} handle value of param correctly)`, () => {
try {
const p: any = null
fn(p, true)
assert(false, 'should throw Error by invalid param, but not')
}
catch (ex) {
assert(true)
}
})
it(`Should ${fnName} handle value of param correctly)`, () => {
try {
const p: any = [1, 2] // should 3 items
fn(p, true)
assert(false, 'should throw Error by invalid param, but not')
}
catch (ex) {
assert(true)
}
})
})
describe(filename + ' :parse_placeholder_unicode(param, _WIN64)', () => {
const fnName = 'parse_placeholder_unicode'
const fn = mods.__get__(fnName)
it(`Should ${fnName} handle value of param correctly)`, () => {
const p: any = 'test'
const res = fn(p, true)
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
assert(res === p, `should ${p} got ${res}`)
})
it(`Should ${fnName} handle value of param correctly)`, () => {
try {
const p: any = null
fn(p, true)
assert(false, 'should throw Error by invalid param, but not')
}
catch (ex) {
assert(true)
}
})
it(`Should ${fnName} handle value of param correctly)`, () => {
try {
const p: any = [1, 2] // should 3 items
fn(p, true)
assert(false, 'should throw Error by invalid param, but not')
}
catch (ex) {
assert(true)
}
})
})
describe(filename + ' :parse_windef()', () => {
const fnName = 'parse_windef()'
const fake = 'fake'
it(`Should ${fnName} process windef with fake windef correctly)`, () => {
const W = { ...WD }
Object.defineProperty(W, fake, {
configurable: true,
writable: true,
enumerable: true,
value: 777, // should string or string[]
})
try {
H.parse_windef(W, macroMap)
assert(false, 'should throw Error, but none')
}
catch (ex) {
assert(true)
}
Object.getOwnPropertyNames(W).forEach((val) => {
if (val === fake) {
W[val] = 'int'
}
})
Object.defineProperty(W, 777, { // should string
configurable: true,
writable: true,
enumerable: true,
value: 'int',
})
try {
H.parse_windef(W, macroMap)
assert(false, 'should throw Error, but none')
}
catch (ex) {
Object.defineProperty(W, 777, { // should string
enumerable: false,
})
assert(true)
}
})
it(`Should ${fnName} process windef macro members correctly)`, () => {
const W: DataTypes = {}
const keyArch = '__testKeyArch'
const v64 = '_v64'
const v32 = '_v32'
W[keyArch] = _WIN64_HOLDER
let map: MacroMap = new Map([ [keyArch, [_WIN64_HOLDER, v64, v32] ] ])
let _WIN64 = true
try {
H.parse_windef(W, map, { ...settingsDefault, _WIN64 })
assert(false, 'should throw error by validateWinData() BUT not')
}
catch (ex) {
assert(true)
}
_WIN64 = false
try {
H.parse_windef(W, map, { ...settingsDefault, _WIN64 })
assert(false, 'should throw error by validateWinData() BUT not')
}
catch (ex) {
assert(true)
}
const keyUni = '__testKeyUNI'
const uni = '_valueUNICODE'
const ansi = '_valueANSI'
delete W[keyArch]
W[keyUni] = _UNICODE_HOLDER
map = new Map([ [keyUni, [_UNICODE_HOLDER, uni, ansi] ] ]) as MacroMap
let _UNICODE = true
try {
H.parse_windef(W, map, { ...settingsDefault, _UNICODE })
assert(false, 'should throw error by validateWinData() BUT not')
}
catch (ex) {
assert(true)
}
_UNICODE = false
try {
H.parse_windef(W, map, { ...settingsDefault, _UNICODE })
assert(false, 'should throw error by validateWinData() BUT not')
}
catch (ex) {
assert(true)
}
})
// at lastest
it(`Should ${fnName} process windef correctly)`, () => {
const W = { ...WD }
const windata = H.parse_windef(W, macroMap, { ...settingsDefault })
const lenData = Object.keys(windata).length
const lenDef = Object.keys(W).length
if (lenData !== lenDef) {
const onlyInRet: Set<string> = new Set()
const onlyInW: Set<string> = new Set()
for (const key of Object.keys(windata)) {
if (typeof W[key] === 'undefined') {
onlyInRet.add(key)
}
}
for (const key of Object.keys(W)) {
if (typeof windata[key] === 'undefined') {
onlyInW.add(key)
}
}
console.info(onlyInRet, onlyInW)
assert(false, `lenData:${lenData}, lenDef:${lenDef} not equal `)
}
})
})
describe(filename + ' :isValidDataDef()', () => {
const fnName = 'isValidDataDef()'
it(`Should ${fnName} works)`, () => {
const srcMap = new Set(['int'])
try {
H.isValidDataDef('int', srcMap)
assert(true)
}
catch (ex) {
return assert(false, 'should passed, but throw error')
}
try {
H.isValidDataDef('float', srcMap)
return assert(false, 'should throw error with invalid value, but NOT')
}
catch (ex) {
assert(true)
}
try {
H.isValidDataDef('', srcMap)
return assert(false, 'should throw error with blank string, but NOT')
}
catch (ex) {
assert(true)
}
try {
H.isValidDataDef('int', new Set())
return assert(false, 'should throw error with blank Set, but NOT')
}
catch (ex) {
assert(true)
}
})
})
describe(filename + ' :validateWinData()', () => {
const fnName = 'validateWinData()'
it(`Should ${fnName} works)`, () => {
const srcMap = new Set(['int'])
try {
H.validateWinData({ BOOL: 'int' }, srcMap)
assert(true)
}
catch (ex) {
return assert(false, 'should passed, but throw error')
}
try {
H.validateWinData({ BOOL: 'float' }, srcMap)
return assert(false, 'should throw error with invalid value, but NOT')
}
catch (ex) {
assert(true)
}
try {
H.validateWinData({ [Symbol.for('test')]: 'int' }, srcMap)
return assert(false, 'should throw error with invalid value, but NOT')
}
catch (ex) {
assert(true)
}
try {
H.validateWinData({ 7: 'int' }, srcMap)
return assert(false, 'should throw error with invalid value, but NOT')
}
catch (ex) {
assert(true)
}
try {
H.validateWinData({ '': 'int' }, srcMap)
return assert(false, 'should throw error with invalid value, but NOT')
}
catch (ex) {
assert(true)
}
try {
H.validateWinData({ '': 'float' }, srcMap)
return assert(false, 'should throw error with invalid value, but NOT')
}
catch (ex) {
assert(true)
}
})
})
describe(filename + ' :prepare_windef_ref()', () => {
const fnName = 'prepare_windef_ref'
const fn = mods.__get__(fnName)
it(`Should ${fnName}() works)`, () => {
const ww = { FAKE: 'fake' }
const macroSrc: Map<string, string> = new Map()
macroSrc.set('FAKE', '')
try {
fn(ww, macroSrc)
return assert(false, 'should throw error, but NOT')
}
catch (ex) {
assert(true)
}
})
})
describe(filename + ' :_lookupRef()', () => {
const fnName = '_lookupRef'
const fn = mods.__get__(fnName)
it(`Should ${fnName}() works)`, () => {
const ww = { Fake: 'PVOID' }
const fakeValue = 'vooid'
const macroSrc: Map<string, string> = new Map()
macroSrc.set('PVOID', fakeValue)
let ret = fn('PVOID', ww, macroSrc)
assert(ret === fakeValue, `should got result "${fakeValue}, but got "${ret}" `)
ret = fn('fakekey', ww, macroSrc)
assert(ret === '', `should got blank result , but got "${ret}" `)
})
}) | the_stack |
import { createPool, Pool, PoolConfig, PoolConnection, UpsertResult } from 'mariadb';
import {
DefaultPlatform,
SqlBuilder,
SQLConnection,
SQLConnectionPool,
SQLDatabaseAdapter,
SQLDatabaseQuery,
SQLDatabaseQueryFactory,
SQLPersistence,
SQLQueryModel,
SQLQueryResolver,
SQLStatement
} from '@deepkit/sql';
import { DatabaseLogger, DatabasePersistenceChangeSet, DatabaseSession, DatabaseTransaction, DeleteResult, Entity, PatchResult, UniqueConstraintFailure } from '@deepkit/orm';
import { MySQLPlatform } from './mysql-platform';
import { Changes, ClassSchema, getClassSchema, getPropertyXtoClassFunction, isArray, resolvePropertySchema } from '@deepkit/type';
import { asyncOperation, ClassType, empty } from '@deepkit/core';
import { FrameCategory, Stopwatch } from '@deepkit/stopwatch';
function handleError(error: Error | string): void {
const message = 'string' === typeof error ? error : error.message;
if (message.includes('Duplicate entry')) {
//todo: extract table name, column name, and find ClassSchema
throw new UniqueConstraintFailure();
}
}
export class MySQLStatement extends SQLStatement {
constructor(protected logger: DatabaseLogger, protected sql: string, protected connection: PoolConnection, protected stopwatch?: Stopwatch) {
super();
}
async get(params: any[] = []) {
const frame = this.stopwatch ? this.stopwatch.start('Query', FrameCategory.databaseQuery) : undefined;
try {
if (frame) frame.data({ sql: this.sql, sqlParams: params });
//mysql/mariadb driver does not maintain error.stack when they throw errors, so
//we have to manually convert it using asyncOperation.
const rows = await asyncOperation<any[]>((resolve, reject) => {
this.connection.query(this.sql, params).then(resolve).catch(reject);
});
this.logger.logQuery(this.sql, params);
return rows[0];
} catch (error) {
handleError(error);
this.logger.failedQuery(error, this.sql, params);
throw error;
} finally {
if (frame) frame.end();
}
}
async all(params: any[] = []) {
const frame = this.stopwatch ? this.stopwatch.start('Query', FrameCategory.databaseQuery) : undefined;
try {
if (frame) frame.data({ sql: this.sql, sqlParams: params });
//mysql/mariadb driver does not maintain error.stack when they throw errors, so
//we have to manually convert it using asyncOperation.
const rows = await asyncOperation<any[]>((resolve, reject) => {
this.connection.query(this.sql, params).then(resolve).catch(reject);
});
this.logger.logQuery(this.sql, params);
return rows;
} catch (error) {
handleError(error);
this.logger.failedQuery(error, this.sql, params);
throw error;
} finally {
if (frame) frame.end();
}
}
release() {
}
}
export class MySQLConnection extends SQLConnection {
protected changes: number = 0;
public lastExecResult?: UpsertResult[];
protected connector?: Promise<PoolConnection>;
constructor(
public connection: PoolConnection,
connectionPool: SQLConnectionPool,
logger?: DatabaseLogger,
transaction?: DatabaseTransaction,
stopwatch?: Stopwatch,
) {
super(connectionPool, logger, transaction, stopwatch);
}
async prepare(sql: string) {
return new MySQLStatement(this.logger, sql, this.connection);
}
async run(sql: string, params: any[] = []) {
const frame = this.stopwatch ? this.stopwatch.start('Query', FrameCategory.databaseQuery) : undefined;
//batch returns in reality a single UpsertResult if only one query is given
try {
if (frame) frame.data({ sql, sqlParams: params });
const res = (await this.connection.query(sql, params)) as UpsertResult[] | UpsertResult;
this.logger.logQuery(sql, params);
this.lastExecResult = isArray(res) ? res : [res];
} catch (error) {
handleError(error);
this.logger.failedQuery(error, sql, params);
throw error;
} finally {
if (frame) frame.end();
}
}
async getChanges(): Promise<number> {
return this.changes;
}
}
export type TransactionTypes = 'REPEATABLE READ' | 'READ UNCOMMITTED' | 'READ COMMITTED' | 'SERIALIZABLE';
export class MySQLDatabaseTransaction extends DatabaseTransaction {
connection?: MySQLConnection;
setTransaction?: TransactionTypes;
/**
* This is the default for mysql databases.
*/
repeatableRead(): this {
this.setTransaction = 'REPEATABLE READ';
return this;
}
readUncommitted(): this {
this.setTransaction = 'READ UNCOMMITTED';
return this;
}
readCommitted(): this {
this.setTransaction = 'READ COMMITTED';
return this;
}
serializable(): this {
this.setTransaction = 'SERIALIZABLE';
return this;
}
async begin() {
if (!this.connection) return;
const set = this.setTransaction ? 'SET TRANSACTION ISOLATION LEVEL ' + this.setTransaction + ';' : '';
await this.connection.run(set + 'START TRANSACTION');
}
async commit() {
if (!this.connection) return;
if (this.ended) throw new Error('Transaction ended already');
await this.connection.run('COMMIT');
this.ended = true;
this.connection.release();
}
async rollback() {
if (!this.connection) return;
if (this.ended) throw new Error('Transaction ended already');
await this.connection.run('ROLLBACK');
this.ended = true;
this.connection.release();
}
}
export class MySQLConnectionPool extends SQLConnectionPool {
constructor(protected pool: Pool) {
super();
}
async getConnection(logger?: DatabaseLogger, transaction?: MySQLDatabaseTransaction, stopwatch?: Stopwatch): Promise<MySQLConnection> {
//when a transaction object is given, it means we make the connection sticky exclusively to that transaction
//and only release the connection when the transaction is commit/rollback is executed.
if (transaction && transaction.connection) return transaction.connection;
this.activeConnections++;
const connection = new MySQLConnection(await this.pool.getConnection(), this, logger, transaction, stopwatch);
if (transaction) {
transaction.connection = connection;
try {
await transaction.begin();
} catch (error) {
transaction.ended = true;
connection.release();
throw new Error('Could not start transaction: ' + error);
}
}
return connection;
}
release(connection: MySQLConnection) {
//connections attached to a transaction are not automatically released.
//only with commit/rollback actions
if (connection.transaction && !connection.transaction.ended) return;
connection.connection.release();
super.release(connection);
}
}
export class MySQLPersistence extends SQLPersistence {
constructor(protected platform: DefaultPlatform, public connectionPool: MySQLConnectionPool, session: DatabaseSession<any>) {
super(platform, connectionPool, session);
}
async batchUpdate<T extends Entity>(classSchema: ClassSchema<T>, changeSets: DatabasePersistenceChangeSet<T>[]): Promise<void> {
const scopeSerializer = this.platform.serializer.for(classSchema);
const tableName = this.platform.getTableIdentifier(classSchema);
const pkName = classSchema.getPrimaryField().name;
const pkField = this.platform.quoteIdentifier(pkName);
const values: { [name: string]: any[] } = {};
const setNames: string[] = [];
const aggregateSelects: { [name: string]: { id: any, sql: string }[] } = {};
const requiredFields: { [name: string]: 1 } = {};
const assignReturning: { [name: string]: { item: any, names: string[] } } = {};
const setReturning: { [name: string]: 1 } = {};
for (const changeSet of changeSets) {
const where: string[] = [];
const pk = scopeSerializer.partialSerialize(changeSet.primaryKey);
for (const i in pk) {
if (!pk.hasOwnProperty(i)) continue;
where.push(`${this.platform.quoteIdentifier(i)} = ${this.platform.quoteValue(pk[i])}`);
requiredFields[i] = 1;
}
if (!values[pkName]) values[pkName] = [];
values[pkName].push(this.platform.quoteValue(changeSet.primaryKey[pkName]));
const fieldAddedToValues: { [name: string]: 1 } = {};
const id = changeSet.primaryKey[pkName];
if (changeSet.changes.$set) {
const value = scopeSerializer.partialSerialize(changeSet.changes.$set);
for (const i in value) {
if (!value.hasOwnProperty(i)) continue;
if (!values[i]) {
values[i] = [];
setNames.push(`${tableName}.${this.platform.quoteIdentifier(i)} = _b.${this.platform.quoteIdentifier(i)}`);
}
requiredFields[i] = 1;
fieldAddedToValues[i] = 1;
values[i].push(this.platform.quoteValue(value[i]));
}
}
if (changeSet.changes.$inc) {
for (const i in changeSet.changes.$inc) {
if (!changeSet.changes.$inc.hasOwnProperty(i)) continue;
const value = changeSet.changes.$inc[i];
if (!aggregateSelects[i]) aggregateSelects[i] = [];
if (!values[i]) {
values[i] = [];
setNames.push(`${tableName}.${this.platform.quoteIdentifier(i)} = _b.${this.platform.quoteIdentifier(i)}`);
}
if (!assignReturning[id]) {
assignReturning[id] = { item: changeSet.item, names: [] };
}
assignReturning[id].names.push(i);
setReturning[i] = 1;
aggregateSelects[i].push({
id: changeSet.primaryKey[pkName],
sql: `_origin.${this.platform.quoteIdentifier(i)} + ${this.platform.quoteValue(value)}`
});
requiredFields[i] = 1;
if (!fieldAddedToValues[i]) {
fieldAddedToValues[i] = 1;
values[i].push(this.platform.quoteValue(null));
}
}
}
}
const selects: string[] = [];
const valuesValues: string[] = [];
const valuesNames: string[] = [];
for (const i in values) {
valuesNames.push(i);
}
for (let i = 0; i < values[pkName].length; i++) {
valuesValues.push('ROW(' + valuesNames.map(name => values[name][i]).join(',') + ')');
}
for (const i in requiredFields) {
if (aggregateSelects[i]) {
const select: string[] = [];
select.push('CASE');
for (const item of aggregateSelects[i]) {
select.push(`WHEN _.${pkField} = ${item.id} THEN ${item.sql}`);
}
select.push(`ELSE _.${this.platform.quoteIdentifier(i)} END as ${this.platform.quoteIdentifier(i)}`);
selects.push(select.join(' '));
} else {
selects.push('_.' + i);
}
}
let setVars = '';
let endSelect = '';
if (!empty(setReturning)) {
const vars: string[] = [];
const endSelectVars: string[] = [];
vars.push(`@_pk := JSON_ARRAYAGG(${pkField})`);
endSelectVars.push('@_pk');
for (const i in setReturning) {
endSelectVars.push(`@_f_${i}`);
vars.push(`@_f_${i} := JSON_ARRAYAGG(${this.platform.quoteIdentifier(i)})`);
}
setVars = `,
(SELECT ${vars.join(', ')} FROM _tmp GROUP BY '0') as _
`;
endSelect = `SELECT ${endSelectVars.join(', ')};`;
}
const sql = `
WITH _tmp(${valuesNames.join(', ')}) AS (
SELECT ${selects.join(', ')} FROM
(VALUES ${valuesValues.join(', ')}) as _(${valuesNames.join(', ')})
INNER JOIN ${tableName} as _origin ON (_origin.${pkField} = _.${pkField})
)
UPDATE
${tableName}, _tmp as _b ${setVars}
SET ${setNames.join(', ')}
WHERE ${tableName}.${pkField} = _b.${pkField};
${endSelect}
`;
const connection = await this.getConnection(); //will automatically be released in SQLPersistence
const result = await connection.execAndReturnAll(sql);
if (!empty(setReturning)) {
const returning = result[1][0];
const ids = JSON.parse(returning['@_pk']) as (number | string)[];
const parsedReturning: { [name: string]: any[] } = {};
for (const i in setReturning) {
parsedReturning[i] = JSON.parse(returning['@_f_' + i]) as any[];
}
for (let i = 0; i < ids.length; i++) {
const id = ids[i];
const r = assignReturning[id];
if (!r) continue;
for (const name of r.names) {
r.item[name] = parsedReturning[name][i];
}
}
}
}
protected async populateAutoIncrementFields<T>(classSchema: ClassSchema<T>, items: T[]) {
const autoIncrement = classSchema.getAutoIncrementField();
if (!autoIncrement) return;
const connection = await this.getConnection(); //will automatically be released in SQLPersistence
if (!connection.lastExecResult || !connection.lastExecResult.length) throw new Error('No lastBatchResult found');
//MySQL returns the _first_ auto-incremented value for a batch insert.
//It's guaranteed to increment always by one (expect if the user provides a manual auto-increment value in between, which should be forbidden).
//So since we know how many items were inserted, we can simply calculate for each item the auto-incremented value.
const result = connection.lastExecResult[0];
let start = result.insertId;
for (const item of items) {
item[autoIncrement.name] = start++;
}
}
}
export class MySQLQueryResolver<T extends Entity> extends SQLQueryResolver<T> {
async delete(model: SQLQueryModel<T>, deleteResult: DeleteResult<T>): Promise<void> {
const primaryKey = this.classSchema.getPrimaryField();
const pkField = this.platform.quoteIdentifier(primaryKey.name);
const primaryKeyConverted = getPropertyXtoClassFunction(primaryKey, this.platform.serializer);
const sqlBuilder = new SqlBuilder(this.platform);
const select = sqlBuilder.select(this.classSchema, model, { select: [pkField] });
const tableName = this.platform.getTableIdentifier(this.classSchema);
const connection = await this.connectionPool.getConnection(this.session.logger, this.session.assignedTransaction, this.session.stopwatch);
try {
const sql = `
WITH _ AS (${select.sql})
DELETE ${tableName}
FROM ${tableName} INNER JOIN _ INNER JOIN (SELECT @_pk := JSON_ARRAYAGG(${pkField}) FROM _ GROUP BY '0') as _pk
WHERE ${tableName}.${pkField} = _.${pkField};
SELECT @_pk
`;
const rows = await connection.execAndReturnAll(sql, select.params);
const returning = rows[1];
const pk = returning[0]['@_pk'];
if (pk) deleteResult.primaryKeys = JSON.parse(pk).map(primaryKeyConverted);
deleteResult.modified = deleteResult.primaryKeys.length;
} finally {
connection.release();
}
}
async patch(model: SQLQueryModel<T>, changes: Changes<T>, patchResult: PatchResult<T>): Promise<void> {
const select: string[] = [];
const selectParams: any[] = [];
const tableName = this.platform.getTableIdentifier(this.classSchema);
const primaryKey = this.classSchema.getPrimaryField();
const primaryKeyConverted = getPropertyXtoClassFunction(primaryKey, this.platform.serializer);
const fieldsSet: { [name: string]: 1 } = {};
const aggregateFields: { [name: string]: { converted: (v: any) => any } } = {};
const scopeSerializer = this.platform.serializer.for(this.classSchema);
const $set = changes.$set ? scopeSerializer.partialSerialize(changes.$set) : undefined;
if ($set) for (const i in $set) {
if (!$set.hasOwnProperty(i)) continue;
fieldsSet[i] = 1;
select.push(`? as ${this.platform.quoteIdentifier(i)}`);
selectParams.push($set[i]);
}
if (changes.$unset) for (const i in changes.$unset) {
if (!changes.$unset.hasOwnProperty(i)) continue;
fieldsSet[i] = 1;
select.push(`NULL as ${this.platform.quoteIdentifier(i)}`);
}
for (const i of model.returning) {
aggregateFields[i] = { converted: getPropertyXtoClassFunction(resolvePropertySchema(this.classSchema, i), this.platform.serializer) };
select.push(`(${this.platform.quoteIdentifier(i)} ) as ${this.platform.quoteIdentifier(i)}`);
}
if (changes.$inc) for (const i in changes.$inc) {
if (!changes.$inc.hasOwnProperty(i)) continue;
fieldsSet[i] = 1;
aggregateFields[i] = { converted: getPropertyXtoClassFunction(resolvePropertySchema(this.classSchema, i), this.platform.serializer) };
select.push(`(${this.platform.quoteIdentifier(i)} + ${this.platform.quoteValue(changes.$inc[i])}) as ${this.platform.quoteIdentifier(i)}`);
}
const set: string[] = [];
for (const i in fieldsSet) {
set.push(`_target.${this.platform.quoteIdentifier(i)} = b.${this.platform.quoteIdentifier(i)}`);
}
const extractSelect: string[] = [];
const selectVars: string[] = [];
let bPrimaryKey = primaryKey.name;
//we need a different name because primaryKeys could be updated as well
if (fieldsSet[primaryKey.name]) {
select.unshift(this.platform.quoteIdentifier(primaryKey.name) + ' as __' + primaryKey.name);
bPrimaryKey = '__' + primaryKey.name;
} else {
select.unshift(this.platform.quoteIdentifier(primaryKey.name));
}
extractSelect.push(`@_pk := JSON_ARRAYAGG(${this.platform.quoteIdentifier(primaryKey.name)})`);
selectVars.push(`@_pk`);
if (!empty(aggregateFields)) {
for (const i in aggregateFields) {
extractSelect.push(`@_f_${i} := JSON_ARRAYAGG(${this.platform.quoteIdentifier(i)})`);
selectVars.push(`@_f_${i}`);
}
}
const extractVarsSQL = `,
(SELECT ${extractSelect.join(', ')} FROM _tmp GROUP BY '0') as _
`;
const selectVarsSQL = `SELECT ${selectVars.join(', ')};`;
const sqlBuilder = new SqlBuilder(this.platform, selectParams);
const selectSQL = sqlBuilder.select(this.classSchema, model, { select });
const params = selectSQL.params;
const sql = `
WITH _tmp AS (${selectSQL.sql})
UPDATE
${tableName} as _target, _tmp as b ${extractVarsSQL}
SET
${set.join(', ')}
WHERE _target.${this.platform.quoteIdentifier(primaryKey.name)} = b.${this.platform.quoteIdentifier(bPrimaryKey)};
${selectVarsSQL}
`;
const connection = await this.connectionPool.getConnection(this.session.logger, this.session.assignedTransaction, this.session.stopwatch);
try {
const result = await connection.execAndReturnAll(sql, params);
const packet = result[0];
patchResult.modified = packet.affectedRows;
const returning = result[1][0];
patchResult.primaryKeys = (JSON.parse(returning['@_pk']) as any[]).map(primaryKeyConverted as any);
for (const i in aggregateFields) {
patchResult.returning[i] = (JSON.parse(returning['@_f_' + i]) as any[]).map(aggregateFields[i].converted);
}
} finally {
connection.release();
}
}
}
export class MySQLDatabaseQuery<T> extends SQLDatabaseQuery<T> {
}
export class MySQLDatabaseQueryFactory extends SQLDatabaseQueryFactory {
createQuery<T extends Entity>(classType: ClassType<T> | ClassSchema<T>): MySQLDatabaseQuery<T> {
return new MySQLDatabaseQuery(getClassSchema(classType), this.databaseSession,
new MySQLQueryResolver(this.connectionPool, this.platform, getClassSchema(classType), this.databaseSession)
);
}
}
export class MySQLDatabaseAdapter extends SQLDatabaseAdapter {
protected pool = createPool({ multipleStatements: true, maxAllowedPacket: 16_000_000, ...this.options });
public connectionPool = new MySQLConnectionPool(this.pool);
public platform = new MySQLPlatform(this.pool);
constructor(
protected options: PoolConfig = {}
) {
super();
}
getName(): string {
return 'mysql';
}
getSchemaName(): string {
//todo extract schema name from connection options. This acts as default when a table has no schemaName defined.
return '';
}
createPersistence(session: DatabaseSession<any>): SQLPersistence {
return new MySQLPersistence(this.platform, this.connectionPool, session);
}
createTransaction(session: DatabaseSession<this>): MySQLDatabaseTransaction {
return new MySQLDatabaseTransaction();
}
queryFactory(databaseSession: DatabaseSession<any>): MySQLDatabaseQueryFactory {
return new MySQLDatabaseQueryFactory(this.connectionPool, this.platform, databaseSession);
}
disconnect(force?: boolean): void {
this.pool.end().catch(console.error);
}
} | the_stack |
import { Rule, Project } from '../../../support/types';
// these tests are best read sequentially, as they share state
describe('projects API', () => {
const cypressPrefix = 'test-projects-api';
const projectWithOrgRule: Project = {
id: `${cypressPrefix}-project1-${Cypress.moment().format('MMDDYYhhmm')}`,
name: 'Test Avengers Project',
skip_policies: true
};
const projectWithServerRule: Project = {
id: `${cypressPrefix}-project2-${Cypress.moment().format('MMDDYYhhmm')}`,
name: 'Test X-men Project',
skip_policies: true
};
const orgRule: Rule = {
id: 'org-rule-1',
name: 'first rule of avengers project',
type: 'NODE',
project_id: projectWithOrgRule.id,
conditions: [
{
attribute: 'CHEF_ORGANIZATION',
operator: 'EQUALS',
values: ['avengers']
}
]
};
const serverRule: Rule = {
id: 'server-rule-1',
name: 'first rule of xmen project',
type: 'NODE',
project_id: projectWithServerRule.id,
conditions: [
{
attribute: 'CHEF_SERVER',
operator: 'EQUALS',
values: ['xmen.co']
}
]
};
before(() => {
// Cypress recommends state cleanup in the before block to ensure
// it gets run every time:
// tslint:disable-next-line:max-line-length
// https://docs.cypress.io/guides/references/best-practices.html#Using-after-or-afterEach-hooks
cy.cleanupIAMObjectsByIDPrefixes(cypressPrefix, ['projects']);
});
after(() => {
cy.cleanupIAMObjectsByIDPrefixes(cypressPrefix, ['projects']);
});
describe('applying project rules', () => {
// testing values
const noRulesStr = 'NO_RULES';
const editsPendingStr = 'EDITS_PENDING';
const rulesAppliedStr = 'RULES_APPLIED';
// corresponds to the number of nodes ingested in this test via fixtures.
const numberOfNodesAdded = 4;
before(() => {
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'POST',
url: 'api/v0/ingest/events/chef/node-multiple-deletes',
body: {
node_ids: [
'f6a5c33f-bef5-433b-815e-a8f6e69e6b1b',
'82760210-4686-497e-b039-efca78dee64b',
'9c139ad0-89a5-44bc-942c-d7f248b155ba',
'6453a764-2415-4934-8cee-2a008834a74a'
]
},
failOnStatusCode: false
});
for (const project of [projectWithOrgRule, projectWithServerRule]) {
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'POST',
url: '/apis/iam/v2/projects',
body: project
});
}
let totalNodes = 0;
cy.request({
headers: {
'api-token': Cypress.env('ADMIN_TOKEN'),
projects: '(unassigned)'
},
method: 'GET',
url: '/api/v0/cfgmgmt/nodes?pagination.size=10'
}).then((response) => {
totalNodes = response.body.length;
});
cy.fixture('converge/avengers1.json').then(node1 => {
cy.fixture('converge/avengers2.json').then(node2 => {
cy.fixture('converge/xmen1.json').then(node3 => {
cy.fixture('converge/xmen2.json').then(node4 => {
for (const node of [node1, node2, node3, node4]) {
cy.sendToDataCollector(node);
}
});
});
});
});
const maxRetries = 200;
waitForUnassignedNodes(totalNodes + numberOfNodesAdded, maxRetries);
cy.request({
headers: {
'api-token': Cypress.env('ADMIN_TOKEN'),
projects: projectWithOrgRule.id
},
method: 'GET',
url: '/api/v0/cfgmgmt/nodes?pagination.size=10'
}).then((response) => {
expect(response.body).to.have.length(0);
});
cy.request({
headers: {
'api-token': Cypress.env('ADMIN_TOKEN'),
projects: projectWithServerRule.id
},
method: 'GET',
url: '/api/v0/cfgmgmt/nodes?pagination.size=10'
}).then((response) => {
expect(response.body).to.have.length(0);
});
});
it('new rules get applied to nodes', () => {
// initially no rules
for (const project of [projectWithOrgRule, projectWithServerRule]) {
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'GET',
url: `/apis/iam/v2/projects/${project.id}/rules`
}).then((response) => {
expect(response.body.rules).to.have.length(0);
});
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'GET',
url: `/apis/iam/v2/projects/${project.id}`
}).then((response) => {
expect(response.body.project.status).to.equal(noRulesStr);
});
}
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'GET',
url: '/apis/iam/v2/projects'
}).then((response) => {
const projects: Project[] = response.body.projects;
projects.filter(({ id, status }) => {
return id === projectWithOrgRule.id || id === projectWithServerRule.id;
})
.forEach(({ status }) => expect(status).to.equal(noRulesStr));
});
for (const rule of [orgRule, serverRule]) {
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'POST',
url: `/apis/iam/v2/projects/${rule.project_id}/rules`,
body: rule
});
}
// confirm rules are staged
for (const project of [projectWithOrgRule, projectWithServerRule]) {
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'GET',
url: `/apis/iam/v2/projects/${project.id}/rules`
}).then((response) => {
expect(response.body.rules).to.have.length(1);
for (const rule of response.body.rules) {
expect(rule).to.have.property('status', 'STAGED');
}
});
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'GET',
url: `/apis/iam/v2/projects/${project.id}`
}).then((response) => {
expect(response.body.project.status).to.equal(editsPendingStr);
});
}
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'GET',
url: '/apis/iam/v2/projects'
}).then((response) => {
const projects: Project[] = response.body.projects;
projects.filter(({ id, status }) => {
return id === projectWithOrgRule.id || id === projectWithServerRule.id;
})
.forEach(({ status }) => expect(status).to.equal(editsPendingStr));
});
cy.applyRulesAndWait();
// confirm rules are applied
for (const project of [projectWithOrgRule, projectWithServerRule]) {
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'GET',
url: `/apis/iam/v2/projects/${project.id}/rules`
}).then((response) => {
expect(response.body.rules).to.have.length(1);
for (const rule of response.body.rules) {
expect(rule).to.have.property('status', 'APPLIED');
}
});
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'GET',
url: `/apis/iam/v2/projects/${project.id}`
}).then((response) => {
expect(response.body.project.status).to.equal(rulesAppliedStr);
});
}
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'GET',
url: '/apis/iam/v2/projects'
}).then((response) => {
const projects: Project[] = response.body.projects;
projects.filter(({ id, status }) => {
return id === projectWithOrgRule.id || id === projectWithServerRule.id;
})
.forEach(({ status }) => expect(status).to.equal(rulesAppliedStr));
});
// confirm nodes are assigned to projects correctly
cy.request({
headers: {
'api-token': Cypress.env('ADMIN_TOKEN'),
projects: projectWithOrgRule.id
},
method: 'GET',
url: '/api/v0/cfgmgmt/nodes?pagination.size=10'
}).then((response) => {
expect(response.body).to.have.length(2);
});
cy.request({
headers: {
'api-token': Cypress.env('ADMIN_TOKEN'),
projects: projectWithServerRule.id
},
method: 'GET',
url: '/api/v0/cfgmgmt/nodes?pagination.size=10'
}).then((response) => {
expect(response.body).to.have.length(2);
});
});
it('rules with updated conditions get applied to nodes', () => {
// change avengers rule to include both organizations
const updatedorgRule = orgRule;
updatedorgRule.conditions = [
{
attribute: 'CHEF_ORGANIZATION',
operator: 'MEMBER_OF',
values: ['avengers', 'xmen']
}
];
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'GET',
url: `/apis/iam/v2/projects/${projectWithOrgRule.id}`
}).then((response) => {
expect(response.body.project.status).to.equal(rulesAppliedStr);
});
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'GET',
url: '/apis/iam/v2/projects'
}).then((response) => {
const projects: Project[] = response.body.projects;
projects.filter(({ id, status }) => id === projectWithOrgRule.id)
.forEach(({ status }) => expect(status).to.equal(rulesAppliedStr));
});
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'PUT',
url: `/apis/iam/v2/projects/${orgRule.project_id}/rules/${orgRule.id}`,
body: updatedorgRule
});
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'GET',
url: `/apis/iam/v2/projects/${projectWithOrgRule.id}`
}).then((response) => {
expect(response.body.project.status).to.equal(editsPendingStr);
});
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'GET',
url: '/apis/iam/v2/projects'
}).then((response) => {
const projects: Project[] = response.body.projects;
projects.filter(({ id, status }) => id === projectWithOrgRule.id)
.forEach(({ status }) => expect(status).to.equal(editsPendingStr));
});
cy.applyRulesAndWait();
cy.request({
headers: {
'api-token': Cypress.env('ADMIN_TOKEN'),
projects: projectWithOrgRule.id
},
method: 'GET',
url: '/api/v0/cfgmgmt/nodes?pagination.size=10'
}).then((response) => {
expect(response.body).to.have.length(4);
});
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'GET',
url: `/apis/iam/v2/projects/${projectWithOrgRule.id}`
}).then((response) => {
expect(response.body.project.status).to.equal(rulesAppliedStr);
});
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'GET',
url: '/apis/iam/v2/projects'
}).then((response) => {
const projects: Project[] = response.body.projects;
projects.filter(({ id, status }) => id === projectWithOrgRule.id)
.forEach(({ status }) => expect(status).to.equal(rulesAppliedStr));
});
});
it('deleted rules get applied to nodes', () => {
// verify project has applied rules
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'GET',
url: `/apis/iam/v2/projects/${projectWithOrgRule.id}`
}).then((response) => {
expect(response.body.project.status).to.equal(rulesAppliedStr);
});
// delete the project's rule
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'DELETE',
url: `/apis/iam/v2/projects/${orgRule.project_id}/rules/${orgRule.id}`
});
// verify project now has edits pending
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'GET',
url: `/apis/iam/v2/projects/${projectWithOrgRule.id}`
}).then((response) => {
expect(response.body.project.status).to.equal(editsPendingStr);
});
cy.applyRulesAndWait();
// verify the project no longer has any rules
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'GET',
url: `/apis/iam/v2/projects/${projectWithOrgRule.id}`
}).then((response) => {
expect(response.body.project.status).to.equal(noRulesStr);
});
// verify the project is no longer applied to node data
cy.request({
headers: {
'api-token': Cypress.env('ADMIN_TOKEN'),
projects: projectWithOrgRule.id
},
method: 'GET',
url: '/api/v0/cfgmgmt/nodes?pagination.size=10'
}).then((response) => {
expect(response.body).to.have.length(0);
});
cy.request({
headers: {
'api-token': Cypress.env('ADMIN_TOKEN'),
projects: '(unassigned)'
},
method: 'GET',
url: '/api/v0/cfgmgmt/nodes?pagination.size=10'
}).then((response) => {
expect(response.body).to.have.length(2);
});
});
});
describe('project graveyarding and deletion', () => {
it('gives a 404 when the project does not exist', () => {
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
url: '/apis/iam/v2/projects/not_found',
failOnStatusCode: false
}).then((response) => {
expect(response.status).to.equal(404);
});
});
it('fails to delete project with staged or applied rules', () => {
// Try to delete a project with an applied rule
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'DELETE',
url: `/apis/iam/v2/projects/${projectWithServerRule.id}`,
failOnStatusCode: false
}).then((deleteResp) => {
expect(deleteResp.status,
'Fails to delete a project with an applied rule').to.equal(400);
});
// Add a new staged rule to a project with existing rules
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'POST',
url: `/apis/iam/v2/projects/${projectWithServerRule.id}/rules`,
body: {
id: 'xmen-rule-2',
name: 'second rule of xmen project',
type: 'NODE',
project_id: projectWithServerRule.id,
conditions: [
{
attribute: 'CHEF_ORGANIZATION',
operator: 'EQUALS',
values: ['xmen']
}
]
}
});
// Try to delete the project with a staged rule
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'DELETE',
url: `/apis/iam/v2/projects/${projectWithServerRule.id}`,
failOnStatusCode: false
}).then((deleteResp) => {
expect(deleteResp.status,
'Fails to delete a project with a staged rule').to.equal(400);
});
// Delete an applied rule
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'DELETE',
url: `/apis/iam/v2/projects/${projectWithServerRule.id}/rules/${serverRule.id}`
});
// Try to delete a project with a deleted rule that has not been applied
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'DELETE',
url: `/apis/iam/v2/projects/${projectWithServerRule.id}`,
failOnStatusCode: false
}).then((deleteResp) => {
expect(deleteResp.status,
'Fails to delete a project with a deleted rule that has not been applied')
.to.equal(400);
});
});
it('successfully deletes a project with no rules', () => {
// Try deleting a project with no rules
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'DELETE',
url: `/apis/iam/v2/projects/${projectWithOrgRule.id}`
}).then((deleteResp) => {
expect(deleteResp.status).to.equal(200);
});
// Ensure the project is removed
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
method: 'GET',
url: '/apis/iam/v2/projects'
}).then((resp: Cypress.ObjectLike) => {
expect(
responseContainsProject(resp.body.projects, projectWithOrgRule.id)).to.equal(false);
});
waitUntilProjectNotInGraveyard(projectWithOrgRule.id, 100);
});
});
});
function waitForUnassignedNodes(totalNodes: number, maxRetries: number) {
cy
.request({
headers: {
projects: '(unassigned)',
'api-token': Cypress.env('ADMIN_TOKEN')
},
method: 'GET',
url: '/api/v0/cfgmgmt/nodes?pagination.size=10'
})
.then((resp: Cypress.ObjectLike) => {
// to avoid getting stuck in an infinite loop
if (maxRetries === 0) {
return;
}
if (resp.body.length === totalNodes + 4) {
return;
}
waitForUnassignedNodes(totalNodes, maxRetries - 1);
});
}
function waitUntilProjectNotInGraveyard(projectID: string, attempts: number): void {
if (attempts === -1) {
throw new Error('project-delete never finished');
}
cy.request({
headers: { 'api-token': Cypress.env('ADMIN_TOKEN') },
url: '/apis/iam/v2/projects',
method: 'POST',
failOnStatusCode: false,
body: {
id: projectID,
name: 'can we create yet',
skip_policies: true
}
}).then((response) => {
if (response.status === 409) {
return;
} else {
cy.log(`${attempts} attempts remaining: waiting for project with ` +
`id ${projectID} to be removed from graveyard`);
cy.wait(1000);
waitUntilProjectNotInGraveyard(projectID, --attempts);
}
});
}
function responseContainsProject(projectsResponse: any, projectId: string): boolean {
return projectsResponse &&
projectsResponse.length > 0 &&
projectsResponse.some((p: any) => p.id === projectId);
} | the_stack |
import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, HostBinding, HostListener, Input, OnDestroy, OnInit, Output, QueryList, Renderer2, ViewChild, ViewChildren, ViewEncapsulation } from '@angular/core';
import { animate, AnimationBuilder, AnimationPlayer, style } from '@angular/animations';
import { NavigationEnd, Router } from '@angular/router';
import { ScrollStrategy, ScrollStrategyOptions } from '@angular/cdk/overlay';
import { BehaviorSubject, merge, Subject, Subscription } from 'rxjs';
import { delay, filter, takeUntil } from 'rxjs/operators';
import { TreoAnimations } from '@treo/animations';
import { TreoVerticalNavigationAppearance, TreoNavigationItem, TreoVerticalNavigationMode, TreoVerticalNavigationPosition } from '@treo/components/navigation/navigation.types';
import { TreoNavigationService } from '@treo/components/navigation/navigation.service';
import { TreoScrollbarDirective } from '@treo/directives/scrollbar/scrollbar.directive';
@Component({
selector : 'treo-vertical-navigation',
templateUrl : './vertical.component.html',
styleUrls : ['./vertical.component.scss'],
animations : TreoAnimations,
encapsulation : ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
exportAs : 'treoVerticalNavigation'
})
export class TreoVerticalNavigationComponent implements OnInit, AfterViewInit, OnDestroy
{
activeAsideItemId: null | string;
onCollapsableItemCollapsed: BehaviorSubject<TreoNavigationItem | null>;
onCollapsableItemExpanded: BehaviorSubject<TreoNavigationItem | null>;
onRefreshed: BehaviorSubject<boolean | null>;
// Auto collapse
@Input()
autoCollapse: boolean;
// Name
@Input()
name: string;
// On appearance changed
@Output()
readonly appearanceChanged: EventEmitter<TreoVerticalNavigationAppearance>;
// On mode changed
@Output()
readonly modeChanged: EventEmitter<TreoVerticalNavigationMode>;
// On opened changed
@Output()
readonly openedChanged: EventEmitter<boolean | ''>;
// On position changed
@Output()
readonly positionChanged: EventEmitter<TreoVerticalNavigationPosition>;
// Private
private _appearance: TreoVerticalNavigationAppearance;
private _asideOverlay: HTMLElement | null;
private _treoScrollbarDirectives: QueryList<TreoScrollbarDirective>;
private _treoScrollbarDirectivesSubscription: Subscription;
private _handleAsideOverlayClick: any;
private _handleOverlayClick: any;
private _inner: boolean;
private _mode: TreoVerticalNavigationMode;
private _navigation: TreoNavigationItem[];
private _opened: boolean | '';
private _overlay: HTMLElement | null;
private _player: AnimationPlayer;
private _position: TreoVerticalNavigationPosition;
private _scrollStrategy: ScrollStrategy;
private _transparentOverlay: boolean | '';
private _unsubscribeAll: Subject<any>;
@HostBinding('class.treo-vertical-navigation-animations-enabled')
private _animationsEnabled: boolean;
@ViewChild('navigationContent')
private _navigationContentEl: ElementRef;
/**
* Constructor
*
* @param {AnimationBuilder} _animationBuilder
* @param {TreoNavigationService} _treoNavigationService
* @param {ChangeDetectorRef} _changeDetectorRef
* @param {ElementRef} _elementRef
* @param {Renderer2} _renderer2
* @param {Router} _router
* @param {ScrollStrategyOptions} _scrollStrategyOptions
*/
constructor(
private _animationBuilder: AnimationBuilder,
private _treoNavigationService: TreoNavigationService,
private _changeDetectorRef: ChangeDetectorRef,
private _elementRef: ElementRef,
private _renderer2: Renderer2,
private _router: Router,
private _scrollStrategyOptions: ScrollStrategyOptions
)
{
// Set the private defaults
this._animationsEnabled = false;
this._asideOverlay = null;
this._handleAsideOverlayClick = () => {
this.closeAside();
};
this._handleOverlayClick = () => {
this.close();
};
this._overlay = null;
this._scrollStrategy = this._scrollStrategyOptions.block();
this._unsubscribeAll = new Subject();
// Set the defaults
this.appearanceChanged = new EventEmitter<TreoVerticalNavigationAppearance>();
this.modeChanged = new EventEmitter<TreoVerticalNavigationMode>();
this.openedChanged = new EventEmitter<boolean | ''>();
this.positionChanged = new EventEmitter<TreoVerticalNavigationPosition>();
this.onCollapsableItemCollapsed = new BehaviorSubject(null);
this.onCollapsableItemExpanded = new BehaviorSubject(null);
this.onRefreshed = new BehaviorSubject(null);
this.activeAsideItemId = null;
this.appearance = 'classic';
this.autoCollapse = true;
this.inner = false;
this.mode = 'side';
this.opened = false;
this.position = 'left';
this.transparentOverlay = false;
}
// -----------------------------------------------------------------------------------------------------
// @ Accessors
// -----------------------------------------------------------------------------------------------------
/**
* Setter & getter for appearance
*
* @param value
*/
@Input()
set appearance(value: TreoVerticalNavigationAppearance)
{
// If the value is the same, return...
if ( this._appearance === value )
{
return;
}
let appearanceClassName;
// Remove the previous appearance class
appearanceClassName = 'treo-vertical-navigation-appearance-' + this.appearance;
this._renderer2.removeClass(this._elementRef.nativeElement, appearanceClassName);
// Store the appearance
this._appearance = value;
// Add the new appearance class
appearanceClassName = 'treo-vertical-navigation-appearance-' + this.appearance;
this._renderer2.addClass(this._elementRef.nativeElement, appearanceClassName);
// Execute the observable
this.appearanceChanged.next(this.appearance);
}
get appearance(): TreoVerticalNavigationAppearance
{
return this._appearance;
}
/**
* Setter for treoScrollbarDirectives
*/
@ViewChildren(TreoScrollbarDirective)
set treoScrollbarDirectives(treoScrollbarDirectives: QueryList<TreoScrollbarDirective>)
{
// Store the directives
this._treoScrollbarDirectives = treoScrollbarDirectives;
// Return, if there are no directives
if ( treoScrollbarDirectives.length === 0 )
{
return;
}
// Unsubscribe the previous subscriptions
if ( this._treoScrollbarDirectivesSubscription )
{
this._treoScrollbarDirectivesSubscription.unsubscribe();
}
// Update the scrollbars on collapsable items' collapse/expand
this._treoScrollbarDirectivesSubscription =
merge(
this.onCollapsableItemCollapsed,
this.onCollapsableItemExpanded
)
.pipe(
takeUntil(this._unsubscribeAll),
delay(250)
)
.subscribe(() => {
// Loop through the scrollbars and update them
treoScrollbarDirectives.forEach((treoScrollbarDirective) => {
treoScrollbarDirective.update();
});
});
}
/**
* Setter & getter for data
*/
@Input()
set navigation(value: TreoNavigationItem[])
{
// Store the data
this._navigation = value;
// Mark for check
this._changeDetectorRef.markForCheck();
}
get navigation(): TreoNavigationItem[]
{
return this._navigation;
}
/**
* Setter & getter for inner
*
* @param value
*/
@Input()
set inner(value: boolean)
{
// If the value is the same, return...
if ( this._inner === value )
{
return;
}
// Set the naked value
this._inner = value;
// Update the class
if ( this.inner )
{
this._renderer2.addClass(this._elementRef.nativeElement, 'treo-vertical-navigation-inner');
}
else
{
this._renderer2.removeClass(this._elementRef.nativeElement, 'treo-vertical-navigation-inner');
}
}
get inner(): boolean
{
return this._inner;
}
/**
* Setter & getter for mode
*
* @param value
*/
@Input()
set mode(value: TreoVerticalNavigationMode)
{
// If the value is the same, return...
if ( this._mode === value )
{
return;
}
// Disable the animations
this._disableAnimations();
// If the mode changes: 'over -> side'
if ( this.mode === 'over' && value === 'side' )
{
// Hide the overlay
this._hideOverlay();
}
// If the mode changes: 'side -> over'
if ( this.mode === 'side' && value === 'over' )
{
// Close the aside
this.closeAside();
// If the navigation is opened
if ( this.opened )
{
// Show the overlay
this._showOverlay();
}
}
let modeClassName;
// Remove the previous mode class
modeClassName = 'treo-vertical-navigation-mode-' + this.mode;
this._renderer2.removeClass(this._elementRef.nativeElement, modeClassName);
// Store the mode
this._mode = value;
// Add the new mode class
modeClassName = 'treo-vertical-navigation-mode-' + this.mode;
this._renderer2.addClass(this._elementRef.nativeElement, modeClassName);
// Execute the observable
this.modeChanged.next(this.mode);
// Enable the animations after a delay
// The delay must be bigger than the current transition-duration
// to make sure nothing will be animated while the mode changing
setTimeout(() => {
this._enableAnimations();
}, 500);
}
get mode(): TreoVerticalNavigationMode
{
return this._mode;
}
/**
* Setter & getter for opened
*
* @param value
*/
@Input()
set opened(value: boolean | '')
{
// If the value is the same, return...
if ( this._opened === value )
{
return;
}
// If the provided value is an empty string,
// take that as a 'true'
if ( value === '' )
{
value = true;
}
// Set the opened value
this._opened = value;
// If the navigation opened, and the mode
// is 'over', show the overlay
if ( this.mode === 'over' )
{
if ( this._opened )
{
this._showOverlay();
}
else
{
this._hideOverlay();
}
}
if ( this.opened )
{
// Update styles and classes
this._renderer2.setStyle(this._elementRef.nativeElement, 'visibility', 'visible');
this._renderer2.addClass(this._elementRef.nativeElement, 'treo-vertical-navigation-opened');
}
else
{
// Update styles and classes
this._renderer2.setStyle(this._elementRef.nativeElement, 'visibility', 'hidden');
this._renderer2.removeClass(this._elementRef.nativeElement, 'treo-vertical-navigation-opened');
}
// Execute the observable
this.openedChanged.next(this.opened);
}
get opened(): boolean | ''
{
return this._opened;
}
/**
* Setter & getter for position
*
* @param value
*/
@Input()
set position(value: TreoVerticalNavigationPosition)
{
// If the value is the same, return...
if ( this._position === value )
{
return;
}
let positionClassName;
// Remove the previous position class
positionClassName = 'treo-vertical-navigation-position-' + this.position;
this._renderer2.removeClass(this._elementRef.nativeElement, positionClassName);
// Store the position
this._position = value;
// Add the new position class
positionClassName = 'treo-vertical-navigation-position-' + this.position;
this._renderer2.addClass(this._elementRef.nativeElement, positionClassName);
// Execute the observable
this.positionChanged.next(this.position);
}
get position(): TreoVerticalNavigationPosition
{
return this._position;
}
/**
* Setter & getter for transparent overlay
*
* @param value
*/
@Input()
set transparentOverlay(value: boolean | '')
{
// If the value is the same, return...
if ( this._opened === value )
{
return;
}
// If the provided value is an empty string,
// take that as a 'true' and set the opened value
if ( value === '' )
{
// Set the opened value
this._transparentOverlay = true;
}
else
{
// Set the transparent overlay value
this._transparentOverlay = value;
}
}
get transparentOverlay(): boolean | ''
{
return this._transparentOverlay;
}
// -----------------------------------------------------------------------------------------------------
// @ Lifecycle hooks
// -----------------------------------------------------------------------------------------------------
/**
* On init
*/
ngOnInit(): void
{
// Register the navigation component
this._treoNavigationService.registerComponent(this.name, this);
// Subscribe to the 'NavigationEnd' event
this._router.events
.pipe(
filter(event => event instanceof NavigationEnd),
takeUntil(this._unsubscribeAll)
)
.subscribe(() => {
if ( this.mode === 'over' && this.opened )
{
// Close the navigation
this.close();
}
});
}
/**
* After view init
*/
ngAfterViewInit(): void
{
setTimeout(() => {
// If 'navigation content' element doesn't have
// perfect scrollbar activated on it...
if ( !this._navigationContentEl.nativeElement.classList.contains('ps') )
{
// Find the active item
const activeItem = this._navigationContentEl.nativeElement.querySelector('.treo-vertical-navigation-item-active');
// If the active item exists, scroll it into view
if ( activeItem )
{
activeItem.scrollIntoView();
}
}
// Otherwise
else
{
// Go through all the scrollbar directives
this._treoScrollbarDirectives.forEach((treoScrollbarDirective) => {
// Skip if not enabled
if ( !treoScrollbarDirective.enabled )
{
return;
}
// Scroll to the active element
treoScrollbarDirective.scrollToElement('.treo-vertical-navigation-item-active', -120, true);
});
}
});
}
/**
* On destroy
*/
ngOnDestroy(): void
{
// Deregister the navigation component from the registry
this._treoNavigationService.deregisterComponent(this.name);
// Unsubscribe from all subscriptions
this._unsubscribeAll.next();
this._unsubscribeAll.complete();
}
// -----------------------------------------------------------------------------------------------------
// @ Private methods
// -----------------------------------------------------------------------------------------------------
/**
* Enable the animations
*
* @private
*/
private _enableAnimations(): void
{
// If the animations are already enabled, return...
if ( this._animationsEnabled )
{
return;
}
// Enable the animations
this._animationsEnabled = true;
}
/**
* Disable the animations
*
* @private
*/
private _disableAnimations(): void
{
// If the animations are already disabled, return...
if ( !this._animationsEnabled )
{
return;
}
// Disable the animations
this._animationsEnabled = false;
}
/**
* Show the overlay
*
* @private
*/
private _showOverlay(): void
{
// If there is already an overlay, return...
if ( this._asideOverlay )
{
return;
}
// Create the overlay element
this._overlay = this._renderer2.createElement('div');
// Add a class to the overlay element
this._overlay.classList.add('treo-vertical-navigation-overlay');
// Add a class depending on the transparentOverlay option
if ( this.transparentOverlay )
{
this._overlay.classList.add('treo-vertical-navigation-overlay-transparent');
}
// Append the overlay to the parent of the navigation
this._renderer2.appendChild(this._elementRef.nativeElement.parentElement, this._overlay);
// Enable block scroll strategy
this._scrollStrategy.enable();
// Create the enter animation and attach it to the player
this._player =
this._animationBuilder
.build([
animate('300ms cubic-bezier(0.25, 0.8, 0.25, 1)', style({opacity: 1}))
]).create(this._overlay);
// Play the animation
this._player.play();
// Add an event listener to the overlay
this._overlay.addEventListener('click', this._handleOverlayClick);
}
/**
* Hide the overlay
*
* @private
*/
private _hideOverlay(): void
{
if ( !this._overlay )
{
return;
}
// Create the leave animation and attach it to the player
this._player =
this._animationBuilder
.build([
animate('300ms cubic-bezier(0.25, 0.8, 0.25, 1)', style({opacity: 0}))
]).create(this._overlay);
// Play the animation
this._player.play();
// Once the animation is done...
this._player.onDone(() => {
// If the overlay still exists...
if ( this._overlay )
{
// Remove the event listener
this._overlay.removeEventListener('click', this._handleOverlayClick);
// Remove the overlay
this._overlay.parentNode.removeChild(this._overlay);
this._overlay = null;
}
// Disable block scroll strategy
this._scrollStrategy.disable();
});
}
/**
* Show the aside overlay
*
* @private
*/
private _showAsideOverlay(): void
{
// If there is already an overlay, return...
if ( this._asideOverlay )
{
return;
}
// Create the aside overlay element
this._asideOverlay = this._renderer2.createElement('div');
// Add a class to the aside overlay element
this._asideOverlay.classList.add('treo-vertical-navigation-aside-overlay');
// Append the aside overlay to the parent of the navigation
this._renderer2.appendChild(this._elementRef.nativeElement.parentElement, this._asideOverlay);
// Create the enter animation and attach it to the player
this._player =
this._animationBuilder
.build([
animate('300ms cubic-bezier(0.25, 0.8, 0.25, 1)', style({opacity: 1}))
]).create(this._asideOverlay);
// Play the animation
this._player.play();
// Add an event listener to the aside overlay
this._asideOverlay.addEventListener('click', this._handleAsideOverlayClick);
}
/**
* Hide the aside overlay
*
* @private
*/
private _hideAsideOverlay(): void
{
if ( !this._asideOverlay )
{
return;
}
// Create the leave animation and attach it to the player
this._player =
this._animationBuilder
.build([
animate('300ms cubic-bezier(0.25, 0.8, 0.25, 1)', style({opacity: 0}))
]).create(this._asideOverlay);
// Play the animation
this._player.play();
// Once the animation is done...
this._player.onDone(() => {
// If the aside overlay still exists...
if ( this._asideOverlay )
{
// Remove the event listener
this._asideOverlay.removeEventListener('click', this._handleAsideOverlayClick);
// Remove the aside overlay
this._asideOverlay.parentNode.removeChild(this._asideOverlay);
this._asideOverlay = null;
}
});
}
/**
* On mouseenter
*
* @private
*/
@HostListener('mouseenter')
private _onMouseenter(): void
{
// Enable the animations
this._enableAnimations();
// Add a class
this._renderer2.addClass(this._elementRef.nativeElement, 'treo-vertical-navigation-hover');
}
/**
* On mouseleave
*
* @private
*/
@HostListener('mouseleave')
private _onMouseleave(): void
{
// Enable the animations
this._enableAnimations();
// Remove the class
this._renderer2.removeClass(this._elementRef.nativeElement, 'treo-vertical-navigation-hover');
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Refresh the component to apply the changes
*/
refresh(): void
{
// Mark for check
this._changeDetectorRef.markForCheck();
// Execute the observable
this.onRefreshed.next(true);
}
/**
* Open the navigation
*/
open(): void
{
// Enable the animations
this._enableAnimations();
// Open
this.opened = true;
}
/**
* Close the navigation
*/
close(): void
{
// Enable the animations
this._enableAnimations();
// Close the aside
this.closeAside();
// Close
this.opened = false;
}
/**
* Toggle the opened status
*/
toggle(): void
{
// Toggle
if ( this.opened )
{
this.close();
}
else
{
this.open();
}
}
/**
* Open the aside
*
* @param item
*/
openAside(item: TreoNavigationItem): void
{
// Return if the item is disabled
if ( item.disabled )
{
return;
}
// Open
this.activeAsideItemId = item.id;
// Show the aside overlay
this._showAsideOverlay();
// Mark for check
this._changeDetectorRef.markForCheck();
}
/**
* Close the aside
*/
closeAside(): void
{
// Close
this.activeAsideItemId = null;
// Hide the aside overlay
this._hideAsideOverlay();
// Mark for check
this._changeDetectorRef.markForCheck();
}
/**
* Toggle the aside
*
* @param item
*/
toggleAside(item: TreoNavigationItem): void
{
// Toggle
if ( this.activeAsideItemId === item.id )
{
this.closeAside();
}
else
{
this.openAside(item);
}
}
/**
* Track by function for ngFor loops
*
* @param index
* @param item
*/
trackByFn(index: number, item: any): any
{
return item.id || index;
}
} | the_stack |
import {BaseGlShaderAssembler} from '../_Base';
// import {GlobalsTextureHandler} from '../../Assembler/Globals/Texture';
import TemplateDefault from '../../templates/particles/Default.glsl';
// import TemplatePosition from './Template/Particle/Position.glsl'
// import TemplateVelocity from './Template/Particle/Velocity.glsl'
// import TemplateAcceleration from './Template/Particle/Acceleration.glsl'
// import {ShaderConfig} from './Config/ShaderConfig';
// import {VariableConfig} from './Config/VariableConfig';
// import {ShaderName, LineType} from '../../../../../Engine/Node/Gl/Assembler/Util/CodeBuilder';
import {AttributeGlNode} from '../../../Attribute';
import {TextureAllocationsController} from '../../utils/TextureAllocationsController';
import {ThreeToGl} from '../../../../../../core/ThreeToGl';
import {BaseGlNodeType} from '../../../_Base';
import {GlobalsGlNode} from '../../../Globals';
import {TypedNodeTraverser} from '../../../../utils/shaders/NodeTraverser';
import {ShaderName} from '../../../../utils/shaders/ShaderName';
import {OutputGlNode} from '../../../Output';
import {GlConnectionPointType, GlConnectionPoint} from '../../../../utils/io/connections/Gl';
import {UniformGLDefinition} from '../../../utils/GLDefinition';
import {GlobalsTextureHandler} from '../../globals/Texture';
import {ShadersCollectionController} from '../../utils/ShadersCollectionController';
import {NodeContext} from '../../../../../poly/NodeContext';
export class ShaderAssemblerParticles extends BaseGlShaderAssembler {
private _texture_allocations_controller: TextureAllocationsController | undefined;
templateShader() {
return undefined;
}
protected _template_shader_for_shader_name(shader_name: ShaderName) {
return TemplateDefault;
}
// async get_shaders(){
// await this.update_shaders()
// return this._shaders_by_name
// }
compile() {
this.setup_shader_names_and_variables();
this.update_shaders();
}
root_nodes_by_shader_name(shader_name: ShaderName): BaseGlNodeType[] {
// return this._root_nodes
const list = [];
for (let node of this._root_nodes) {
switch (node.type()) {
case OutputGlNode.type(): {
list.push(node);
break;
}
case AttributeGlNode.type(): {
// TODO: typescript - gl - why is there a texture allocation controller in the base assembler?
const attrib_name = (node as AttributeGlNode).attribute_name;
const variable = this._texture_allocations_controller?.variable(attrib_name);
if (variable && variable.allocation()) {
const allocation_shader_name = variable.allocation()?.shaderName();
if (allocation_shader_name == shader_name) {
list.push(node);
}
}
break;
}
}
}
return list;
}
leaf_nodes_by_shader_name(shader_name: ShaderName): BaseGlNodeType[] {
const list = [];
for (let node of this._leaf_nodes) {
switch (node.type()) {
case GlobalsGlNode.type(): {
list.push(node);
break;
}
case AttributeGlNode.type(): {
// TODO: typescript - gl - why is there a texture allocation controller in the base assembler? AND especially since there is no way to assign it?
const attrib_name: string = (node as AttributeGlNode).attribute_name;
const variable = this._texture_allocations_controller?.variable(attrib_name);
if (variable && variable.allocation()) {
const allocation_shader_name = variable.allocation()?.shaderName();
if (allocation_shader_name == shader_name) {
list.push(node);
}
}
break;
}
}
}
return list;
}
setup_shader_names_and_variables() {
const node_traverser = new TypedNodeTraverser<NodeContext.GL>(
this.currentGlParentNode(),
this.shaderNames(),
(root_node, shader_name) => {
return this.input_names_for_shader_name(root_node, shader_name);
}
);
this._leaf_nodes = node_traverser.leaves_from_nodes(this._root_nodes);
// for (let node of this._root_nodes) {
// await node.params.eval_all();
// }
// for (let node of this._leaf_nodes) {
// await node.params.eval_all();
// }
this._texture_allocations_controller = new TextureAllocationsController();
this._texture_allocations_controller.allocateConnectionsFromRootNodes(this._root_nodes, this._leaf_nodes);
// const globals_handler = new GlobalsTextureHandler()
// this.set_assembler_globals_handler(globals_handler)
if (this.globals_handler) {
((<unknown>this.globals_handler) as GlobalsTextureHandler)?.set_texture_allocations_controller(
this._texture_allocations_controller
);
}
this._reset_shader_configs();
}
update_shaders() {
this._shaders_by_name.clear();
this._lines.clear();
for (let shader_name of this.shaderNames()) {
const template = this._template_shader_for_shader_name(shader_name);
this._lines.set(shader_name, template.split('\n'));
}
if (this._root_nodes.length > 0) {
// the code builder needs to be reset here,
// as otherwise it will not know that the shader names may have changed
this._resetCodeBuilder();
this.build_code_from_nodes(this._root_nodes);
this._build_lines();
}
// this._material.uniforms = this.build_uniforms(template_shader)
for (let shader_name of this.shaderNames()) {
const lines = this._lines.get(shader_name);
if (lines) {
this._shaders_by_name.set(shader_name, lines.join('\n'));
}
}
}
//
//
// CHILDREN NODES PARAMS
//
//
add_output_inputs(output_child: OutputGlNode) {
// output_child.add_param(ParamType.VECTOR3, 'position', [0, 0, 0]);
// output_child.add_param(ParamType.VECTOR3, 'velocity', [0, 0, 0]);
output_child.io.inputs.setNamedInputConnectionPoints([
new GlConnectionPoint('position', GlConnectionPointType.VEC3),
new GlConnectionPoint('velocity', GlConnectionPointType.VEC3),
]);
}
add_globals_outputs(globals_node: GlobalsGlNode) {
globals_node.io.outputs.setNamedOutputConnectionPoints([
new GlConnectionPoint('position', GlConnectionPointType.VEC3),
new GlConnectionPoint('velocity', GlConnectionPointType.VEC3),
// new TypedNamedConnectionPoint('acceleration', ConnectionPointType.VEC3),
new GlConnectionPoint('time', GlConnectionPointType.FLOAT),
]);
}
allow_attribute_exports() {
return true;
}
textureAllocationsController() {
return (this._texture_allocations_controller =
this._texture_allocations_controller || new TextureAllocationsController());
}
//
//
// CONFIGS
//
//
create_shader_configs() {
return this._texture_allocations_controller?.createShaderConfigs() || [];
// [
// new ShaderConfig('position', ['position'], []),
// // new ShaderConfig('fragment', ['color', 'alpha'], ['vertex']),
// ]
}
create_variable_configs() {
return [
// new VariableConfig('position', {
// default: 'vec3( position )',
// prefix: 'vec3 transformed = '
// }),
];
}
shaderNames(): ShaderName[] {
return this.textureAllocationsController().shaderNames() || [];
}
input_names_for_shader_name(root_node: BaseGlNodeType, shader_name: ShaderName) {
return this.textureAllocationsController().inputNamesForShaderName(root_node, shader_name) || [];
// return this.shader_config(shader_name).input_names()
}
//
//
// TEMPLATE HOOKS
//
//
protected insert_define_after(shader_name: ShaderName) {
return '// INSERT DEFINE';
}
protected insert_body_after(shader_name: ShaderName) {
return '// INSERT BODY';
}
protected lines_to_remove(shader_name: ShaderName) {
return ['// INSERT DEFINE', '// INSERT BODY'];
}
//
//
// TEMPLATE CODE REPLACEMENT
//
//
add_export_body_line(
export_node: BaseGlNodeType,
input_name: string,
input: BaseGlNodeType,
variable_name: string,
shaders_collection_controller: ShadersCollectionController
) {
if (input) {
const var_input = export_node.variableForInput(input_name);
const new_var = ThreeToGl.vector3(var_input);
if (new_var) {
const texture_variable = this.textureAllocationsController().variable(variable_name);
// if we are in the texture this variable is allocated to, we write it back
const shader_name = shaders_collection_controller.current_shader_name;
if (texture_variable && texture_variable.allocation()?.shaderName() == shader_name) {
const component = texture_variable.component();
const line = `gl_FragColor.${component} = ${new_var}`;
shaders_collection_controller.addBodyLines(export_node, [line], shader_name);
}
}
}
}
set_node_lines_output(output_node: BaseGlNodeType, shaders_collection_controller: ShadersCollectionController) {
const shader_name = shaders_collection_controller.current_shader_name;
const input_names = this.textureAllocationsController().inputNamesForShaderName(output_node, shader_name);
if (input_names) {
for (let input_name of input_names) {
const input = output_node.io.inputs.named_input(input_name);
if (input) {
const variable_name = input_name;
this.add_export_body_line(
output_node,
input_name,
input,
variable_name,
shaders_collection_controller
);
} else {
// position reads the default attribute position
// or maybe there is no need?
// if(input_name == 'position'){
// this.globals_handler().read_attribute(output_node, 'vec3', 'position')
// }
}
}
}
}
set_node_lines_attribute(
attribute_node: AttributeGlNode,
shaders_collection_controller: ShadersCollectionController
) {
if (attribute_node.isImporting()) {
const gl_type = attribute_node.gl_type();
const attribute_name = attribute_node.attribute_name;
const new_value = this.globals_handler?.read_attribute(
attribute_node,
gl_type,
attribute_name,
shaders_collection_controller
);
const var_name = attribute_node.glVarName(attribute_node.output_name);
const body_line = `${gl_type} ${var_name} = ${new_value}`;
shaders_collection_controller.addBodyLines(attribute_node, [body_line]);
// re-export to ensure it is available on next frame
const texture_variable = this.textureAllocationsController().variable(attribute_name);
const shader_name = shaders_collection_controller.current_shader_name;
if (texture_variable && texture_variable.allocation()?.shaderName() == shader_name) {
const variable = this.textureAllocationsController().variable(attribute_name);
if (variable) {
const component = variable.component();
const body_line = `gl_FragColor.${component} = ${var_name}`;
shaders_collection_controller.addBodyLines(attribute_node, [body_line]);
}
}
// this.add_import_body_line(
// attribute_node,
// shader_name,
// Attribute.output_name(),
// attribute_node.attribute_name()
// )
}
if (attribute_node.isExporting()) {
const input = attribute_node.connected_input_node();
if (input) {
const variable_name = attribute_node.attribute_name;
this.add_export_body_line(
attribute_node,
attribute_node.input_name,
input,
variable_name,
shaders_collection_controller
);
}
}
}
set_node_lines_globals(globals_node: GlobalsGlNode, shaders_collection_controller: ShadersCollectionController) {
for (let output_name of globals_node.io.outputs.used_output_names()) {
switch (output_name) {
case 'time':
this._handle_globals_time(globals_node, output_name, shaders_collection_controller);
break;
default:
this._handle_globals_default(globals_node, output_name, shaders_collection_controller);
}
}
}
private _handle_globals_time(
globals_node: GlobalsGlNode,
output_name: string,
shaders_collection_controller: ShadersCollectionController
) {
const definition = new UniformGLDefinition(globals_node, GlConnectionPointType.FLOAT, output_name);
shaders_collection_controller.addDefinitions(globals_node, [definition]);
const var_name = globals_node.glVarName(output_name);
const body_line = `float ${var_name} = ${output_name}`;
shaders_collection_controller.addBodyLines(globals_node, [body_line]);
this.setUniformsTimeDependent();
}
private _handle_globals_default(
globals_node: GlobalsGlNode,
output_name: string,
shaders_collection_controller: ShadersCollectionController
) {
const output_connection_point = globals_node.io.outputs.namedOutputConnectionPointsByName(output_name);
if (output_connection_point) {
const gl_type = output_connection_point.type();
const attrib_read = this.globals_handler?.read_attribute(
globals_node,
gl_type,
output_name,
shaders_collection_controller
);
if (attrib_read) {
const var_name = globals_node.glVarName(output_name);
const body_line = `${gl_type} ${var_name} = ${attrib_read}`;
shaders_collection_controller.addBodyLines(globals_node, [body_line]);
}
}
}
} | the_stack |
import * as searchString from 'search-string';
import { searchableItems } from 'src/__data__/searchableItems';
import * as RefinedSearch from './refinedSearch';
import { QueryJSON } from './refinedSearch';
import { SearchableItem } from './search.interfaces';
const {
areAllTrue,
areAnyTrue,
doesSearchTermMatchItemField,
ensureValueIsString,
flattenSearchableItem,
formatQuery,
getQueryInfo,
getRealEntityKey,
isSimpleQuery,
recursivelyTestItem,
refinedSearch,
searchDefaultFields,
testItem,
} = RefinedSearch;
const data = searchableItems as SearchableItem[];
describe('Refined Search', () => {
describe('simple query', () => {
it('should search labels', () => {
const query = 'test-linode-001';
const results = refinedSearch(query, data).map((entity) => entity.label);
expect(results).toContain('test-linode-001');
});
it('should not include non matching label results', () => {
const query = 'test-linode-001';
const results = refinedSearch(query, data).map((entity) => entity.label);
expect(results).toEqual(['test-linode-001']);
});
it('should search tags', () => {
const query = 'my-app';
const results = refinedSearch(query, data).map((entity) => entity.value);
expect(results).toContain(1);
expect(results).toContain(2);
});
it('should not include non matching tag results', () => {
const query = 'production';
const results = refinedSearch(query, data).map((entity) => entity.value);
expect(results).toEqual([2, 3]);
});
it('should search both label and tags', () => {
const query = 'my-app';
const results = refinedSearch(query, data).map((entity) => entity.value);
expect(results).toEqual([1, 2, 4]);
});
it('should search by partial label', () => {
const query = 'test-linode-00';
const results = refinedSearch(query, data).map((entity) => entity.label);
expect(results).toEqual([
'test-linode-001',
'test-linode-002',
'test-linode-003',
]);
});
it('should search by partial tag', () => {
const query = 'my-app';
const results = refinedSearch(query, data).map((entity) => entity.value);
expect(results).toEqual([1, 2, 4]);
});
});
describe('key value search', () => {
it('should allow searching by label', () => {
const query = 'label:test-linode-001';
const results = refinedSearch(query, data).map((entity) => entity.label);
expect(results).toEqual(['test-linode-001']);
});
it('should allow searching by single tag', () => {
const query = 'tags:my-app';
const results = refinedSearch(query, data).map((entity) => entity.value);
expect(results).toEqual([1, 2]);
});
it('should allow searching by multiple tags', () => {
const query = 'tags:my-app2,production';
const results = refinedSearch(query, data).map((entity) => entity.value);
expect(results).toEqual([2]);
});
it('should treat multiple tags as AND condition instead of OR', () => {
const query = 'tags:my-app,unrelated-app';
const results = refinedSearch(query, data).map((entity) => entity.value);
expect(results).toEqual([]);
});
it('should allow specifying multiple keys', () => {
const query = 'label:test-linode tags:my-app2';
const results = refinedSearch(query, data).map((entity) => entity.value);
expect(results).toEqual([2]);
});
it('should allow negating key values with the "-" character', () => {
let query = '-label:test-linode';
let results = refinedSearch(query, data).map((entity) => entity.value);
expect(results).toEqual([4]);
query = '-tag:production,unrelated-app';
results = refinedSearch(query, data).map((entity) => entity.value);
expect(results).toEqual([1, 4]);
});
it('does not crash when unknown keys are specified', () => {
const query = 'unknown:hello';
expect(refinedSearch(query, data)).toEqual([]);
});
it('makes known substitutions', () => {
let query = 'tags:my-app';
let results = refinedSearch(query, data).map((entity) => entity.value);
expect(results).toEqual([1, 2]);
query = 'name:test-linode-001';
results = refinedSearch(query, data).map((entity) => entity.value);
expect(results).toEqual([1]);
});
});
describe('boolean logic', () => {
it('allows joining search terms with AND', () => {
let query = 'label:test-linode-002 AND tags:my-app2';
let results = refinedSearch(query, data).map((entity) => entity.value);
expect(results).toEqual([2]);
query = 'label:test-linode-00 AND tags:my-app';
results = refinedSearch(query, data).map((entity) => entity.value);
expect(results).toEqual([1, 2]);
});
it('allows joining search terms with OR', () => {
let query = 'label:test-linode-002 OR tags:my-app2';
let results = refinedSearch(query, data).map((entity) => entity.value);
expect(results).toEqual([2]);
query = 'label:test-linode-00 OR tags:my-app';
results = refinedSearch(query, data).map((entity) => entity.value);
expect(results).toEqual([1, 2, 3]);
});
it('allows incomplete queries', () => {
let query = 'label:test-linode AND';
let results = refinedSearch(query, data).map((entity) => entity.value);
expect(results).toEqual([]);
query = 'label:test-linode AN';
results = refinedSearch(query, data).map((entity) => entity.value);
expect(results).toEqual([]);
query = 'label:test-linode ANDD';
results = refinedSearch(query, data).map((entity) => entity.value);
expect(results).toEqual([]);
query = 'label:test-linode OR';
results = refinedSearch(query, data).map((entity) => entity.value);
expect(results).toEqual([]);
query = 'label:test-linode ORR';
results = refinedSearch(query, data).map((entity) => entity.value);
expect(results).toEqual([]);
});
});
});
const mockLinode: SearchableItem = {
value: 1234,
label: 'my-linode',
entityType: 'linode',
data: {
tags: ['my-app', 'production'],
ips: ['1234'],
},
};
describe('formatQuery', () => {
it('trims whitespace', () => {
expect(formatQuery('hello world ')).toBe('hello world');
expect(formatQuery(' hello world ')).toBe('hello world');
expect(formatQuery(' hello world')).toBe('hello world');
expect(formatQuery('hello world')).toBe('hello world');
});
it('replaces " && " with " AND "', () => {
expect(formatQuery('hello && world')).toBe('hello AND world');
expect(formatQuery('hello &&world')).toBe('hello &&world');
expect(formatQuery('hello&&world')).toBe('hello&&world');
expect(formatQuery('hello AND world')).toBe('hello AND world');
expect(formatQuery('hello AND world')).toBe('hello AND world');
});
it('replaces " || " with " OR "', () => {
expect(formatQuery('hello || world')).toBe('hello OR world');
expect(formatQuery('hello ||world')).toBe('hello ||world');
expect(formatQuery('hello||world')).toBe('hello||world');
expect(formatQuery('hello OR world')).toBe('hello OR world');
expect(formatQuery('hello OR world')).toBe('hello OR world');
});
});
describe('recursivelyTestItem', () => {
beforeEach(() => {
jest.resetAllMocks();
});
const queryJSON1: QueryJSON = {
type: 'and',
values: [
{ type: 'string', value: 'tags:my-app' },
{ type: 'string', value: 'tags:production' },
],
};
const queryJSON2: QueryJSON = {
type: 'or',
values: [
{ type: 'string', value: 'tags:my-app' },
{ type: 'string', value: 'tags:production' },
],
};
const queryJSON3: QueryJSON = { type: 'string', value: 'tags:production' };
const queryJSON4: QueryJSON = {
type: 'or',
values: [
{
type: 'string',
value: 'type:linode',
},
{
type: 'and',
values: [
{
type: 'string',
value: 'tag:my-app',
},
{
type: 'string',
value: 'type:domain',
},
],
},
],
};
const spy_areAnyTrue = jest.spyOn(RefinedSearch, 'areAnyTrue');
const spy_areAllTrue = jest.spyOn(RefinedSearch, 'areAllTrue');
const spy_recursivelyTestItem = jest.spyOn(
RefinedSearch,
'recursivelyTestItem'
);
it('calls the areAllTrue() function if the type is "and"', () => {
recursivelyTestItem(queryJSON1, mockLinode);
expect(spy_areAllTrue).toHaveBeenCalled();
});
it('calls the areAnyTrue() function if the type is "or"', () => {
recursivelyTestItem(queryJSON2, mockLinode);
expect(spy_areAnyTrue).toHaveBeenCalled();
});
it('does not call areAnyTrue() or areAllTrue() if it is a single value', () => {
recursivelyTestItem(queryJSON3, mockLinode);
// testItem() WILL call areAllTrue, so we test that it's only been called once.
expect(spy_areAllTrue).toHaveBeenCalledTimes(1);
expect(spy_areAnyTrue).not.toHaveBeenCalled();
});
it('calls itself recursively', () => {
recursivelyTestItem(queryJSON4, mockLinode);
expect(spy_recursivelyTestItem).toHaveBeenCalledTimes(2);
});
it('returns false if given bad data', () => {
expect(recursivelyTestItem({} as QueryJSON, mockLinode)).toBe(false);
});
});
describe('testItem', () => {
it('returns TRUE if there is a substring match, and FALSE if there is not', () => {
expect(testItem(mockLinode, 'my-linode')).toBe(true);
expect(testItem(mockLinode, 'my-')).toBe(true);
expect(testItem(mockLinode, 'linode')).toBe(true);
expect(testItem(mockLinode, 'production')).toBe(true);
expect(testItem(mockLinode, 'my-app')).toBe(true);
expect(testItem(mockLinode, 'n')).toBe(true);
expect(testItem(mockLinode, 'hello')).toBe(false);
});
});
describe('isSimpleQuery', () => {
it('returns true if there are no specified search fields', () => {
let parsedQuery = searchString.parse('-hello world').getParsedQuery();
expect(isSimpleQuery(parsedQuery)).toBe(true);
parsedQuery = searchString.parse('hello world').getParsedQuery();
expect(isSimpleQuery(parsedQuery)).toBe(true);
parsedQuery = searchString.parse('hello -world').getParsedQuery();
expect(isSimpleQuery(parsedQuery)).toBe(true);
});
it('returns false if there are specified search fields', () => {
let parsedQuery = searchString.parse('label:hello').getParsedQuery();
expect(isSimpleQuery(parsedQuery)).toBe(false);
parsedQuery = searchString.parse('tags:hello,world').getParsedQuery();
expect(isSimpleQuery(parsedQuery)).toBe(false);
parsedQuery = searchString.parse('-label:hello').getParsedQuery();
expect(isSimpleQuery(parsedQuery)).toBe(false);
});
});
describe('searchDefaultFields', () => {
it('searches each default field', () => {
// Label
expect(searchDefaultFields(mockLinode, 'my-linode')).toBe(true);
// Tags
expect(searchDefaultFields(mockLinode, 'production')).toBe(true);
// Ips
expect(searchDefaultFields(mockLinode, '1234')).toBe(true);
});
});
describe('doesSearchTermMatchItemField', () => {
it('matches given field name', () => {
expect(doesSearchTermMatchItemField('my-app', mockLinode, 'tags')).toBe(
true
);
expect(doesSearchTermMatchItemField('my-app', mockLinode, 'ips')).toBe(
false
);
expect(doesSearchTermMatchItemField('12', mockLinode, 'ips')).toBe(true);
});
it('is case-insensitive by default', () => {
expect(doesSearchTermMatchItemField('MY-APP', mockLinode, 'tags')).toBe(
true
);
});
it('is case-sensitive if specified', () => {
expect(
doesSearchTermMatchItemField('MY-APP', mockLinode, 'tags', true)
).toBe(false);
});
});
describe('flattenSearchableItem', () => {
it('flattens properties in "data" with the rest of the entity', () => {
expect(flattenSearchableItem(mockLinode)).toHaveProperty('tags');
expect(flattenSearchableItem(mockLinode)).toHaveProperty('ips');
expect(flattenSearchableItem(mockLinode)).not.toHaveProperty('data');
});
});
describe('ensureValueIsString', () => {
it('returns original input if it is a string', () => {
expect(ensureValueIsString('hello')).toBe('hello');
expect(ensureValueIsString('')).toBe('');
});
it('returns joined string if input is an array', () => {
expect(ensureValueIsString(['hello', 'world'])).toBe('hello world');
expect(ensureValueIsString([1, 2, 3])).toBe('1 2 3');
expect(ensureValueIsString(['hello'])).toBe('hello');
});
});
describe('getQueryInfo', () => {
it('returns searchTerms, fieldName, and isNegated', () => {
const parsedQuery = { exclude: {}, tags: ['my-app'] };
expect(getQueryInfo(parsedQuery)).toHaveProperty('searchTerms');
expect(getQueryInfo(parsedQuery)).toHaveProperty('fieldName');
expect(getQueryInfo(parsedQuery)).toHaveProperty('isNegated');
});
it('returns isNegated as TRUE when excluded is not empty', () => {
const parsedQuery = { exclude: { tag: ['my-app'] } };
expect(getQueryInfo(parsedQuery).isNegated).toBe(true);
});
it('returns field name', () => {
const parsedQuery1 = { exclude: { tags: ['my-app'] } };
expect(getQueryInfo(parsedQuery1).fieldName).toBe('tags');
const parsedQuery2 = { exclude: {}, tags: ['my-app'] };
expect(getQueryInfo(parsedQuery2).fieldName).toBe('tags');
});
it('returns other search terms', () => {
const parsedQuery1 = { exclude: { tags: ['my-app'] } };
expect(getQueryInfo(parsedQuery1).searchTerms).toEqual(['my-app']);
const parsedQuery2 = { exclude: {}, tags: ['my-app', 'my-other-app'] };
expect(getQueryInfo(parsedQuery2).searchTerms).toEqual([
'my-app',
'my-other-app',
]);
});
});
describe('getRealEntityKey', () => {
it('returns "label" if given "name" or "title"', () => {
expect(getRealEntityKey('name')).toBe('label');
expect(getRealEntityKey('title')).toBe('label');
});
it('returns "tags" if given "tag" or "groups"', () => {
expect(getRealEntityKey('tag')).toBe('tags');
expect(getRealEntityKey('group')).toBe('tags');
});
it('returns "ips" if given "ip"', () => {
expect(getRealEntityKey('ip')).toBe('ips');
});
it('returns the original string if no substitute key is found', () => {
expect(getRealEntityKey('hello')).toBe('hello');
expect(getRealEntityKey('')).toBe('');
});
});
describe('areAllTrue', () => {
it('returns true if all values in array are true', () => {
let values = [true, true, true];
expect(areAllTrue(values)).toBe(true);
values = [true, false, true];
expect(areAllTrue(values)).toBe(false);
});
});
describe('areAnyTrue', () => {
it('returns true if at least ONE value in array is true', () => {
let values = [false, false, false];
expect(areAnyTrue(values)).toBe(false);
values = [true, false, false];
expect(areAnyTrue(values)).toBe(true);
values = [true, true, true];
expect(areAnyTrue(values)).toBe(true);
});
}); | the_stack |
const cleanOption: Fig.Option = {
name: "--clean",
description: "Forces rebuilding the native application",
};
const timeoutOption: Fig.Option = {
name: "--timeout",
description:
"Sets the number of seconds that the NativeScript CLI will wait for the debugger to boot. If not set, the default timeout is 90 seconds",
args: {
name: "seconds",
},
};
const emulatorOption: Fig.Option = {
name: "--emulator",
description: "Specifies that you want to debug the app in an emulator",
};
const deviceOption: Fig.Option = {
name: "--device",
description: "Specifies a connected device/emulator to start and run the app",
args: {
name: "device id",
// TODO: create a generator of ns device <platform> --available-devices
// generators: {
// script: "ns devices --json",
// postProcess: (output) => {
// return [{
// name: "test1",
// description: "Test 1"
// }]
// },
// },
},
};
const forceOption: Fig.Option = {
name: "--force",
description:
"Skips the application compatibility checks and forces npm i to ensure all dependencies are installed",
};
const noHmrOption: Fig.Option = {
name: "--no-hmr",
description: "Disables Hot Module Replacement (HMR)",
};
const frameworkPathOption: Fig.Option = {
name: "--framework-path",
description:
"Sets the path to a NativeScript runtime for the specified platform that you want to use instead of the default runtime. <File Path> must point to a valid npm package",
args: {
name: "path",
template: "filepaths",
},
};
const jsonOption: Fig.Option = {
name: "--json",
description: "Show the output of the command in JSON format",
};
const justLaunchOption: Fig.Option = {
name: "--justlaunch",
description: "Does not print the application output in the console",
};
const releaseOption: Fig.Option = {
name: "--release",
description:
"Produces a release build by running webpack in production mode and native build in release mode. Otherwise, produces a debug build",
};
const bundleOption: Fig.Option = {
name: "--bundle",
description: "Bundle the application",
};
const helpOption = (label: string): Fig.Option => {
return {
name: ["--help", "-h"],
description: `Show help for the ${label} subcommand`,
priority: 0,
};
};
/**
* Plaform options used across many commands of the CLI
*/
const androidGeneralOptions: Fig.Option[] = [
{
name: "--aab",
description:
"Specifies that the command will produce and deploy an Android App Bundle",
},
{
name: "--env.snapshot",
description:
"Creates a V8 Snapshot decreasing the app start time (only for release builds for Android)",
dependsOn: ["--release"],
},
{
name: "--env.compileSnapshot",
description:
"Compiles the static assets produced by --env.snapshot into .so files allowing the native build to split them per architecture. This will reduce the app size when using the --aab option",
dependsOn: ["--env.snapshot", "--aab"],
},
{
name: "--env.appComponents",
description: "Allows passing additional App Components for android",
},
];
const androidKeyOptions: Fig.Option[] = [
{
name: "--key-store-path",
description:
"Specifies the file path to the keystore file (P12) which you want to use to code sign your APK",
args: {
name: "path",
template: "filepaths",
},
dependsOn: ["--release"],
},
{
name: "--key-store-password",
description:
"Provides the password for the keystore file specified with --key-store-path",
args: {
name: "password",
},
dependsOn: ["--release"],
},
{
name: "--key-store-alias",
description:
"Provides the alias for the keystore file specified with --key-store-path",
args: {
name: "alias",
},
dependsOn: ["--release"],
},
{
name: "--key-store-alias-password",
description:
"Provides the password for the alias specified with --key-store-alias-password",
args: {
name: "alias password",
},
dependsOn: ["--release"],
},
];
const platformEnvOptions: Fig.Option[] = [
{
name: "--env.aot",
description: "Creates an Ahead-Of-Time build (Angular only)",
},
{
name: "--env.uglify",
description: "Provides basic obfuscation and smaller app size",
},
{
name: "--env.report",
description:
"Creates a Webpack report inside a /report folder in the root folder",
},
{
name: "--env.sourceMap",
description: "Creates inline source maps",
},
{
name: "--env.hiddenSourceMap",
description:
"Creates sources maps in the root folder (useful for Crashlytics usage with bundled app in release)",
},
{
name: "--env.verbose",
description: "Prints verbose logs and the internal config before building",
},
{
name: "--env.production",
description: "Enable production mode (will minify the code)",
},
{
name: "--env.replace=from:to",
description:
"Add file replacement rules. For source files (.js and .ts) this will add a new alias to the config, for everything else, this will add a new copy rule",
insertValue: "--env.replace={cursor}:",
},
];
const platformGeneralOptions: Fig.Option[] = [
...platformEnvOptions,
noHmrOption,
forceOption,
deviceOption,
cleanOption,
emulatorOption,
timeoutOption,
];
/**
* Defined a map of shared options for various commands
* Some commands have slightly varied options.
*/
const platformOptions = {
// NOTE: used like so:
// ...platformOption.<command>.both
// ...platformOption.<command>.ios
run: {
both: [
...platformGeneralOptions,
justLaunchOption,
releaseOption,
bundleOption,
],
ios: [
{
name: "--sdk",
description: "Specifies the target simulator's sdk",
args: {
name: "sdk",
},
},
],
android: [...androidGeneralOptions, ...androidKeyOptions],
},
debug: {
both: [
...platformGeneralOptions,
{
name: "--debug-brk",
description:
"Prepares, builds and deploys the application package on a device or in an emulator, and stops at the first JavaScript line until either the debugger frontend connects or a 30 seconds timeout elapses",
},
{
name: "--start",
description: "Attaches the debug tools to a deployed and running app",
},
{
name: "--no-watch",
description: "Changes in your code will not be livesynced",
},
],
ios: [
{
name: "--no-client",
description:
"The NativeScript CLI attaches the debug tools but does not launch the developer tools in Safari. Could be used on already started Safari Web Inspector",
},
{
name: "--inspector",
description:
"The developer tools in the Safari Web Inspector are used for debugging the application",
},
],
android: androidGeneralOptions,
},
test: {
both: [
{
name: "--watch",
description:
"When you save changes to the project, changes are automatically synchronized to the connected device and tests are re-run",
},
{
name: "--debug-brk",
description:
"Runs the tests under the debugger. The debugger will break just before your tests are executed, so you have a chance to place breakpoints",
},
justLaunchOption,
forceOption,
deviceOption,
emulatorOption,
],
ios: [],
android: androidGeneralOptions,
},
build: {
both: [
...platformEnvOptions,
releaseOption,
{
name: "--copy-to",
description:
"Specifies the file path where the built .ipa|.apk will be copied. If it points to a non-existent directory path, it will be created. If the specified value is existing directory, the original file name will be used",
args: {
name: "path",
template: "folders" as Fig.Template,
},
},
{
name: "--path",
description:
"Specifies the directory where you want to create the project, if different from the current directory",
args: {
name: "directory",
template: "folders" as Fig.Template,
},
},
forceOption,
cleanOption,
deviceOption,
],
android: [
...androidGeneralOptions,
{
name: "--compileSdk",
description:
"Sets the Android SDK that will be used to build the project",
args: {
name: "api level",
},
},
...androidKeyOptions,
],
ios: [
{
name: "--for-device",
description:
"Produces an application package that you can deploy on device. Otherwise, produces a build that you can run only in the native iOS Simulator",
},
{
name: "--i-cloud-container-environment",
description:
"Adds the passed iCloudContainerEnvironment when exporting an application package with the --for-device option",
dependsOn: ["--for-device"],
},
{
name: "--team-id",
description:
"If used without parameter, lists all team names and ids. If used with team name or id, it will switch to automatic signing mode and configure the .xcodeproj file of your app. In this case .xcconfig should not contain any provisioning/team id flags",
args: {
name: "team id",
isOptional: true,
},
},
{
name: "--provision",
description:
"If used without parameter, lists all eligible provisioning profiles. If used with UUID or name of your provisioning profile, it will switch to manual signing mode and configure the .xcodeproj file of your app",
args: {
name: "uuid",
isOptional: true,
},
},
],
},
deploy: {
both: [
deviceOption,
cleanOption,
forceOption,
releaseOption,
...platformEnvOptions,
],
ios: [],
android: [...androidGeneralOptions, ...androidKeyOptions],
},
};
// General Commands
const helpCommand: Fig.Subcommand = {
name: "help",
description: "Open the CLI's documentation in your web browser",
options: [helpOption("help")],
};
const infoCommand: Fig.Subcommand = {
name: "info",
description:
"Displays version information about the NativeScript CLI, core modules, and runtimes",
options: [helpOption("info")],
};
const updateCommand: Fig.Subcommand = {
name: "update",
description:
"Updates the project with the latest versions of platform runtimes, cross-platform modules and webpack",
isDangerous: true,
subcommands: [
{
name: "next",
description: "The latest development release",
},
],
args: {
name: "version",
description: "The version to update the project to",
isOptional: true,
},
options: [helpOption("update")],
};
const packageManagerCommand: Fig.Subcommand = {
name: "package-manager",
description: "Prints the value of the current package manager",
subcommands: [
{
name: "get",
description: "Prints the value of the current package manager",
},
{
name: "set",
description:
"Enables the specified package manager for the NativeScript CLI. Supported values are npm, yarn and pnpm",
},
],
options: [helpOption("package-manager")],
};
const doctorCommand: Fig.Subcommand = {
name: "doctor",
description:
"Checks your system for configuration problems which might prevent the NativeScript CLI from working properly for the specified platform, if configured",
subcommands: [
{
name: "android",
description: "Check your system configuration for android",
},
{
name: "ios",
description: "Check your system configuration for ios",
},
],
options: [helpOption("doctor")],
};
const migrateCommand: Fig.Subcommand = {
name: "migrate",
description:
"Migrates the app dependencies to a form compatible with NativeScript 6.0",
isDangerous: true,
options: [helpOption("migrate")],
};
const proxyCommand: Fig.Subcommand = {
name: "proxy",
description: "Displays the current proxy settings of the NativeScript CLI",
subcommands: [
{
name: "clear",
description:
"Clears the currently configured proxy settings of the NativeScript CLI",
},
{
name: "set",
description: "Sets the proxy settings of the NativeScript CLI",
args: [
{
name: "proxy url",
description:
"Full url of the proxy. For example, http://127.0.0.1:8888. If you do not provide the url when running the command, the NativeScript CLI will prompt you to provide it",
},
{
name: "username",
description: "Credentials for the proxy",
isOptional: true,
},
{
name: "password",
description: "Credentials for the proxy",
isOptional: true,
},
],
options: [
{
name: "--insecure",
description:
"Allows insecure SSL connections and transfers to be performed. In case your proxy doesn't have a CA certificate or has an invalid one you need to use this flag",
},
],
},
],
options: [helpOption("proxy")],
};
const usageReportingCommand: Fig.Subcommand = {
name: "usage-reporting",
description:
"Configures anonymous usage reporting for the NativeScript CLI. All data gathered is used strictly for improving the product and will never be used to identify or contact you",
subcommands: [
{
name: "status",
description:
"Shows the current configuration for anonymous usage reporting for the NativeScript CLI",
},
{
name: "enable",
description: "Enables anonymous usage reporting",
},
{
name: "disable",
description: "Disables anonymous usage reporting",
},
],
options: [helpOption("usage-reporting")],
priority: 1,
};
const errorReportingCommand: Fig.Subcommand = {
name: "error-reporting",
description:
"Configures anonymous error reporting for the NativeScript CLI. All data gathered is used strictly for improving the product and will never be used to identify or contact you",
subcommands: [
{
name: "status",
description:
"Shows the current configuration for anonymous error reporting for the NativeScript CLI",
},
{
name: "enable",
description: "Enables anonymous error reporting",
},
{
name: "disable",
description: "Disables anonymous error reporting",
},
],
options: [helpOption("error-reporting")],
priority: 1,
};
// Project Development Commands
const createCommand: Fig.Subcommand = {
name: "create",
description:
"Create a new Nativescript project. Press Enter for an interactive walkthrough",
args: {
name: "application name",
description: "The name of the Nativescript project",
isOptional: true,
},
options: [
{
name: "--template",
description: "Create a project using a predefined template",
args: {
name: "template",
generators: {
script:
"curl https://api.github.com/repos/NativeScript/nativescript-app-templates/contents/packages",
cache: {
ttl: 100 * 24 * 60 * 60 * 1000, // 100days
},
postProcess: (output) => {
return JSON.parse(output).map((branch) => {
const template = branch?.name;
return {
name: `@nativescript/${template}`,
description: `Template ${template}`,
} as Fig.Suggestion;
});
},
},
},
},
{
name: ["--angular", "--ng"],
description: "Create a project using the Angular template",
},
{
name: "--react",
description: "Create a project using the React template",
},
{
name: ["--vue", "--vuejs"],
description: "Create a project using the Vue template",
},
{
name: "--svelte",
description: "Create a project using the Svelte template",
},
{
name: ["--typescript", "--tsc", "--ts"],
description: "Create a project using plain TypeScript",
},
{
name: ["--javascript", "--js"],
description: "Create a project using plain JavaScript",
},
{
name: "--path",
description:
"Specifies the directory where you want to create the project, if different from the current directory. <directory> is the absolute path to an empty directory in which you want to create the project",
priority: 10,
args: {
name: "directory",
template: "folders",
},
},
{
name: "--appid",
description:
"Sets the application identifier of your project. <appid> is the value of the application identifier and it must meet the specific requirements of each platform that you want to target. If not specified, the application identifier is set to org.nativescript.<Project Name>. The application identifier must be a domain name in reverse",
args: {
name: "identifier",
},
},
helpOption("create"),
],
};
const cleanCommand: Fig.Subcommand = {
name: "clean",
description: "Clean your Nativescript project",
options: [helpOption("clean")],
};
const previewCommand: Fig.Subcommand = {
name: "preview",
description:
"Produces a QR code which can be used to preview the app on a device",
options: [forceOption, noHmrOption, helpOption("preview")],
};
const platformCommand: Fig.Subcommand = {
name: "platform",
description:
"Lists all platforms that the project currently targets. You can build and deploy your project only for these target platforms",
subcommands: [
{
name: "list",
description:
"Lists all platforms that the project currently targets. You can build and deploy your project only for these target platforms",
},
{
name: "add",
description:
"Configures the current project to target the selected platform",
subcommands: [
{
name: "android",
description: "The latest android platform",
options: [frameworkPathOption],
},
{
name: "android@[Version]",
insertValue: "android@{cursor}",
description: "The defined android platform eg. 1.0.0",
options: [frameworkPathOption],
},
{
name: "ios",
description: "The latest ios platform",
options: [frameworkPathOption],
},
{
name: "ios@[Version]",
insertValue: "ios@{cursor}",
description: "The defined ios platform eg. 1.0.0",
options: [frameworkPathOption],
},
],
},
{
name: "remove",
description:
"Removes the selected platform from the platforms that the project currently targets",
subcommands: [
{
name: "android",
description: "The latest android platform",
},
{
name: "ios",
description: "The latest ios platform",
},
],
},
{
name: "update",
description:
"Updates the NativeScript runtime for the specified platform",
subcommands: [
{
name: "android",
description: "The latest android platform",
},
{
name: "ios",
description: "The latest ios platform",
},
],
},
],
options: [helpOption("platform")],
};
const runCommand: Fig.Subcommand = {
name: "run",
description:
"Runs your project on all connected devices or in native emulators for the selected platform",
subcommands: [
{
name: "android",
description: "The latest android platform",
options: [...platformOptions.run.both, ...platformOptions.run.android],
priority: 90,
},
{
name: "ios",
description: "The latest ios platform",
options: [...platformOptions.run.both, ...platformOptions.run.ios],
priority: 90,
},
],
options: [...platformOptions.run.both, helpOption("run")],
};
const debugCommand: Fig.Subcommand = {
name: "debug",
description:
"Initiates a debugging session for your project on a connected device or native emulator",
subcommands: [
{
name: "android",
description:
"Start a debugging session for your project on a connected Android device or Android emulator",
options: [
...platformOptions.debug.both,
...platformOptions.debug.android,
],
priority: 90,
},
{
name: "ios",
description:
"Start a debugging session for your project on a connected iOS device or in the native iOS simulator",
options: [...platformOptions.debug.both, ...platformOptions.debug.ios],
priority: 90,
},
],
options: [helpOption("debug")],
};
const testCommand: Fig.Subcommand = {
name: "test",
description: "Runs unit tests on the selected mobile platform",
subcommands: [
{
name: "init",
description: "Configure your project for unit testing",
options: [
{
name: "--framework",
description: "Sets the unit testing framework to install",
args: {
name: "framework",
suggestions: ["mocha", "jasmine", "qunit"],
},
},
],
},
{
name: "android",
description:
"Run unit tests on all connected android devices or native emulators",
options: [...platformOptions.test.both, ...platformOptions.test.android],
priority: 90,
},
{
name: "ios",
description:
"Run unit tests on all connected ios devices or native emulators",
options: [...platformOptions.test.both, ...platformOptions.test.ios],
priority: 90,
},
],
options: [helpOption("test")],
};
const pluginCommand: Fig.Subcommand = {
name: "plugin",
description: "Manage the plugins for your project",
subcommands: [
{
name: "add",
description: "Installs the specified plugin and its dependencies",
args: {
name: "plugin",
description: "A valid Nativescript plugin",
},
},
{
name: "remove",
description: "Uninstalls the specified plugin and its dependencies",
args: {
name: "plugin",
description: "A valid Nativescript plugin",
},
},
{
name: "update",
description:
"Uninstalls and installs the specified plugin(s) and its dependencies",
args: {
name: "plugin(s)",
description: "A valid Nativescript plugin",
},
},
{
name: "build",
description: "Builds the Android parts of a NativeScript plugin",
},
{
name: "create",
description: "Creates a project for building a new NativeScript plugin",
args: {
name: "plugin repository name",
description: "A valid Nativescript plugin repository",
},
options: [
{
name: "--path",
description:
"Specifies the directory where you want to create the project, if different from the current directory",
args: {
name: "directory",
description:
"Specifies the directory where you want to create the project, if different from the current directory",
template: "folders",
},
},
{
name: "--username",
description:
"Specifies the GitHub username, which will be used to build the URLs in the plugin's package.json file",
args: {
name: "username",
description: "GitHub username",
},
},
{
name: "--pluginName",
description:
"Used to set the default file and class names in the plugin source",
args: {
name: "name",
},
},
{
name: "--includeTypeScriptDemo",
description: "Specifies if a TypeScript demo should be created",
},
{
name: "--includeTypeScriptDemo=n",
description: "Specifies if TypeScript demo should NOT be created",
},
{
name: "--includeAngularDemo",
description: "Specifies if an Angular demo should be created",
},
{
name: "--includeAngularDemo=n",
description: "Specifies if Angular demo should NOT be created",
},
{
name: "--template",
description:
"Specifies the custom seed archive, which you want to use to create your plugin",
args: {
name: "template",
description: "Specifies the template for the plugin",
},
},
],
},
],
options: [helpOption("plugin")],
};
const resourcesCommand: Fig.Subcommand = {
name: "resources",
description: "Manage the plugins for your project",
subcommands: [
{
name: "update",
description:
"Updates the App_Resources's internal folder structure to conform to that of an Android Studio project",
},
{
name: "generate",
subcommands: [
{
name: "splashes",
args: {
name: "image path",
description:
"Path to an image that will be used to generate all splashscreens",
template: "filepaths",
},
options: [
{
name: "--background",
description: "Sets the background color of the splashscreen",
args: {
name: "color",
default: "white",
},
},
],
},
{
name: "icons",
args: {
name: "image path",
description:
"Path to an image that will be used to generate all splashscreens",
template: "filepaths",
},
},
],
},
],
options: [helpOption("plugin")],
};
const prepareCommand: Fig.Subcommand = {
name: "prepare",
description:
"Starts a Webpack compilation and prepares the app's App_Resources and the plugins platforms directories",
subcommands: [
{
name: "android",
description: "Prepares your project for an Android build",
options: [
{
name: "--hmr",
description: "Enables the hot module replacement (HMR) feature",
},
forceOption,
],
},
{
name: "ios",
description: "Prepares your project for an iOS build",
options: [
{
name: "--hmr",
description: "Enables the hot module replacement (HMR) feature",
},
forceOption,
],
},
],
options: [
{
name: "--hmr",
description: "Enables the hot module replacement (HMR) feature",
},
forceOption,
helpOption("prepare"),
],
};
const buildCommand: Fig.Subcommand = {
name: "build",
description:
"Builds the project for iOS and produces an APP or IPA that you can manually deploy in the iOS Simulator or on a device",
subcommands: [
{
name: "android",
options: [
...platformOptions.build.both,
...platformOptions.build.android,
],
priority: 90,
},
{
name: "ios",
options: [...platformOptions.build.both, ...platformOptions.build.ios],
priority: 90,
},
],
options: [
...platformOptions.build.both,
{
name: "--hmr",
description: "Enables the hot module replacement (HMR) feature",
},
justLaunchOption,
helpOption("build"),
],
};
const deployCommand: Fig.Subcommand = {
name: "deploy",
description:
"Prepares, builds and deploys the project to a connected device or native emulator. You must specify the target platform on which you want to deploy. It will deploy the app on all connected devices targeting the selected platform",
subcommands: [
{
name: "android",
options: [
...platformOptions.deploy.both,
...platformOptions.deploy.android,
],
priority: 90,
},
{
name: "ios",
options: [...platformOptions.deploy.both, ...platformOptions.deploy.ios],
priority: 90,
},
],
options: [helpOption("deploy")],
};
const installCommand: Fig.Subcommand = {
name: "install",
description:
"Installs all dependencies described in a valid package.json or installs a selected NativeScript development module as a dev dependency",
subcommands: [
{
name: "typescript",
description: "Enable TypeScript support",
},
],
args: {
name: "module",
description:
"Specifies a NativeScript development module by path to a local directory containing a valid npm module or by name in the npm registry",
},
options: [
{
name: "--path",
description:
"Specifies the directory which contains the package.json file, if different from the current directory",
args: {
name: "directory",
template: "folders",
},
},
helpOption("install"),
],
};
// Publishing Commands
const appStoreCommand: Fig.Subcommand = {
name: "appstore",
description:
"Lists all application records in iTunes Connect. The list contains name, version and bundle ID for each application record",
subcommands: [
{
name: "upload",
description:
"Uploads project to iTunes Connect. The command either issues a production build and uploads it to iTunes Connect, or uses an already built package to upload",
args: [
{
name: "appleId",
description: "Apple id for logging in iTunes Connect",
},
{
name: "password",
description: "Password for logging in iTunes Connect",
},
{
name: "mobile provisioning profile identifier",
description:
"The identifier of the mobile provision(e.g. d5d40f61-b303-4fc8-aea3-fbb229a8171c) which will be used for building. This can easily be acquired through the iPhone Configuration Utility",
},
{
name: "code sign identity",
description:
"The code sign identity which will be used for building. You can set it to something generic like 'iPhone Distribution' to let the build automatically detect a code sign identity",
},
],
options: [
{
name: "--ipa",
description:
"Use the provided .ipa file instead of building the project",
args: {
name: "ipa file path",
template: "filepaths",
},
},
{
name: "--appleApplicationSpecificPassword",
description:
"Specifies the password for accessing the information you store in iTunes Transporter application",
args: {
name: "password",
},
},
{
name: "--appleSessionBase64",
description:
"The session that will be used instead of triggering a new login each time NativeScript CLI communicates with Apple's APIs",
args: {
name: "base64",
},
},
],
},
],
args: [
{
name: "appleId",
description:
"Credentials for logging in iTunes Connect. If you do not provide them when running the command, the NativeScript CLI will prompt you to provide them",
},
{
name: "password",
description: "Password for logging in iTunes Connect",
},
],
options: [
{
name: "--team-id",
description:
"Specifies the team id for which Xcode will try to find distribution certificate and provisioning profile when exporting for AppStore submission",
args: {
name: "team id",
},
},
helpOption("appstore"),
],
};
// Devices Commands
const deviceCommand: Fig.Subcommand = {
name: ["device", "devices"],
description:
"Lists all recognized connected Android or iOS devices with serial number and index, grouped by platform",
subcommands: [
{
name: "android",
description:
"Lists all recognized connected Android physical and running Android virtual devices",
options: [
timeoutOption,
{
name: "--available-devices",
description: "Lists all available Android devices",
},
jsonOption,
],
},
{
name: "ios",
description:
"Lists all recognized connected iOS devices with serial number and index",
options: [
timeoutOption,
{
name: "--available-devices",
description: "Lists all available iOS devices",
},
jsonOption,
],
},
{
name: "log",
description:
"Opens the device log stream for a selected connected device",
options: [deviceOption],
},
{
name: "list-applications",
description:
"Lists the installed applications on all connected Android or iOS devices",
options: [deviceOption],
},
{
name: "run",
description:
"Runs the selected application on a connected Android or iOS device",
args: {
name: "application id",
description: "The application identifier", //TODO: generator $ tns device list-applications.
// generators: {
// script: "ns device list-applications",
// postProcess: (output) => {
// return JSON.parse(output).map((branch) => {
// const template = branch?.name;
// return {
// name: `@nativescript/${template}`,
// description: `Template ${template}`,
// } as Fig.Suggestion;
// });
// },
// },
},
options: [deviceOption],
},
],
options: [
{
name: "--available-devices",
description: "Lists all available devices",
},
jsonOption,
helpOption("device"),
],
};
/**
* Command groups
* (based off the help page when running `ns help`)
*/
const generalCommands: Array<Fig.Subcommand> = [
helpCommand,
infoCommand,
updateCommand,
packageManagerCommand,
doctorCommand,
migrateCommand,
usageReportingCommand,
errorReportingCommand,
proxyCommand,
// autoCompleteCommand,
];
const projectDevelopmentCommands: Array<Fig.Subcommand> = [
createCommand,
cleanCommand,
previewCommand,
platformCommand,
runCommand,
debugCommand,
testCommand,
pluginCommand,
resourcesCommand,
prepareCommand,
buildCommand,
deployCommand,
installCommand,
];
const publishingCommands: Array<Fig.Subcommand> = [appStoreCommand];
const devicesCommand: Array<Fig.Subcommand> = [deviceCommand];
// Environment Configuration Commands
// const setupCommand: Fig.Subcommand = {}
const environmentConfigurationCommands: Array<Fig.Subcommand> = [
// setupCommand
];
const allCommands = [
...generalCommands,
...projectDevelopmentCommands,
...publishingCommands,
...devicesCommand,
...environmentConfigurationCommands,
];
const completionSpec: Fig.Spec = {
name: "ns",
description:
"The NativeScript CLI lets you create, build, and deploy NativeScript based apps on iOS and Android devices",
subcommands: allCommands,
options: [
{
name: ["-v", "--version"],
description: "View your current Nativescript CLI version",
},
],
};
export default completionSpec; | the_stack |
import path from 'path';
import glob from 'glob';
import webpack from 'webpack';
import fs from 'fs';
import osenv from 'osenv';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
import HtmlWebpackExternalsPlugin from 'html-webpack-externals-plugin';
import SriPlugin from 'webpack-subresource-integrity';
import OfflineWebpackPlugin from 'offline-webpack-plugin';
import CleanWebpackPlugin from 'clean-webpack-plugin';
import UglifyJsPlugin from 'uglifyjs-webpack-plugin';
import StringReplaceWebpackPlugin from 'string-replace-webpack-plugin';
import HTMLInlineCSSWebpackPlugin from 'html-inline-css-webpack-plugin';
import OptimizeCssAssetsPlugin from 'optimize-css-assets-webpack-plugin';
import {deepCopy, listDir, merge, isEmpty, getCSSModulesLocalIdent} from './util';
import Config from './config';
// 当前运行的时候的根目录
let projectRoot: string = Config.getPath('feflow.json');
if (!projectRoot) {
projectRoot = Config.getPath('feflow.js');
}
export interface BaseConfig {
[propName: string]: any;
}
export interface BuilderOptions {
outDir: string | object,
entry: string | object,
moduleName?: string,
bizName?: string,
minifyHTML: boolean,
minifyCSS?: boolean,
minifyJS?: boolean,
inlineCSS: boolean,
usePx2rem: boolean,
useSri: boolean,
"remUnit": number,
remPrecision: number,
inject: boolean,
useTreeShaking?: boolean,
port?: number,
hot?: boolean,
product?: string,
domain?: string,
cdn?: string,
useReact?: boolean,
externals?: Array<any>,
runtime?: string,
alias?: any,
babelrcPath?: string,
babelrc?:boolean,
enableE2ETest: boolean,
devtool: string
}
export interface LoaderObj {
test?: object,
use?: object | Array<any>,
loader?: any,
options: LoaderObjOptions,
include?: string,
exclude?: string
}
export interface LoaderObjOptions{
[propName: string]: any
}
interface String {
endsWith(searchString: string, endPosition?: number): boolean;
};
// 最基础的配置
const baseConfig = {
target: 'web',
cache: true,
entry: glob.sync(path.join(projectRoot, './src/pages/*')),
module: {
rules: []
},
output: '',
plugins: [],
resolve: {
alias: glob.sync(path.join(projectRoot, './src/*/')) // 支持Webpack import绝对路径的写法
},
resolveLoader: {},
// 对体积过大的包进行提示
performance: {
hints: 'warning', // enum
maxAssetSize: 200000, // int (in bytes),
maxEntrypointSize: 400000, // int (in bytes)
assetFilter: function (assetFilename: String): boolean {
// Function predicate that provides asset filenames
return assetFilename.endsWith('.css') || assetFilename.endsWith('.js')
}
}
};
const PATHS = {
src: path.join(projectRoot, 'src')
};
class Builder {
/**
* @function createDevConfig
* @desc 创建用于开发过程中的webpack打包配置
*
* @param {Object} options 参数
* @param {Boolean} options.usePx2rem 是否启用px2rem
* @param {Number} options.remUnit px2rem的单位, 默认75
* @param {Number} options.remPrecision px2rem的精度,默认8
* @param {Number} options.port webpack打包的端口号,默认8001
* @param {String} options.inject 是否注入chunks
* @param {Boolean} options.inlineCSS 是否注入inline打包出来的css
* @param {String} options.babelrcPath 指定babelrc配置路径
*
* @example
*/
static createDevConfig(options: BuilderOptions): BaseConfig {
const devConfig: BaseConfig = deepCopy(baseConfig);
devConfig.mode = 'development';
// 设置打包规则
const devRules: Array<any> = [];
// 设置HTML解析规则
devRules.push(this.setHtmlRule());
// 设置图片解析规则
devRules.push(this.setImgRule(false));
// 设置CSS解析规则
devRules.push(this.setCssRule());
// 设置使用CSS Modules的CSS解析规则
devRules.push(this.setCssModulesRule());
// 设置Less解析规则,开发环境开启css-hot-loader
devRules.push(this.setLessRule(true, options.usePx2rem, options.remUnit, options.remPrecision));
// 设置使用CSS Modules的Less解析规则,开发环境开启css-hot-loader
devRules.push(this.setLessModulesRule(true, options.usePx2rem, options.remUnit, options.remPrecision));
// 设置JS解析规则
devRules.push(this.setJsRule(options.babelrcPath, options.babelrc));
// 设置TS解析规则
devRules.push(this.setTsRule());
// 设置字体解析规则
devRules.push(this.setFontRule());
// 启用端对端测试的特殊模式
if (options.enableE2ETest) {
devRules.push(this.setE2ETestRule());
devConfig.devtool = 'sourcemap';
} else {
devConfig.devtool = 'inline-source-map';
}
// 设置打包插件
let devPlugins: Array<any> = [];
devPlugins.push(new StringReplaceWebpackPlugin());
// 设置提取CSS为一个单独的文件的插件
devPlugins.push(this.setMiniCssExtractPlugin(false, ''));
if (options.useReact !== false) {
// React, react-dom 通过cdn引入
devPlugins.push(this.setExternalPlugin(options.externals));
}
// 增加热更新组件
devPlugins.push(new webpack.HotModuleReplacementPlugin());
// 抽离公共js
// devPlugins.push(this.setCommonsChunkPlugin());
// 多页面打包
// 开发环境不使用inlineCss,保证css热更新功能
const {newEntry, htmlWebpackPlugins, cssInlinePlugins} = this.setMultiplePage(devConfig.entry, false, options.inject, false, '', '');
devPlugins = devPlugins.concat(htmlWebpackPlugins, cssInlinePlugins);
devConfig.entry = newEntry;
// 开发阶段增加sourcemap.
// 这里还是依然按照原来的配置,将静态资源用根目录伺服
devConfig.output = this.setOutput(false, '', '/', options.outDir);
devConfig.module.rules = devRules;
devConfig.plugins = devPlugins;
devConfig.devServer = this.setDevServer(options.port || 8001);
devConfig.resolve.alias = this.setAlias(options.alias);
devConfig.resolve.extensions = ['.js', '.jsx', '.ts', '.tsx', '.json'];
// 设置 loader 的npm包查找的相对路径,包括本地node_modules、.feflow、测试环境的node_module
devConfig.resolveLoader = this.setResolveLoaderPath(options.runtime);
return devConfig;
}
/**
* @function createProdConfig
* @desc 创建用于生产环境中的webpack打包配置
*
* @param {Object} options 参数
* @param {Boolean} options.minifyHTML 是否压缩HTML
* @param {Boolean} options.minifyCSS 是否压缩CSS
* @param {Boolean} options.minifyJS 是否压缩JS
* @param {Boolean} options.usePx2rem 是否启用px2rem
* @param {Number} options.remUnit px2rem的单位, 默认75
* @param {Number} options.remPrecision px2rem的精度,默认8
* @param {String} options.moduleName 模块名称 (如果不传,则放在根目录)
* @param {String} options.bizName 业务名称
* @param {String} options.inject 是否注入chunks
* @param {Boolean} options.inlineCSS 是否注入inline打包出来的css
* @param {String} options.babelrcPath 指定babelrc配置路径
* @example
*/
static createProdConfig(options: BuilderOptions): BaseConfig {
const prodConfig: BaseConfig = deepCopy(baseConfig);
prodConfig.mode = 'production';
const bizName: string | undefined = options.bizName;
const moduleName: string | undefined = options.moduleName;
// 业务域名
const domain: string = options.domain || 'now.qq.com';
const cdn: string = options.cdn || '11.url.cn';
const product: string = options.product || 'now';
// Html 路径前缀, 打包时的目录
const htmlPrefix: string = moduleName ? `../../webserver/${bizName}` : '../webserver';
// Css, Js, Img等静态资源路径前缀, 打包时的目录
const assetsPrefix: string = moduleName ? `cdn/${bizName}` : 'cdn';
const cdnUrl: string = moduleName ? `//${cdn}/${product}/${moduleName}/${bizName}` : `//${cdn}/${product}/${bizName}`;
const serverUrl: string = moduleName ? `//${domain}/${moduleName}/${bizName}` : `//${domain}/${bizName}`;
// const regex = new RegExp(assetsPrefix + '/', 'g');
// 设置打包规则
const prodRules: Array<any> = [];
// 设置HTML解析规则
prodRules.push(this.setHtmlRule());
// 设置图片解析规则, 图片需要hash
prodRules.push(this.setImgRule(true, ''));
// 设置CSS解析规则
prodRules.push(this.setCssRule());
// 设置开启CSS Modules的CSS解析规则
prodRules.push(this.setCssModulesRule());
// 设置Less解析规则,生产环境不开启css-hot-loader
prodRules.push(this.setLessRule(false, options.usePx2rem, options.remUnit, options.remPrecision));
// 设置开启CSS Modules的Less解析规则,生产环境不开启css-hot-loader
prodRules.push(this.setLessModulesRule(false, options.usePx2rem, options.remUnit, options.remPrecision));
// 设置JS解析规则
prodRules.push(this.setJsRule(options.babelrcPath, options.babelrc));
// 设置TS解析规则
prodRules.push(this.setTsRule());
// 设置字体解析规则
prodRules.push(this.setFontRule());
// 启用端对端测试的特殊模式
if (options.enableE2ETest) {
prodRules.push(this.setE2ETestRule());
prodConfig.devtool = 'sourcemap';
}
// 设置打包插件
let prodPlugins: Array<any> = [];
// 清空Public目录插件, https://github.com/johnagan/clean-webpack-plugin/issues/17
prodPlugins.push(new CleanWebpackPlugin([options.outDir], {
root: projectRoot,
verbose: true,
dry: false
}));
prodPlugins.push(new StringReplaceWebpackPlugin());
// 设置提取CSS为一个单独的文件的插件
prodPlugins.push(this.setMiniCssExtractPlugin(true, ''));
prodPlugins.push(this.setOptimizeCssAssetsPlugin());
if (options.minifyJS) {
// 压缩JS
// webpack4 mode=production 下会默认启动 terser-webpack-plugin
}
if (options.useReact !== false) {
// React, react-dom 通过cdn引入
prodPlugins.push(this.setExternalPlugin(options.externals));
}
// 抽离公共js
/**
* 这个地方应当支持配置
*/
//prodPlugins.push(this.setCommonsChunkPlugin());
// 支持Fis3的 inline 语法糖 多页面打包, 默认压缩html
const {newEntry, htmlWebpackPlugins, cssInlinePlugins} = this.setMultiplePage(prodConfig.entry, options.minifyHTML, options.inject, options.inlineCSS, assetsPrefix, htmlPrefix);
prodPlugins = prodPlugins.concat(htmlWebpackPlugins, cssInlinePlugins);
if (options.useSri !== false) {
// 给生成出来的js bundle增加跨域头(cross-origin),便于错误日志记录
prodPlugins.push(this.setSriPlugin());
}
prodPlugins.push(this.setOffline(assetsPrefix, htmlPrefix, cdnUrl, serverUrl, domain, cdn, product, options.outDir));
prodConfig.entry = newEntry;
prodConfig.output = this.setOutput(true, assetsPrefix, cdnUrl + '/', options.outDir);
prodConfig.module.rules = prodRules;
prodConfig.plugins = prodPlugins;
prodConfig.bail = true;
prodConfig.resolve.alias = this.setAlias(options.alias);
prodConfig.resolve.extensions = ['.js', '.jsx', '.ts', '.tsx', '.json'];
// 设置 loader 的npm包查找的相对路径,此处设置在全局的 .feflow 目录下
prodConfig.resolveLoader = this.setResolveLoaderPath(options.runtime);
return prodConfig;
}
/**
* 设置打包后的输出 output 内容
* @param useHash 是否开启JS资源hash
* @param pathPrefix JS的前缀, 不传入则为空
* @param publicPath
* @returns {{filename: string, path: string, publicPath: *}}
* @private
*/
static setOutput(useHash: boolean, pathPrefix: string, publicPath: string, outDir: string | object) {
let hash = '';
outDir = outDir || 'public';
if (useHash) {
hash = '_[chunkhash:8]';
}
return {
filename: `[name]${hash}.js?_bid=152`,
path: path.join(projectRoot, `${outDir}/${pathPrefix}`),
publicPath: publicPath,
crossOriginLoading: 'anonymous'
};
}
/**
* 设置图片解析规则
* @param useHash 是否开启图片资源hash
* @param pathPrefix 图片的前缀,不传入则为空
* @returns {{test: RegExp, use: {loader: string, options: {name: string}}}}
* @private
*/
static setImgRule(useHash: boolean, pathPrefix?: string) {
let filename = '';
let hash = '';
if (pathPrefix) {
filename = pathPrefix + '/';
}
if (useHash) {
hash = '_[hash:8]';
}
return {
test: /\.(png|svg|jpg|gif|blob)$/,
use: {
loader: 'inline-file-loader',
options: {
name: `${filename}img/[name]${hash}.[ext]`
}
}
};
}
/**
* 设置字体解析规则
*/
static setFontRule() {
return {
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: {
loader: 'file-loader'
}
};
}
/**
* 设置 Html 文件解析规则
* 支持 Fis3 的 ?inline 语法糖
*
* @returns {{test: RegExp, use: Array}}
* @private
*/
static setHtmlRule() {
const htmlRuleArray: Array<any> = [];
htmlRuleArray.push({
loader: 'html-loader',
options: {
// 支持 html `${}` 语法
interpolate: 1,
attrs: [':src']
}
});
// Fis3 inline 语法糖支持
htmlRuleArray.push({
loader: 'replace-text-loader',
options: {
rules: [
{
// inline script, 匹配所有的<script src="package?__inline"></script> 需要inline的标签
// 并且替换为
// <script>${require('raw-loader!babel-loader!../../node_modules/@tencent/report
// - whitelist')}</script> 语法
pattern: /<script.*?src="(.*?)\?__inline".*?>.*?<\/script>/gmi,
replacement: (source: string): string => {
// 找到需要 inline 的包
const result = /<script.*?src="(.*?)\?__inline"/gmi.exec(source);
const pkg = result && result[1];
return "<script>${require('raw-loader!babel-loader!" + pkg + "')}</script>";
}
}, {
// inline html, 匹配<!--inline[/assets/inline/meta.html]-->语法
pattern: /<!--inline\[.*?\]-->/gmi,
replacement: (source: string): string => {
// 找到需要 inline 的包
const result = /<!--inline\[(.*?)\]-->/gmi.exec(source);
let path = result && result[1];
if (path && path[0] === '/') {
path = '../..' + path;
}
return "${require('raw-loader!" + path + "')}";
}
}
]
}
});
return {test: /index\.html$/, use: htmlRuleArray}
}
/**
* 样式文件正则
*/
static cssRegex = /\.css$/;
static cssModulesRegex = /\.module\.css$/;
static lessRegex = /\.less$/;
static lessModulesRegex = /\.module\.less$/;
/**
* 设置CSS解析规则
*/
static setCssRule() {
return {
test: Builder.cssRegex,
exclude: Builder.cssModulesRegex,
use: ['style-loader', 'css-loader']
}
}
/**
* 设置使用CSS Modules的CSS解析规则
*/
static setCssModulesRule() {
return {
test: Builder.cssModulesRegex,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
getLocalIdent: getCSSModulesLocalIdent
}
}
]
}
}
/**
* 设置Less文件解析规则
*
* @param useHotLoader 是否使用css-hot-loader
* @param usePx2rem 是否使用px2rem loader
* @param remUnit rem单位,默认75
* @param remPrecision rem精度, 默认8
* @returns {{test: RegExp, use: *}}
* @private
*/
static setLessRule(useHotLoader: boolean, usePx2rem: boolean, remUnit: number, remPrecision: number) {
const cssRuleArray: Array<LoaderObj>= [];
if (useHotLoader) {
cssRuleArray.push({
loader: 'css-hot-loader',
options: {}
});
}
cssRuleArray.push({
loader: MiniCssExtractPlugin.loader,
options: {}
});
// 加载Css loader, 判断是否开启压缩
const cssLoaderRule = {
loader: "css-loader",
options: {}
};
cssRuleArray.push(cssLoaderRule);
// 如果开启px2rem,则加载px2rem-loader
if (usePx2rem) {
cssRuleArray.push({
loader: "px2rem-loader",
options: {
remUnit: remUnit || 75,
remPrecision: remPrecision || 8
}
});
}
// css 前缀,兼容低版本浏览器
cssRuleArray.push({
loader: 'postcss-loader',
options: {
plugins: () => [
require('autoprefixer')({
overrideBrowserslist: ["last 2 version", "> 1%", "iOS 7"]
})
]
}
});
// 雪碧图loader
cssRuleArray.push({
loader: "sprites-loader",
options: {}
});
// 加载解析less的less-loader
cssRuleArray.push({
loader: "less-loader",
options: {
includePaths: [path.join(projectRoot, "./src")]
}
});
return {
test: Builder.lessRegex,
exclude: Builder.lessModulesRegex,
use: cssRuleArray
};
}
/**
* 设置使用CSS Modules的Less文件解析规则
*
* @param useHotLoader 是否使用css-hot-loader
* @param usePx2rem 是否使用px2rem loader
* @param remUnit rem单位,默认75
* @param remPrecision rem精度, 默认8
* @returns {{test: RegExp, use: *}}
* @private
*/
static setLessModulesRule(useHotLoader: boolean, usePx2rem: boolean, remUnit: number, remPrecision: number) {
const cssRuleArray: Array<LoaderObj>= [];
if (useHotLoader) {
cssRuleArray.push({
loader: 'css-hot-loader',
options: {}
});
}
cssRuleArray.push({
loader: MiniCssExtractPlugin.loader,
options: {}
});
// 加载Css loader, 开启Css Modules
const cssLoaderRule = {
loader: "css-loader",
options: {
modules: true,
getLocalIdent: getCSSModulesLocalIdent
}
};
cssRuleArray.push(cssLoaderRule);
// 如果开启px2rem,则加载px2rem-loader
if (usePx2rem) {
cssRuleArray.push({
loader: "px2rem-loader",
options: {
remUnit: remUnit || 75,
remPrecision: remPrecision || 8
}
});
}
// css 前缀,兼容低版本浏览器
cssRuleArray.push({
loader: 'postcss-loader',
options: {
plugins: () => [
require('autoprefixer')({
overrideBrowserslist: ["last 2 version", "> 1%", "iOS 7"]
})
]
}
});
// 雪碧图loader
cssRuleArray.push({
loader: "sprites-loader",
options: {}
});
// 加载解析less的less-loader
cssRuleArray.push({
loader: "less-loader",
options: {
includePaths: [path.join(projectRoot, "./src")]
}
});
return {
test: Builder.lessModulesRegex,
use: cssRuleArray
};
}
/**
* 设置Js文件解析规则, 此处使用happypack,多实例构建
* @param babelrc 是否搜索相关的babel类型的配置文件,并和现有的babel文件进行合并
* @returns {{test: RegExp, loader: string}}
* @private
*/
static setJsRule(babelrcPath,babelrc: boolean = true) {
return {
test: /\.jsx?$/, // 支持jsx
include: path.join(projectRoot, 'src'),
use: [
{
loader: 'thread-loader',
options: {
workers: 3
}
},
{
loader: 'babel-loader',
options: {
// babel默认查找根目录下的babel.config.js作为全局配置,除非在此选项强制指定;
// 且此选项不会影响加载.babelrc,参考:https://babeljs.io/docs/en/options#configfile
configFile: babelrcPath && path.join(process.cwd(), babelrcPath),
// 是否搜索相关的babel类型的配置文件,并和现有的babel文件进行合并
babelrc:babelrc
}
}
]
};
}
/**
* 设置TS文件解析规则, 此处使用happypack,多实例构建
*
* @returns {{test: RegExp, loader: string}}
* @private
*/
static setTsRule() {
return {test: /\.ts(x?)$/, loader: 'happypack/loader', exclude: path.join(projectRoot, 'node_modules')};
}
/**
* 设置提取Css资源的插件
* @param useHash 是否开启图片资源hash
* @param pathPrefix CSS的前缀,不传入则为空
* @private
*/
static setMiniCssExtractPlugin(useHash: boolean, pathPrefix: string) {
let filename = '';
let hash = '';
if (pathPrefix) {
filename = pathPrefix + '/';
}
if (useHash) {
hash = '_[contenthash:8]';
}
return new MiniCssExtractPlugin({
filename: `${filename}[name]${hash}.css`
});
}
/**
* 设置端对端测试的一些规则
*
* @returns {Object}
* @private
*/
static setE2ETestRule() {
return {
test: /\.js$/,
use: {
loader: 'istanbul-instrumenter-loader',
options: {esModules: true}
},
enforce: 'post',
exclude: /node_modules|.\spec\.js$/,
};
}
static setOptimizeCssAssetsPlugin() {
return new OptimizeCssAssetsPlugin({
assetNameRegExp: /\.css$/g,
cssProcessor: require('cssnano')
});
}
/**
* 不把React, react-dom打到公共包里,并在html插入cdn资源
* @private
*/
static setExternalPlugin(externals) {
const newExternals = externals || [
{
module: 'react',
entry: '//11.url.cn/now/lib/16.2.0/react.min.js?_bid=3123',
global: 'React'
}, {
module: 'react-dom',
entry: '//11.url.cn/now/lib/16.2.0/react-dom.min.js?_bid=3123',
global: 'ReactDOM'
}
];
return new HtmlWebpackExternalsPlugin({externals: newExternals});
}
/**
* 多页面打包
* @param entries glob的entry路径
* @param minifyHtml 是否压缩html
* @param inject 是否自动注入打包出来的js和css
* @param inlineCSS 是否inline打包出来的css
* @param assetsPrefix Css, Js, img的路径前缀
* @param htmlPrefix Html的路径前缀
* @returns {{newEntry: {}, htmlWebpackPlugins: Array}}
* @private
*/
static setMultiplePage(entries: string | object, minifyHtml: boolean, inject: boolean, _inlineCSS: boolean, _assetsPrefix: string, htmlPrefix?: string) {
const newEntry = {};
const htmlWebpackPlugins: Array<any> = [];
const cssInlinePlugins: Array<any> = [];
Object
.keys(entries)
.map((index) => {
const entry = entries[index];
/**
* TODO: 这个地方会不会太强业务相关了?
*/
const entryFile = `${entry}/init.js`;
// 支持 init.js 文件不是必须存在的场景,纯html
const isEntryFileExists = fs.existsSync(entryFile);
const match = entry.match(/\/pages\/(.*)/);
const pageName = match && match[1];
let filename = '';
if (htmlPrefix) {
filename = htmlPrefix + '/';
}
if (isEntryFileExists) {
newEntry[pageName] = entryFile;
}
htmlWebpackPlugins.push(new HtmlWebpackPlugin({
template: path.join(projectRoot, `src/pages/${pageName}/index.html`),
filename: `${filename}${pageName}.html`,
chunks: [pageName],
// assetsPrefix: `${assetsPrefix}/`,
inject: inject && isEntryFileExists,
minify: minifyHtml
? {
html5: true,
collapseWhitespace: true,
preserveLineBreaks: false,
minifyCSS: true,
minifyJS: true,
removeComments: false
}
: false
}));
// Inline 生成出来的css
if (_inlineCSS) {
let pageName = path.normalize(entry).split(path.sep).pop();
if (pageName) {
cssInlinePlugins.push(new HTMLInlineCSSWebpackPlugin({
filter(fileName) {
let cssFileName = fileName;
if (/\.css$/.test(fileName)) {
// file的hash默认是8个,如果另外定义数量请注意修改这里的截取位置(MiniCssExtractPlugin中)
cssFileName = fileName.slice(0, fileName.length - 13);
}
return (pageName === cssFileName) || new RegExp(`${pageName}\.html$`).test(fileName);
}
}));
}
}
});
return {newEntry, htmlWebpackPlugins, cssInlinePlugins};
}
/**
* 给生成的 js bundle文件增加 SRI 资源校验,防止CDN劫持
* @returns {SriPlugin}
* @private
*/
static setSriPlugin() {
return new SriPlugin({
hashFuncNames: ['sha256', 'sha384']
});
}
/**
* 离线包打包逻辑
* @param assetsPrefix CSS、Img、JS等打包路径前缀
* @param htmlPrefix Html打包路径前缀
* @param cdnUrl CDN路径
* @param serverUrl now.qq.com路径
* @param domain 域名
* @param cdn cdn路径
* @param product cdn对应的产品
* @private
*/
static setOffline(assetsPrefix: string, htmlPrefix: string, _cdnUrl: string, serverUrl: string, domain: string, cdn: string, product: string, outDir: string | object) {
outDir = outDir || 'public';
return new OfflineWebpackPlugin({
path: path.join(projectRoot, `./${outDir}/offline`),
filename: 'offline.zip',
pathMapper: (assetPath: string) => {
if (assetPath.indexOf(htmlPrefix) !== -1) {
// 所有资源都改成 now.qq.com 的域名, 防止跨域问题
assetPath = assetPath.replace(htmlPrefix, '');
} else if (assetPath.indexOf(assetsPrefix) !== -1) {
assetPath = assetPath.replace(assetsPrefix, '');
}
return path.join(serverUrl.replace('//', ''), assetPath);
},
beforeAddBuffer(source: string, assetPath: string) {
if (assetPath.indexOf(htmlPrefix) !== -1) {
// 基础包域名修改, 防止跨域问题
source = source.replace(/\/\/11\.url\.cn\/now\/([^"'\)\`]+)(["'\`\)])/g, `//${domain}/$1$2`);
// 业务资源的域名修改, 防止跨域问题
const regex = new RegExp(`//${cdn}/${product}/([^"'\)\`]+)(["'\`\)])`, 'g');
source = source.replace(regex, `//${domain}/$1$2`);
// 去掉 crossorigin="annoymous"
source = source.replace(/crossorigin=\"anonymous\"/g, '');
// 去掉 业务 js 文件的 ?_bid=152
source = source.replace(/\?_bid=152/g, '');
// 去掉业务 js 上的 integrity 属性
source = source.replace(/(<script.*)integrity=".*?"/g, '$1');
// 注入离线包的版本号. pack
const inject = {
version: Date.now()
};
source = source.replace(/(<script)/, '<script>var pack = ' + JSON.stringify(inject) + '</script>$1');
}
return source;
}
})
}
/**
* Code split, 提取出公共js文件,避免每个页面重复打包
*/
// static setCommonsChunkPlugin() {
// return new webpack.optimize.CommonsChunkPlugin({
// name: 'common'
// });
// }
/**
* 设置dev server,WDS配置
* @param port
* @returns {{contentBase: string, inline: boolean, historyApiFallback: boolean, disableHostCheck: boolean, port: *}}
* @private
*/
static setDevServer(port: number) {
return {
contentBase: path.join(projectRoot, './src'),
inline: true,
historyApiFallback: false,
disableHostCheck: true,
port: port
};
}
/**
* 设置引用的Alias路径匹配规则,以src下面的目录为根目录
* TODO: 这个地方是否可以替代css绝对路径的问题
* 支持import TitleBar from "/modules/components/titlebar" 绝对路径语法
* @param alias 用户自定义的alias
*
* @private
*/
static setAlias(alias?: any) {
const aliasObject = {};
listDir(path.join(projectRoot, './src'), 1, []).forEach((dir) => {
const {name, dirPath} = dir;
aliasObject['/' + name] = dirPath;
aliasObject[name] = dirPath;
});
if (isEmpty(alias)) {
return aliasObject;
}
return merge(alias, aliasObject);
}
/**
* 设置Loader的path查找的目录
* 目前已把本builder的node_modules也引入
* 好处是:把构建器放在 ./feflow 目录下,多个项目可以公用一个构建器,便于构建器的增量更新和统一升级
*/
static setResolveLoaderPath(runtime?: string): object {
const jbRuntime = runtime || 'runtime-now-6';
const resolveLoaderPath = path.join(osenv.home(), './.feflow/node_modules');
// Loader在捷豹平台的查找路径
const jbLoaderPath = `/data/frontend/install/AlloyDist/${jbRuntime}/node_modules`;
return {
modules: [
path.resolve(__dirname, "../node_modules"),
resolveLoaderPath,
jbLoaderPath,
]
};
}
}
export default Builder; | the_stack |
import {getDefaultSlicingSpec} from './shape-utils';
import {Shape, TensorViewSlicingSpec} from './types';
export type OnSlicingSpecChangeCallback = (
slicingSpec: TensorViewSlicingSpec
) => void;
/**
* UI control for
* - selecting which dimensions to slicing down to 1 and which to view
* as a 2D data table.
* - which index to select within each sliced dimension.
*
* Used for tensors with rank (dimensionality) 3 or higher.
*/
export class SlicingControl {
private readonly rank: number;
// The current slicing spec.
private slicingSpec: TensorViewSlicingSpec;
// Constituent UI components.
private dimControls: HTMLDivElement[] = [];
// Input elements for selecting the slices in sliced dimensions.
private dimInputs: HTMLInputElement[] = [];
// Displayed commas.
private commas: HTMLDivElement[] = [];
// Dropdown mini-menus to allow swapping a viewed dimension with another
// dimension.
private dropdowns: HTMLDivElement[] = [];
// Static divs that display brackets ("[" and "]") on the two sides.
private readonly bracketDivs: [HTMLDivElement | null, HTMLDivElement | null] =
[null, null];
private dimControlsListenerAttached: boolean[] = [];
/**
* Constructor of SlicingControl.
*
* @param rootDiv The div element in which all the UI components will be
* rendered.
* @param shape Shape of the tensor.
* @param onSlicingSpecChange User specified callback for slicing spec changes
* triggered by user interactions with this SlicingControl. The callback
* will be invoked for changes in:
* - which dimensions are used for slicing and which for viewing
* - the selected index within a slicing dimension.
*/
constructor(
private readonly rootDiv: HTMLDivElement,
private readonly shape: Shape,
private readonly onSlicingSpecChange: OnSlicingSpecChangeCallback = () => {}
) {
this.rank = this.shape.length;
if (this.rank < 3) {
throw new Error(
`Dimension control is not applicable to tensor shapes less than ` +
`3D: received ${this.rank}D tensor shape: ` +
`${JSON.stringify(this.shape)}.`
);
}
this.createComponents();
this.slicingSpec = getDefaultSlicingSpec(shape);
}
/**
* Create all UI components of this SlicingControl.
*
* The detailed contents of the components are not filled in. Those are filled
* in when the `render()` method is called.
*/
private createComponents() {
// Clear the dim group.
while (this.rootDiv.firstChild) {
this.rootDiv.removeChild(this.rootDiv.firstChild);
}
this.dimControls = [];
this.dimInputs = [];
this.commas = [];
this.dropdowns = [];
this.dimControlsListenerAttached = [];
// Create the div elements for the brackets and the dim controls.
this.bracketDivs[0] = document.createElement('div');
this.bracketDivs[0].textContent = 'Slicing: [';
this.bracketDivs[0].classList.add('tensor-widget-dim-brackets');
this.rootDiv.appendChild(this.bracketDivs[0]);
for (let i = 0; i < this.rank; ++i) {
const dimControl = document.createElement('div');
dimControl.classList.add('tensor-widget-dim');
dimControl.title = `Dimension ${i}: size=${this.shape[i]}`;
this.rootDiv.appendChild(dimControl);
this.dimControls.push(dimControl);
this.dimControlsListenerAttached.push(false);
const dimInput = document.createElement('input');
dimInput.classList.add('tensor-widget-dim');
// The dim input is initially hidden, and will be shown when the
// corresponding dim control is clicked.
dimInput.style.display = 'none';
this.rootDiv.appendChild(dimInput);
this.dimInputs.push(dimInput);
if (i < this.rank - 1) {
// Render a comma
const comma = document.createElement('div');
comma.classList.add('tensor-widget-dim-comma');
comma.textContent = ',';
this.rootDiv.appendChild(comma);
this.commas.push(comma);
}
const dropdown = document.createElement('div');
dropdown.classList.add('tensor-widget-dim-dropdown');
// The dropdown is initially hidden, and will be shown when the
// corresponding dim control is clicked.
dropdown.style.display = 'none';
this.rootDiv.appendChild(dropdown);
this.dropdowns.push(dropdown);
}
this.bracketDivs[1] = document.createElement('div');
this.bracketDivs[1].textContent = ']';
this.bracketDivs[1].classList.add('tensor-widget-dim-brackets');
this.rootDiv.appendChild(this.bracketDivs[1]);
this.rootDiv.addEventListener('mouseleave', () => {
this.clearAllDropdowns();
});
}
/**
* Re-render the slicing control according to the current slicing spec.
*/
render(slicingSpec?: TensorViewSlicingSpec) {
if (slicingSpec != null) {
this.slicingSpec = JSON.parse(
JSON.stringify(slicingSpec)
) as TensorViewSlicingSpec;
}
if (this.slicingSpec === null) {
throw new Error(
'Slicing control rendering failed due to missing slicing spec.'
);
}
const slicingDims = this.slicingSpec.slicingDimsAndIndices.map(
(dimAndIndex) => dimAndIndex.dim
);
const slicingIndices = this.slicingSpec.slicingDimsAndIndices.map(
(dimAndIndex) => dimAndIndex.index
);
for (let i = 0; i < this.rank; ++i) {
const dimControl = this.dimControls[i];
const dimInput = this.dimInputs[i];
const dropdown = this.dropdowns[i];
if (dimInput.style.display !== 'none') {
// This dimension is currently being adjusted for slicing index. Skip
// rendering.
continue;
}
const dimSize = this.shape[i];
if (slicingDims.indexOf(i) !== -1) {
// This is a dimension being sliced down to a size of 1.
const currentIndex = slicingIndices[slicingDims.indexOf(i)];
dimControl.textContent = String(currentIndex);
dimInput.classList.add('tensor-widget-dim');
dimInput.type = 'number';
dimInput.min = '0';
dimInput.max = String(dimSize - 1);
dimInput.value = String(currentIndex);
// When the dim control is clicked, it becomes a number input.
if (!this.dimControlsListenerAttached[i]) {
dimControl.addEventListener('click', () => {
this.clearAllDropdowns();
dimControl.style.display = 'none';
dimInput.style.display = 'inline-block';
});
// Set change callback for the dim input.
dimInput.addEventListener('change', () => {
if (this.slicingSpec === null) {
throw new Error(
'Slicing control change callback failed due to missing spec.'
);
}
const newIndex = parseInt(dimInput.value, 10);
if (
!isFinite(newIndex) ||
newIndex < 0 ||
newIndex >= dimSize ||
Math.floor(dimSize) != dimSize
) {
// Reject invalid value.
dimInput.value = String(
this.slicingSpec.slicingDimsAndIndices[slicingDims.indexOf(i)]
.index
);
return;
}
this.slicingSpec.slicingDimsAndIndices[
slicingDims.indexOf(i)
].index = newIndex;
dimControl.textContent = String(newIndex);
this.onSlicingSpecChange(this.slicingSpec);
});
// When defocusing (blurring) from the dim input, it changes back into
// a static div.
dimInput.addEventListener('blur', () => {
dimInput.style.display = 'none';
dimControl.style.display = 'inline-block';
});
this.dimControlsListenerAttached[i] = true;
}
} else {
if (this.slicingSpec.viewingDims[0] === i) {
// This is a dimension being viewed as the vertical (rows) dimension.
if (this.slicingSpec.verticalRange === null) {
throw new Error('Missing vertical range.');
}
dimControl.textContent =
`↕ ${this.slicingSpec.verticalRange[0]}:` +
`${this.slicingSpec.verticalRange[1]}`;
} else {
// This is a dimension being viewed as the horizontal (columns)
// dimension.
if (this.slicingSpec.horizontalRange === null) {
throw new Error('Missing horizontal range.');
}
dimControl.textContent =
`↔ ${this.slicingSpec.horizontalRange[0]}:` +
`${this.slicingSpec.horizontalRange[1]}`;
}
dimControl.classList.add('tensor-widget-dim');
if (!this.dimControlsListenerAttached[i]) {
dimControl.addEventListener('click', () => {
const rect = dimControl.getBoundingClientRect();
const top = rect.bottom;
const left = rect.left;
this.renderDropdownMenuItems(dropdown, top, left, i);
});
this.dimControlsListenerAttached[i] = true;
}
}
}
}
/**
* Render items in a viewing dimension's dropdown menu.
*
* The rendering is based on what dimension swappings are possible.
* The dropdown menu will be shown if it is non-empty after the menu items are
* populated.
*
* @param dropdown
* @param top The top coordinate of the menu.
* @param left The left coordinate of the menu.
* @param dim The dimension that the viewing dimension belongs to. E.g., `0`
* for the first dimension.
*/
private renderDropdownMenuItems(
dropdown: HTMLDivElement,
top: number,
left: number,
dim: number
) {
if (this.slicingSpec === null) {
throw new Error(
'Slicing control cannot render dropdown menu items due to missing ' +
'slicing spec.'
);
}
// Clear all dropdown menus. Make sure that at any moment, only one dropdown
// menu is open.
this.clearAllDropdowns();
const slicingDims = this.slicingSpec.slicingDimsAndIndices.map(
(dimAndIndex) => dimAndIndex.dim
);
for (let i = 0; i < this.rank; ++i) {
// Create "Swap with" menu items only with slicing dimensions, i.e., not
// with viewing dimensions.
if (slicingDims.indexOf(i) === -1) {
continue;
}
// Also, do not allow the second (columns) viewing dimension to be before
// the first one.
if (
(dim === this.slicingSpec.viewingDims[1] &&
i <= this.slicingSpec.viewingDims[0]) ||
(dim == this.slicingSpec.viewingDims[0] &&
i >= this.slicingSpec.viewingDims[1])
) {
continue;
}
const menuItem = document.createElement('div');
menuItem.classList.add('tensor-widget-dim-dropdown-menu-item');
menuItem.textContent = `Swap with dimension ${i}`;
dropdown.appendChild(menuItem);
menuItem.addEventListener('mouseenter', () => {
menuItem.classList.add('tensor-widget-dim-dropdown-menu-item-active');
this.dimControls[i].classList.add('tensor-widget-dim-highlighted');
});
menuItem.addEventListener('mouseleave', () => {
menuItem.classList.remove(
'tensor-widget-dim-dropdown-menu-item-active'
);
this.dimControls[i].classList.remove('tensor-widget-dim-highlighted');
});
const isFirstViewingDim = this.slicingSpec.viewingDims[0] === dim;
menuItem.addEventListener('click', () => {
if (this.slicingSpec === null) {
throw new Error(
'Dimension swapping failed due to missing slicing spec'
);
}
const k = slicingDims.indexOf(i);
this.slicingSpec.viewingDims[isFirstViewingDim ? 0 : 1] = i;
this.slicingSpec.slicingDimsAndIndices[k] = {
dim,
index: 0,
};
this.slicingSpec.verticalRange = null;
this.slicingSpec.horizontalRange = null;
if (this.onSlicingSpecChange) {
this.onSlicingSpecChange(this.slicingSpec);
}
});
}
dropdown.addEventListener('mouseleave', () => {
dropdown.style.display = 'none';
});
// Show the dropdown menu if and only if it is non-empty.
if (dropdown.firstChild) {
dropdown.style.position = 'fixed';
dropdown.style.top = `${top}px`;
dropdown.style.left = `${left}px`;
dropdown.style.display = 'block';
// Check the actual position of the dropdown menu and make sure
// that it's actually aligned with the dim control.
// TODO(cais): Investigate for the offset in the Debugger Plugin
// and whether there is a way to avoid the hacky repositioning below.
const actualRect = dropdown.getBoundingClientRect();
const topOffset = actualRect.top - top;
const leftOffset = actualRect.left - left;
dropdown.style.top = (top - topOffset).toFixed(1) + 'px';
dropdown.style.left = (left - leftOffset).toFixed(1) + 'px';
}
}
/**
* Set the slicing spec externally.
*
* This will trigger a re-rendering of the SlicingControl's UI components,
* which will reflect the input slicing spec's value.
*
* @param slicingSpec The externally-set slicing spec. It will not be mutated
* by SlicingControl.
*/
setSlicingSpec(slicingSpec: TensorViewSlicingSpec) {
this.slicingSpec = JSON.parse(
JSON.stringify(slicingSpec)
) as TensorViewSlicingSpec;
if (this.slicingSpec === null) {
throw new Error('Cannot set slicing spec to null.');
}
this.render(this.slicingSpec);
}
private clearAllDropdowns() {
this.dropdowns.forEach((dropdown) => {
if (dropdown != null) {
while (dropdown.firstChild) {
dropdown.removeChild(dropdown.firstChild);
}
dropdown.style.display = 'none';
}
});
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.