text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import * as React from 'react';
import * as ReactDom from "react-dom";
import styles from './FollowDocumentWebPart.module.scss';
import { IFollowDocumentWebPartProps } from './IFollowDocumentWebPartProps';
import { IFollowDocumentWebPartState } from './IFollowDocumentWebPartState';
import { FollowDocumentGrid } from '../components/followDocumentGrid/index';
import Rest from '../Service/Rest';
import Graph from "../Service/GraphService";
// Used to render list grid
import {
DocumentCard,
DocumentCardDetails,
DocumentCardActions,
DocumentCardTitle,
DocumentCardLocation,
DocumentCardType,
DocumentCardImage
} from 'office-ui-fabric-react/lib/DocumentCard';
import { WebPartTitle } from "@pnp/spfx-controls-react/lib/WebPartTitle";
import { followDocumentPreview } from './followDocumentPreview/followDocumentPreview';
import { IfollowDocumentPreviewProps } from './followDocumentPreview/IfollowDocumentPreviewProps';
import FollowDocumentDialog from './followDocumentDialog/followDocumentDialog';
import { followType } from '../util/followType';
import { ImageFit } from 'office-ui-fabric-react/lib/Image';
import { ISize } from 'office-ui-fabric-react/lib/Utilities';
import { Spinner, SpinnerSize } from 'office-ui-fabric-react/lib/Spinner';
import { Dropdown, IDropdownOption } from 'office-ui-fabric-react/lib/Dropdown';
import { IconButton } from 'office-ui-fabric-react/lib/Button';
import { SearchBox } from 'office-ui-fabric-react/lib/SearchBox';
import { Stack, IStackTokens } from 'office-ui-fabric-react/lib/Stack';
const stackTokens: Partial<IStackTokens> = { childrenGap: 20 };
export default class FollowDocumentWebPart extends React.Component<IFollowDocumentWebPartProps, IFollowDocumentWebPartState> {
private _siteId: string = null;
private _listId: string = null;
private _panelPlaceHolder: HTMLDivElement = null;
private _selectedGroup: string = "0";
constructor(props) {
super(props);
this.state = {
Items: [],
siteId: null,
listId: null,
previewImgUrl: null,
visible: true,
};
this._panelPlaceHolder = document.body.appendChild(
document.createElement("div")
);
this.getListItems();
}
private getListItems = () => {
this._selectedGroup = "0";
if (!this.state.visible) {
this.setState({
visible: true,
});
}
//Load using Graph
this.getGraphFollowedDocs();
}
//get Web Name and Web Url of Document
private getSearchWebID = async (graphData: any[], webs: any[]): Promise<any[]> => {
const graphService: Graph = new Graph();
const initialized = await graphService.initialize(this.props.context.serviceScope);
let queryString: string = "";
for (let index = 0; index < webs.length; index++) {
if (index === 0) {
queryString += "WebId:" + webs[index].replace('{', '').replace('}', '');
} else {
queryString += " OR WebId:" + webs[index].replace('{', '').replace('}', '') + " ";
}
}
if (initialized) {
const HeaderWeb = {
"requests": [
{
"entityTypes": [
"site"
],
"query": {
"queryString": "" + queryString + "",
}
}
]
};
//Retrieve webNames
const tmpWebs = await graphService.postGraphContent("https://graph.microsoft.com/beta/search/query", HeaderWeb);
graphData.forEach(element => {
tmpWebs.value[0].hitsContainers[0].hits.forEach(Webelement => {
if (element.fields.WebId.replace('{', '').replace('}', '') === Webelement.resource.id.split(/[, ]+/).pop().toUpperCase()) {
element.WebName = Webelement.resource.name;
element.WebUrl = Webelement.resource.webUrl;
}
}
);
});
return graphData;
}
}
private onActionTeamsClick = (action: any, ev: React.SyntheticEvent<HTMLElement>): void => {
const dialog: FollowDocumentDialog = new FollowDocumentDialog();
dialog.initializedTeams(action, this.props.context, followType.SendTeams);
ev.stopPropagation();
ev.preventDefault();
}
private getSearchListItemID = async (ListId: string): Promise<string> => {
const graphService: Graph = new Graph();
const initialized = await graphService.initialize(this.props.context.serviceScope);
if (initialized) {
const HeaderListId = {
"requests": [
{
"entityTypes": [
"list"
],
"query": {
"queryString": "ListID:" + ListId + ""
},
"fields": [
"webUrl"
]
}
]
};
const tmpFileID = await graphService.postGraphContent("https://graph.microsoft.com/beta/search/query", HeaderListId);
console.log(tmpFileID);
return tmpFileID.value[0].hitsContainers[0].hits[0].resource.webUrl.substring(0, tmpFileID.value[0].hitsContainers[0].hits[0].resource.webUrl.lastIndexOf("/"));
}
}
private getListItemID = async (ListID, ItemID) => {
const _ListId = await this.getSearchListItemID(ListID);
const dialog: FollowDocumentDialog = new FollowDocumentDialog();
dialog.initialize(_ListId + "/dispForm.aspx?ID=" + ItemID, followType.ViewPropreties);
}
private _showPanel = (Url: string, Title: string): void => {
this._renderPanelComponent({
context: this.props.context,
url: Url,
filename: Title,
isOpen: true,
});
}
private _renderPanelComponent = (props: IfollowDocumentPreviewProps): void => {
const element: React.ReactElement<IfollowDocumentPreviewProps> =
React.createElement(followDocumentPreview, props);
ReactDom.render(element, this._panelPlaceHolder);
}
private onActionPropertiesClick = (action: any, ev: React.SyntheticEvent<HTMLElement>): void => {
//Get Document Display Form List
this.getListItemID(action.fields.ListId.replace('{', '').replace('}', ''), action.fields.ItemId);
ev.stopPropagation();
ev.preventDefault();
}
private onActionFolderClick = (action: any, ev: React.SyntheticEvent<HTMLElement>): void => {
window.open(action.fields.Url.replace(action.fields.Title, ""), "_blank");
ev.stopPropagation();
ev.preventDefault();
}
/**
* Unfollow Option
*/
private onActionUnfollowClick = async (action: any, ev: React.SyntheticEvent<HTMLElement>) => {
ev.stopPropagation();
ev.preventDefault();
const dialog: FollowDocumentDialog = new FollowDocumentDialog();
dialog._followTypeDialog = followType.Unfollow;
dialog._filename = action.fields.Title;
dialog.show().then(async () => {
if (dialog._followDocumentState) {
const restService: Rest = new Rest();
const Status = await restService.stopfollowing(
this.props.context.spHttpClient,
action.fields.Url,
this.props.context.pageContext.web.absoluteUrl,
);
if (Status) {
dialog._followDocumentState = false;
this.getListItems();
}
}
});
}
private onActionPanelClick = async (action: any, ev: React.SyntheticEvent<HTMLElement>) => {
this._showPanel(action.fields.Url, action.fields.Title);
ev.stopPropagation();
ev.preventDefault();
}
private getGraphFollowedDocs = async () => {
const GraphService: Graph = new Graph();
let DriveItem: any = [];
if (this.state.siteId === null) {
let graphData: any = await GraphService.getGraphContent("https://graph.microsoft.com/v1.0/me/drive/list", this.props.context);
this._siteId = graphData.parentReference.siteId;
DriveItem = await this.getListID(graphData.parentReference.siteId);
} else {
if (this.state.listId === null) {
DriveItem = await this.getListID(this.state.siteId);
} else {
DriveItem = await this.getFollowDocuments(this.state.siteId, this.state.listId);
}
}
let items = [];
DriveItem.forEach(element => {
if (element.fields.IconUrl.indexOf("lg_iczip.gif") > -1) {
element.fields.IconUrl = element.fields.IconUrl.replace("lg_iczip.gif", "lg_iczip.png");
}
if (element.fields.IconUrl.indexOf("lg_icmsg.png") > -1) {
element.fields.IconUrl = element.fields.IconUrl.replace("lg_icmsg.png", "lg_icmsg.gif");
}
items.push({
thumbnail: element.previewImg,
title: element.fields.Title,
profileImageSrc: element.fields.IconUrl,
url: (element.fields.ServerUrlProgid === undefined ? element.fields.Url : element.fields.ServerUrlProgid.substring(1)),
webName: element.WebName,
webUrl: element.WebUrl,
documentCardActions: [
{
iconProps: { iconName: 'TeamsLogo' },
onClick: this.onActionTeamsClick.bind(this, element),
ariaLabel: 'Send to Teams',
},
{
iconProps: { iconName: 'FabricFolder' },
onClick: this.onActionFolderClick.bind(this, element),
ariaLabel: 'open Folder',
},
{
iconProps: { iconName: 'FavoriteStarFill' },
onClick: this.onActionUnfollowClick.bind(this, element),
ariaLabel: 'Unfollow Document',
},
{
iconProps: { iconName: 'Info' },
onClick: this.onActionPropertiesClick.bind(this, element),
ariaLabel: 'Document info',
},
{
iconProps: { iconName: 'DocumentSearch' },
onClick: this.onActionPanelClick.bind(this, element),
ariaLabel: 'Preview',
},
]
});
});
let uniq = {};
let group: Array<IDropdownOption> = new Array<IDropdownOption>();
//Remove duplicated from array
let uniqueArray = [];
uniqueArray = items.filter(obj => !uniq[obj.webUrl] && (uniq[obj.webUrl] = true));
group.push({ key: '0', text: 'All Sites' });
uniqueArray.forEach(element => {
group.push({
key: element.webUrl,
text: "Site: " + element.webName,
});
});
this.setState({
Items: items,
ItemsSearch: items,
ItemsGroup: group,
visible: false,
siteId: this._siteId,
listId: this._listId
});
}
private getListID = async (siteId: string): Promise<string> => {
const GraphService: Graph = new Graph();
let graphData: any = await GraphService.getGraphContent(`https://graph.microsoft.com/v1.0/sites/${siteId}/lists?$select=id&$filter=displayName eq 'Social'`, this.props.context);
this._listId = graphData.value[0].id;
const DriveItem: string = await this.getFollowDocuments(siteId, graphData.value[0].id);
return DriveItem;
}
private getFollowDocuments = async (siteId: string, listId: string): Promise<any> => {
const GraphService: Graph = new Graph();
let graphData: any = [];
graphData = await GraphService.getGraphContent(`https://graph.microsoft.com/v1.0/sites/${siteId}/Lists/${listId}/items?expand=fields(select=ItemId,ListId,SiteId,webId,Title,Url,ServerUrlProgid,IconUrl,File_x0020_Type.progid)&$filter=fields/ItemId gt -1`, this.props.context);
graphData.value = graphData.value.sort((a, b) => {
return b.id - a.id;
});
//Get Web site Name
graphData = await this.getFollowDocumentsWebName(graphData);
return graphData;
}
private getFollowDocumentsWebName = async (graphData) => {
let _webs = [];
graphData.value.forEach(element => {
if (_webs.indexOf(element.fields.WebId) === -1) {
_webs.push(element.fields.WebId);
}
});
graphData = await this.getSearchWebID(graphData.value, _webs);
return graphData;
}
public render(): React.ReactElement<IFollowDocumentWebPartProps> {
//Filter Search Text
const checkSearchDrive = (SearchQuery: string) => {
let items = [];
if (this._selectedGroup === "0") {
items = this.state.Items.filter(item => (item.title.toLowerCase().indexOf(SearchQuery.toLowerCase()) > -1));
} else {
items = this.state.Items.filter(item => (item.title.toLowerCase().indexOf(SearchQuery.toLowerCase()) > -1 && item.webUrl.toLowerCase().indexOf(this._selectedGroup.toLowerCase()) > -1));
}
this.setState({
ItemsSearch: items,
});
};
const checkClear = (ev: any) => {
let items = [];
if (this._selectedGroup === "0") {
items = this.state.Items;
} else {
items = this.state.Items.filter(item => (item.webUrl.toLowerCase().indexOf(this._selectedGroup.toLowerCase()) > -1));
}
this.setState({
ItemsSearch: items,
});
};
const filterall = (event: React.FormEvent<HTMLDivElement>, selectedOption: IDropdownOption) => {
this._selectedGroup = selectedOption.key.toString();
if (selectedOption.key.toString() === "0") {
this.setState({
ItemsSearch: this.state.Items,
});
} else {
const items = this.state.Items.filter(item => item.webUrl.toLowerCase().indexOf(selectedOption.key.toString().toLowerCase()) > -1);
this.setState({
ItemsSearch: items,
});
}
};
return (
<>
<WebPartTitle displayMode={this.props.displayMode}
title={this.props.title}
updateProperty={this.props.updateProperty} moreLink={
<div style={{ display: "inline-flex" }}>
{(!this.state.visible) &&
<div>
<IconButton
iconProps={{ iconName: 'Refresh' }}
onClick={
this.getListItems
} allowDisabledFocus disabled={false} checked={false}
/>
</div>
}
{(!this.state.visible) &&
<Dropdown
placeholder="Filter by Site"
onChange={filterall}
tabIndex={0}
// eslint-disable-next-line react/jsx-no-bind
options={this.state.ItemsGroup}
styles={{ dropdown: { width: 300 } }}
/>
}
</div>
} />
<div className={styles.spinnerLoading}>
{(this.state.visible) &&
<Spinner size={SpinnerSize.large} />
}
{(!this.state.visible) &&
<Stack tokens={stackTokens}>
<SearchBox style={{ width: "80%" }} placeholder="Search Document" onSearch={checkSearchDrive} onClear={checkClear} />
</Stack>
}
</div>
<div className={styles.grid}>
<FollowDocumentGrid
items={this.state.ItemsSearch}
onRenderGridItem={(item: any, finalSize: ISize, isCompact: boolean) => this._onRenderGridItem(item, finalSize, isCompact)}
/>
</div>
</>
);
}
private _onRenderGridItem = (item: any, finalSize: ISize, isCompact: boolean): JSX.Element => {
return <div
className={styles.documentTile}
data-is-focusable={true}
role="listitem"
aria-label={item.title}
>
<DocumentCard
type={isCompact ? DocumentCardType.compact : DocumentCardType.normal}
>
<div style={{ cursor: 'pointer' }} onClick={() => window.open(item.url, '_blank')}>
<DocumentCardImage height={100} imageFit={ImageFit.center} imageSrc={item.profileImageSrc} />
</div>
{!isCompact && <DocumentCardLocation location={item.webName} onClick={() => window.open(item.webUrl, '_blank')} />}
<DocumentCardDetails>
<DocumentCardTitle
title={item.title}
shouldTruncate={true}
/>
<DocumentCardActions className={styles.DocumentCardActionsPadding} actions={item.documentCardActions} />
</DocumentCardDetails>
</DocumentCard>
</div>;
}
} | the_stack |
import * as Preact from 'preact';
import { ContextMenu } from 'diagramMaker/components/contextMenu';
import { Edge, EdgeBadge, EdgeStyle, PotentialEdge } from 'diagramMaker/components/edge';
import { Node, PotentialNode } from 'diagramMaker/components/node';
import { Panel } from 'diagramMaker/components/panel';
import { SelectionMarquee } from 'diagramMaker/components/selectionMarquee';
import { Workspace } from 'diagramMaker/components/workspace';
import ConfigService, {
ConnectorPlacement, ConnectorPlacementType, DestroyCallback, Shape, ShapeType, TypeForVisibleConnectorTypes
} from 'diagramMaker/service/ConfigService';
import { getInflectionPoint } from 'diagramMaker/service/positionUtils';
import { DiagramMakerComponentsType } from 'diagramMaker/service/ui/types';
import {
DiagramMakerData,
DiagramMakerEdge,
DiagramMakerEdges,
DiagramMakerNode,
Position,
Size
} from 'diagramMaker/state/types';
import './View.scss';
const CONNECTOR_PLACEMENT_TO_EDGE_TYPE = {
[ConnectorPlacement.LEFT_RIGHT]: EdgeStyle.LEFT_RIGHT_BEZIER,
[ConnectorPlacement.TOP_BOTTOM]: EdgeStyle.TOP_BOTTOM_BEZIER,
[ConnectorPlacement.CENTERED]: EdgeStyle.STRAIGHT,
[ConnectorPlacement.BOUNDARY]: EdgeStyle.STRAIGHT
};
interface EdgeCoordinatePair {
src: Position;
dest: Position;
}
export interface ViewProps<NodeType, EdgeType> {
state: DiagramMakerData<NodeType, EdgeType>;
configService: ConfigService<NodeType, EdgeType>;
}
const getConnectorPlacementForNode = <NodeType, EdgeType>(
node: DiagramMakerNode<NodeType>,
configService: ConfigService<NodeType, EdgeType>
) => {
const typeId = node.typeId;
if (!typeId) {
return configService.getConnectorPlacement();
}
return configService.getConnectorPlacementForNodeType(typeId);
};
const getCenteredConnectorCoordinates =
<NodeType extends any>(node: DiagramMakerNode<NodeType>): Position => {
const { position, size } = node.diagramMakerData;
return {
x: position.x + size.width / 2,
y: position.y + size.height / 2
};
};
const getLeftRightConnectorCoordinatesSource =
<NodeType extends any>(node: DiagramMakerNode<NodeType>): Position => {
const { position, size } = node.diagramMakerData;
return {
x: position.x + size.width,
y: position.y + size.height / 2
};
};
const getLeftRightConnectorCoordinatesDestination =
<NodeType extends any>(node: DiagramMakerNode<NodeType>): Position => {
const { position, size } = node.diagramMakerData;
return {
x: position.x,
y: position.y + size.height / 2
};
};
const getTopBottomConnectorCoordinatesDestination =
<NodeType extends any>(node: DiagramMakerNode<NodeType>): Position => {
const { position, size } = node.diagramMakerData;
return {
x: position.x + size.width / 2,
y: position.y
};
};
const getTopBottomConnectorCoordinatesSource =
<NodeType extends any>(node: DiagramMakerNode<NodeType>): Position => {
const { position, size } = node.diagramMakerData;
return {
x: position.x + size.width / 2,
y: position.y + size.height
};
};
const getEdgeCoordinateSource =
<NodeType, EdgeType>(
node: DiagramMakerNode<NodeType>,
configService: ConfigService<NodeType, EdgeType>
): Position => {
let sourceCoordinates: Position;
const connectorPlacement = getConnectorPlacementForNode(node, configService);
if (connectorPlacement === ConnectorPlacement.LEFT_RIGHT) {
sourceCoordinates = getLeftRightConnectorCoordinatesSource(node);
} else if (connectorPlacement === ConnectorPlacement.TOP_BOTTOM) {
sourceCoordinates = getTopBottomConnectorCoordinatesSource(node);
} else {
sourceCoordinates = getCenteredConnectorCoordinates(node);
}
return sourceCoordinates;
};
const getEdgeCoordinateDestination =
<NodeType, EdgeType>(
node: DiagramMakerNode<NodeType>,
configService: ConfigService<NodeType, EdgeType>
): Position => {
let sourceCoordinates: Position;
const connectorPlacement = getConnectorPlacementForNode(node, configService);
if (connectorPlacement === ConnectorPlacement.LEFT_RIGHT) {
sourceCoordinates = getLeftRightConnectorCoordinatesDestination(node);
} else if (connectorPlacement === ConnectorPlacement.TOP_BOTTOM) {
sourceCoordinates = getTopBottomConnectorCoordinatesDestination(node);
} else {
sourceCoordinates = getCenteredConnectorCoordinates(node);
}
return sourceCoordinates;
};
const getDistance = (srcPosition: Position, destPosition: Position) => {
const diffX = destPosition.x - srcPosition.x;
const diffY = destPosition.y - srcPosition.y;
return Math.sqrt((diffX * diffX) + (diffY * diffY));
};
const getBoundaryCoordinatesForCircle = (
sourcePosition: Position,
sourceSize: Size,
destinationPosition: Position
): Position => {
const distance = getDistance(sourcePosition, destinationPosition);
if (distance === 0) {
return sourcePosition;
}
// Using this formula to compute the coordinates: https://brilliant.org/wiki/section-formula/
const { x: x1, y: y1 } = sourcePosition;
const { x: x2, y: y2 } = destinationPosition;
const m = sourceSize.width / 2;
const n = distance - m;
return {
x: ((m * x2) + (n * x1)) / distance,
y: ((m * y2) + (n * y1)) / distance
};
};
const getBoundaryCoordinatesForRectangle = (
sourcePosition: Position,
sourceSize: Size,
destinationPosition: Position
): Position => {
// If the two points are orthogonal, the boundary is half the width or height of the rectangle.
if (sourcePosition.x === destinationPosition.x) {
return {
x: sourcePosition.x,
y: destinationPosition.y > sourcePosition.y ?
sourcePosition.y + sourceSize.height / 2 :
sourcePosition.y - sourceSize.height / 2
};
}
if (sourcePosition.y === destinationPosition.y) {
return {
x: destinationPosition.x > sourcePosition.x ?
sourcePosition.x + sourceSize.width / 2 :
sourcePosition.x - sourceSize.width / 2,
y: sourcePosition.y
};
}
// Otherwise - locate the boundary intersection point by calculating two right angle triangles.
// The first, bigger one, is created between the source and destination points.
// The second, smaller one, is created between the destination center and boundary intersection,
// with the rectangle. Use Pythagorus theorem for the calculations.
const adjacentSideBig = Math.abs(sourcePosition.x - destinationPosition.x);
const oppositeSideBig = Math.abs(sourcePosition.y - destinationPosition.y);
const angleT = Math.atan(oppositeSideBig / adjacentSideBig);
// Now we calculate the smaller triangle, inside the rectangle.
let adjacentSide;
let oppositeSide;
const diagonalAngle = Math.atan((sourceSize.width / 2) / sourceSize.height / 2);
if (angleT > diagonalAngle) {
// Intersection is on the top or bottom side
oppositeSide = sourceSize.height / 2;
adjacentSide = Math.abs(oppositeSide / Math.tan(angleT));
} else {
// Intersection is on the left or right side
adjacentSide = sourceSize.width / 2;
oppositeSide = Math.abs(adjacentSide * Math.tan(angleT));
}
let distanceX = adjacentSide;
let distanceY = oppositeSide;
// Calculate directions
if (destinationPosition.x < sourcePosition.x) {
distanceX = distanceX * -1;
}
if (destinationPosition.y < sourcePosition.y) {
distanceY = distanceY * -1;
}
return {
x: sourcePosition.x + distanceX,
y: sourcePosition.y + distanceY
};
};
const getBoundaryCoordinates = (
sourcePosition: Position,
sourceShape: ShapeType | undefined,
sourceSize: Size,
destPosition: Position
): Position => {
switch (sourceShape) {
case Shape.CIRCLE:
return getBoundaryCoordinatesForCircle(sourcePosition, sourceSize, destPosition);
case Shape.RECTANGLE:
return getBoundaryCoordinatesForRectangle(sourcePosition, sourceSize, destPosition);
}
return sourcePosition;
};
const applyBoundaryCheck =
<NodeType, EdgeType>(
configService: ConfigService<NodeType, EdgeType>,
nodeSrc: DiagramMakerNode<NodeType>,
positionSrc: Position,
positionDest: Position
) => {
const sourceConnectorPlacement = getConnectorPlacementForNode(nodeSrc, configService);
let sourceShape: ShapeType | undefined;
if (nodeSrc.typeId) {
sourceShape = configService.getShapeForNodeType(nodeSrc.typeId);
}
if (sourceConnectorPlacement === ConnectorPlacement.BOUNDARY) {
return getBoundaryCoordinates(
positionSrc,
sourceShape,
nodeSrc.diagramMakerData.size,
positionDest
);
}
return positionSrc;
};
const getEdgeCoordinatePair =
<NodeType, EdgeType>(
nodeSrc: DiagramMakerNode<NodeType>,
nodeDest: DiagramMakerNode<NodeType>,
configService: ConfigService<NodeType, EdgeType>,
overlappingEdge?: boolean
): EdgeCoordinatePair => {
const coordinates: EdgeCoordinatePair = {
src: getEdgeCoordinateSource(nodeSrc, configService),
dest: getEdgeCoordinateDestination(nodeDest, configService)
};
let tempDest = coordinates.dest;
let tempSrc = coordinates.src;
/**
* To find the point to cut based on overlapping edges
* We estimate the x/y coordinates of dest & src by creating a bezier curve
* https://stackoverflow.com/questions/51811935/point-of-intersection-between-bezier-curve-and-circle
*/
if (overlappingEdge) {
const { x: startingX, y: startingY } = getInflectionPoint(tempSrc, tempDest);
tempDest = { x: startingX, y: startingY };
tempSrc = { x: startingX, y: startingY };
}
const newSrc = applyBoundaryCheck(configService, nodeSrc, coordinates.src, tempDest);
const newDest = applyBoundaryCheck(configService, nodeDest, coordinates.dest, tempSrc);
return {
src: newSrc,
dest: newDest
};
};
const getEdgeStyle = (
sourceConnectorPlacement: ConnectorPlacementType,
destinationConnectorPlacement: ConnectorPlacementType
): EdgeStyle => {
if (sourceConnectorPlacement === destinationConnectorPlacement) {
return CONNECTOR_PLACEMENT_TO_EDGE_TYPE[sourceConnectorPlacement];
}
return EdgeStyle.STRAIGHT;
};
class View<NodeType, EdgeType> extends Preact.Component<ViewProps<NodeType, EdgeType>> {
public render() {
const {
position: workspacePosition,
canvasSize: workspaceSize,
scale: workspaceScale
} = this.props.state.workspace;
/**
* We need to put interim on top of the panels so that we can make the potential nodes appear on top of the panels.
* This is because workspace has a stacking context of its own and we cannot make the node appear on top of the
* panel from within the workspace.
* To make it so that when the node comes out of the panel, it appears the same size as it would in the workspace,
* we need to apply the same transforms on the interim as well.
*/
const transform = `translate3d(${workspacePosition.x}px, ${workspacePosition.y}px, 0) scale(${workspaceScale})`;
return (
<div className="dm-view" tabIndex={0} data-type={DiagramMakerComponentsType.VIEW}>
<Workspace
position={workspacePosition}
canvasSize={workspaceSize}
scale={workspaceScale}
>
<div className="dm-elements">
<svg className="dm-edges" xmlns="http://www.w3.org/2000/svg">
{this.renderArrowheadMarker()}
{this.renderEdges()}
</svg>
{this.renderEdgeBadges()}
{this.renderNodes()}
<svg className="dm-potential-edge" xmlns="http://www.w3.org/2000/svg">
{this.renderPotentialEdge()}
</svg>
</div>
</Workspace>
<div className="dm-panels">
{this.renderPanels()}
</div>
<div
className="dm-interim"
style={{ transform }}
>
{this.renderPotentialNode()}
</div>
<div
className="dm-selection"
style={{ transform }}
>
{this.renderSelectionMarquee()}
</div>
<div className="dm-menu">
{this.renderContextMenu()}
</div>
</div>
);
}
private renderArrowheadMarker() {
if (!this.props.configService.getShowArrowhead()) {
return;
}
return (
<defs>
<marker
id="arrow"
markerWidth="5"
markerHeight="5"
orient="auto"
refY="2.5"
refX="5"
stroke="#879596"
fill="#879596"
>
<path d="M0,0 L5,2.5 0,5" />
</marker>
</defs>
);
}
private renderNodes() {
const nodes = this.props.state.nodes;
const renderCallback = this.props.configService.getRenderNode();
const destroyCallback = this.props.configService.getRenderDestroy();
const nodeKeys = Object.keys(nodes);
return nodeKeys.map((nodeKey: string) => {
const typeId = nodes[nodeKey].typeId;
const connectorPlacement = getConnectorPlacementForNode(nodes[nodeKey], this.props.configService);
let visibleConnectorTypes: TypeForVisibleConnectorTypes | undefined;
if (typeId) {
visibleConnectorTypes = this.props.configService.getVisibleConnectorTypesForNodeType(typeId);
}
return (
<Node
key={`node_${nodes[nodeKey].id}`}
renderCallback={renderCallback.bind(null, nodes[nodeKey])}
destroyCallback={destroyCallback}
connectorPlacement={connectorPlacement}
diagramMakerNode={nodes[nodeKey]}
visibleConnectorTypes={visibleConnectorTypes}
/>
);
});
}
private renderPotentialNode() {
const node = this.props.state.potentialNode;
const renderCallback = this.props.configService.getRenderPotentialNode();
const destroyCallback = this.props.configService.getRenderDestroy();
if (!node || !renderCallback) {
return;
}
const { typeId, position, size } = node;
return (
<PotentialNode
key="potentialNode"
typeId={typeId}
position={position}
size={size}
renderCallback={renderCallback.bind(null, node)}
destroyCallback={destroyCallback}
/>
);
}
private renderEdges() {
const { singles: edgeSingles, pairs: edgePairs } = this.getEdges();
let pairEdges: JSX.Element[] = [];
edgePairs.forEach((edgePair: string[]) => {
pairEdges = pairEdges.concat(edgePair.map(edgeKey => this.renderEdge(edgeKey, true)));
});
const singleEdges = edgeSingles.map(edgeKey => this.renderEdge(edgeKey));
return singleEdges.concat(pairEdges);
}
private renderEdge(edgeKey: string, isEdgePair?: boolean) {
const nodes = this.props.state.nodes;
const edges = this.props.state.edges;
const edgeSource = nodes[edges[edgeKey].src];
const edgeDestination = nodes[edges[edgeKey].dest];
const edgeCoordinates = getEdgeCoordinatePair(
edgeSource,
edgeDestination,
this.props.configService,
isEdgePair
);
const edgeStyle = isEdgePair ? EdgeStyle.QUADRATIC_BEZIER : getEdgeStyle(
getConnectorPlacementForNode(edgeSource, this.props.configService),
getConnectorPlacementForNode(edgeDestination, this.props.configService)
);
return (
<Edge
key={`edge_${edges[edgeKey].id}`}
id={edges[edgeKey].id}
src={edgeCoordinates.src}
dest={edgeCoordinates.dest}
srcTypeId={edgeSource.typeId}
destTypeId={edgeDestination.typeId}
edgeStyle={edgeStyle}
selected={edges[edgeKey].diagramMakerData.selected}
showArrowhead={this.props.configService.getShowArrowhead()}
/>
);
}
private renderEdgeBadges() {
const nodes = this.props.state.nodes;
const edges = this.props.state.edges;
const renderCallback = this.props.configService.getRenderEdge();
const destroyCallback = this.props.configService.getRenderDestroy();
if (!renderCallback) {
return;
}
const { singles: edgeSingles, pairs: edgePairs } = this.getEdges();
let pairEdges: JSX.Element[] = [];
edgePairs.forEach((edgePair: string[]) => {
pairEdges = pairEdges.concat(edgePair.map((edgeKey: string, index: number) => {
const edgeCoordinates = getEdgeCoordinatePair(
nodes[edges[edgeKey].src],
nodes[edges[edgeKey].dest],
this.props.configService,
true
);
return (
<EdgeBadge
id={edgeKey}
key={`edgeBadge_${edges[edgeKey].id}`}
src={edgeCoordinates.src}
dest={edgeCoordinates.dest}
renderCallback={renderCallback.bind(null, edges[edgeKey])}
destroyCallback={destroyCallback}
isPartOfEdgePair={true}
/>
);
}));
});
const singleEdges = edgeSingles
.map((edgeKey: string) => {
const edgeCoordinates = getEdgeCoordinatePair(
nodes[edges[edgeKey].src],
nodes[edges[edgeKey].dest],
this.props.configService
);
return (
<EdgeBadge
id={edgeKey}
key={`edgeBadge_${edges[edgeKey].id}`}
src={edgeCoordinates.src}
dest={edgeCoordinates.dest}
renderCallback={renderCallback.bind(null, edges[edgeKey])}
destroyCallback={destroyCallback}
/>
);
});
return singleEdges.concat(pairEdges);
}
private getEdges(): { singles: string[], pairs: string[][]} {
const nodes = this.props.state.nodes;
const edges = this.props.state.edges;
const edgeKeys = Object.keys(edges);
const activeEdges = edgeKeys.filter(
(edgeKey: string) => !!(nodes[edges[edgeKey].src] && nodes[edges[edgeKey].dest])
);
const connectorPlacement = this.props.configService.getConnectorPlacement();
const edgeMapping: { [key: string]: string } = {};
const edgePairs: string[][] = [];
if (
connectorPlacement === ConnectorPlacementType.LEFT_RIGHT ||
connectorPlacement === ConnectorPlacementType.TOP_BOTTOM
) {
return { singles: activeEdges, pairs: [] };
}
activeEdges.forEach((edgeKey: string) => {
const currentEdge = edges[edgeKey];
const edgeSource = nodes[currentEdge.src];
const edgeDestination = nodes[currentEdge.dest];
const edgeMapId = `${edgeSource.id}__${edgeDestination.id}`;
const matchingEdgeId = `${edgeDestination.id}__${edgeSource.id}`;
let edgeOverlap;
if (edgeMapping[matchingEdgeId]) {
edgeOverlap = edgeMapping[matchingEdgeId];
edgePairs.push([currentEdge.id, edgeOverlap]);
delete edgeMapping[matchingEdgeId];
} else {
edgeMapping[edgeMapId] = currentEdge.id;
}
});
const edgeSingles: string[] = Object.keys(edgeMapping).map(val => edgeMapping[val]);
return {
singles: edgeSingles,
pairs: edgePairs
};
}
private renderPanels() {
const state = this.props.state;
const panels = this.props.state.panels;
const viewContainerSize = this.props.state.workspace.viewContainerSize;
const renderCallback = this.props.configService.getRenderPanel;
const destroyCallback = this.props.configService.getRenderDestroy();
const panelKeys = Object.keys(panels);
return panelKeys.map((panelKey: string) => (
<Panel
positionAnchor={panels[panelKey].positionAnchor}
key={`panel_${panels[panelKey].id}`}
id={panels[panelKey].id}
position={panels[panelKey].position}
size={panels[panelKey].size}
renderCallback={renderCallback(panelKey).bind(null, panels[panelKey], state)}
destroyCallback={destroyCallback}
viewContainerSize={viewContainerSize}
/>
));
}
private renderPotentialEdge() {
const nodes = this.props.state.nodes;
const edge = this.props.state.potentialEdge;
if (!edge) {
return;
}
const sourceCoordinates = getEdgeCoordinateSource(nodes[edge.src], this.props.configService);
const edgeStyle = getEdgeStyle(
getConnectorPlacementForNode(nodes[edge.src], this.props.configService),
this.props.configService.getConnectorPlacement()
);
return (
<PotentialEdge
key="potentialEdge"
src={sourceCoordinates}
dest={edge.position}
edgeStyle={edgeStyle}
showArrowhead={this.props.configService.getShowArrowhead()}
/>
);
}
private renderSelectionMarquee() {
const marquee = this.props.state.editor.selectionMarquee;
if (!marquee) {
return;
}
return (
<SelectionMarquee
anchor={marquee.anchor}
position={marquee.position}
/>
);
}
private renderContextMenu() {
const menu = this.props.state.editor.contextMenu;
if (!menu) {
return;
}
const renderCallback = this.props.configService.getBoundRenderContextMenu(menu.targetType, menu.targetId);
const destroyCallback = this.props.configService.getRenderDestroy();
if (!renderCallback) {
return;
}
return (
<ContextMenu
position={menu.position}
renderCallback={renderCallback}
destroyCallback={destroyCallback}
/>
);
}
}
export { View }; | the_stack |
import { Component, NgZone, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import {
ModalController, Platform,
LoadingController, ToastController, AlertController
} from '@ionic/angular';
import { NavParams } from '@ionic/angular';
import { OsmApiService } from '../../services/osmApi.service';
import { MapService } from '../../services/map.service';
import { DataService } from '../../services/data.service';
import { ConfigService } from '../../services/config.service';
import { AlertService } from '../../services/alert.service';
import { TagsService } from '../../services/tags.service';
import { ModalPrimaryTag } from './modal.primaryTag/modal.primaryTag';
import { ModalSelectList } from './modalSelectList/modalSelectList';
import { getConfigTag } from '../../../../scripts/osmToOsmgo/index.js'
import { Feature, Tag, Preset, PrimaryTag, TagConfig } from '../../../type'
import { cloneDeep, isEqual, findIndex } from 'lodash';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'modal',
templateUrl: './modal.html',
styleUrls: ['./modal.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ModalsContentPage implements OnInit {
tags: Tag[] = []; // main data
originalTags = [];
feature: Feature;
origineData: string;
typeFiche: string;
displayCode: boolean = false;
mode;
tagConfig: TagConfig
primaryKey: PrimaryTag
savedFields;
tagId: string;
geometryType: 'point' | 'vertex' | 'line' | 'area';
customValue = '';
newKey = '';
allTags;
newPosition;
displayAddTag = false;
presetsIds = [];
constructor(
public platform: Platform,
public params: NavParams,
public loadingCtrl: LoadingController,
public osmApi: OsmApiService,
public tagsService: TagsService,
public modalCtrl: ModalController,
public mapService: MapService,
public dataService: DataService,
public configService: ConfigService,
public alertService: AlertService,
public toastCtrl: ToastController,
private alertCtrl: AlertController,
private zone: NgZone,
private translate: TranslateService,
private cdr: ChangeDetectorRef
) {
this.newPosition = params.data.newPosition;
this.feature = cloneDeep(params.data.data);
const originalFeatureGeometry = this.feature.properties.way_geometry ? this.feature.properties.way_geometry : this.feature.geometry
const typeGeomFeature = originalFeatureGeometry.type;
const usedByWay = this.feature.properties.usedByWays ? true : false
if (typeGeomFeature === 'Point' && !usedByWay) {
this.geometryType = 'point';
} else if (typeGeomFeature === 'Point' && usedByWay) {
this.geometryType = 'vertex';
} else if (typeGeomFeature === 'LineString' || typeGeomFeature === 'MultiLineString') {
this.geometryType = 'line'
} else if (typeGeomFeature === 'Polygon' || typeGeomFeature === 'MultiPolygon') {
this.geometryType = 'area'
}
this.mode = params.data.type; // Read, Create, Update
this.origineData = this.params.data.origineData; // literal, sources
this.typeFiche = 'Loading'; // Edit, Read, Loading
// converti les tags (object of objects) en array (d'objets) ([{key: key, value: v}])
// tslint:disable-next-line:forin
for (const tag in this.feature.properties.tags) {
this.tags.push({ key: tag, value: this.feature.properties.tags[tag] });
}
// clone
this.originalTags = cloneDeep(this.tags);
}
ngOnInit() { // override
this.initComponent();
this.cdr.detectChanges();
if (this.mode === 'Create') {
this.openPrimaryTagModal();
}
}
presentConfirm() {
this.alertCtrl.create({
header: this.translate.instant('MODAL_SELECTED_ITEM.DELETE_CONFIRM_HEADER'),
message: this.translate.instant('MODAL_SELECTED_ITEM.DELETE_CONFIRM_MESSAGE'),
buttons: [
{
text: this.translate.instant('SHARED.CANCEL'),
role: 'cancel',
handler: () => {
}
},
{
text: this.translate.instant('SHARED.CONFIRM'),
handler: () => {
this.deleteOsmElement();
}
}
]
}).then(alert => {
alert.present();
});
}
initComponent(tagConfig: TagConfig = null) {
let _tags = [...this.tags]
let feature = cloneDeep(this.feature)
let _tagConfig: TagConfig;
let _tagId;
let _presetsIds: string[];
let _savedFields;
let _primaryKey;
_primaryKey = this.tagsService.findPkey(_tags);
feature.properties.primaryTag = _primaryKey
// this.feature.properties.primaryTag = this.primaryKey
// Edit, Read, Loading
this.typeFiche = (this.mode === 'Update' || this.mode === 'Create') ? 'Edit' : 'Read'; // ?
_tags = _tags.filter(tag => tag.value && tag.value !== '' && !tag.isDefaultValue);
if (!_tags.find(tag => tag.key === 'name')) { // on ajoute un nom vide si il n'existe pas
_tags.push({ key: 'name', value: '' });
}
// la configuration pour cette clé principale (lbl, icon, presets[], ...)
if (!tagConfig) {
_tagConfig = getConfigTag(feature, this.tagsService.tags);
} else {
_tagConfig= tagConfig;
}
_tagId = _tagConfig && _tagConfig.id ? _tagConfig.id : `${_primaryKey.key}/${_primaryKey.value}`;
// this.tagId = this.tagConfig && this.tagConfig.id ? this.tagConfig.id : `${this.primaryKey.key}/${this.primaryKey.value}`;
_savedFields = this.tagsService.savedFields[_tagId];
this.savedFields = _savedFields;
// this.presetsIds = (this.tagConfig && this.tagConfig.presets) ? this.tagConfig.presets : undefined;
_presetsIds = (_tagConfig && _tagConfig.presets) ? _tagConfig.presets : undefined;
if (_presetsIds && _presetsIds.length > 0) {
// on ajoute les presets manquant aux données 'tags' (chaine vide); + ajout 'name' si manquant
for (let i = 0; i < _presetsIds.length; i++) {
const preset: Preset = this.tagsService.presets[_presetsIds[i]];
// le tag utilisant la clé du preset
const tagOfPreset: Tag = _tags.find(tag => tag.key === preset.key) || undefined;
if (tagOfPreset) {
tagOfPreset['preset'] = preset; // on met la config du prset direct dans le "tag" => key, value, preset[]
} else { // => un le tag avec la key du preset n'existe pas, on l'insert vide
_tags.push({ 'key': preset.key, 'value': '', preset: preset });
}
}
}
this.tagId = _tagId;
this.feature = feature;
this.tags = _tags;
this.presetsIds = _presetsIds;
this.tagConfig = _tagConfig;
this.primaryKey = _primaryKey;
return { tagConfig: _tagConfig, tags: _tags, feature: feature }
}
dataIsChanged() {
const tagsNotNull = [];
for (let i = 0; i < this.tags.length; i++) {
if (this.tags[i].value) {
tagsNotNull.push({ 'key': this.tags[i].key, 'value': this.tags[i].value });
}
}
const originalTagsNotNull = [];
for (let i = 0; i < this.originalTags.length; i++) {
if (this.originalTags[i].value && this.originalTags[i].value !== '') {
originalTagsNotNull.push({ 'key': this.originalTags[i].key, 'value': this.originalTags[i].value });
}
}
if (isEqual(tagsNotNull, originalTagsNotNull)) {
return false;
}
return true;
}
updateMode() {
this.zone.run(() => {
this.mode = 'Update';
this.typeFiche = 'Edit';
});
}
toogleCode() { // affiche les tags originaux
this.zone.run(() => {
this.displayCode = (this.displayCode) ? false : true;
});
}
addNewKey(key){
// Check if the key already exists in presets
if ( this.tags.find( t => t.key == key)){
this.displayAddTag = false;
this.newKey = '';
return;
}
const genericPreset = this.tagsService.presets[key];
if (!genericPreset){
this.tags = [...this.tags, {key: key, value:''}]
} else {
this.tags = [...this.tags, {key: key, value:'', preset: genericPreset }]
}
this.newKey = '';
this.displayAddTag = false;
}
deleteTag(tag) {
const idx = findIndex(this.tags, { key: tag.key });
if (idx !== -1) {
this.tags.splice(idx, 1);
}
}
toLowerCase(text: string) {
return text.toLowerCase();
}
// renvoie l'élément du tableau correspondant || TODO => pipe
findElement(array, kv) { // {'user': 'fred'}
const idx = findIndex(array, kv);
if (idx !== -1) {
return array[idx];
}
return null;
}
dismiss(data = null) {
this.modalCtrl.dismiss(data);
}
createOsmElement(tagconfig) {
this.typeFiche = 'Loading';
this.tagsService.addTagTolastTagsUsed(tagconfig.id);
if (this.configService.getAddSurveyDate()) {
this.addSurveyDate()
}
this.pushTagsToFeature(); // on pousse les tags dans la feature
this.osmApi.createOsmNode(this.feature).subscribe(data => {
this.dismiss({ redraw: true });
});
}
updateOsmElement(tagconfig) {
this.typeFiche = 'Loading';
this.tagsService.addTagTolastTagsUsed(tagconfig ? tagconfig.id : null);
// si les tags et la position n'ont pas changé, on ne fait rien!
if (!this.dataIsChanged() && !this.newPosition) {
this.dismiss();
return;
}
if (this.configService.getAddSurveyDate()) {
this.addSurveyDate()
}
this.pushTagsToFeature(); // on pousse les tags dans la feature
this.osmApi.updateOsmElement(this.feature, this.origineData).subscribe(data => {
this.dismiss({ redraw: true });
});
}
deleteOsmElement() {
this.typeFiche = 'Loading';
this.osmApi.deleteOsmElement(this.feature).subscribe(data => {
this.dismiss({ redraw: true });
});
}
pushTagsToFeature() {
const tagObjects = {};
for (let i = 0; i < this.tags.length; i++) {
tagObjects[this.tags[i].key] = this.tags[i].value;
}
this.feature.properties.tags = tagObjects;
}
moveOsmElement() {
this.pushTagsToFeature();
// on ferme la modal
this.dismiss({ type: 'Move', 'geojson': this.feature, mode: this.mode });
}
async openPrimaryTagModal() {
const modal = await this.modalCtrl.create({
component: ModalPrimaryTag,
componentProps: { geojson: this.feature, tagConfig: this.tagConfig, tags: this.tags, geometryType : this.geometryType }
});
await modal.present();
modal.onDidDismiss()
.then(d => {
const newTagConfig = d.data;
const oldTagConfig = this.tagConfig;
const oldKeyTagsToDelete = Object.keys(oldTagConfig.tags);
let copyTags = cloneDeep(this.tags);
copyTags = copyTags.filter( t => !oldKeyTagsToDelete.includes(t.key))
for (let t of copyTags){
if (t.preset ){
delete t.preset
}
}
if (!newTagConfig){
this.cdr.detectChanges();
return;
}
const newTagsKeys = Object.keys(newTagConfig.tags )
let newTagsToAdd = [];
for (let k in newTagConfig.tags ){
newTagsToAdd = [{key: k, value:newTagConfig.tags[k] }, ...newTagsToAdd]
}
copyTags = copyTags.filter( ct => !newTagsKeys.includes(ct.key))
copyTags = [...newTagsToAdd, ...copyTags ]
if (newTagConfig.addTags){
copyTags = this.addTags(newTagConfig.addTags,copyTags )
}
this.tags = [...copyTags];
this.initComponent(newTagConfig);
this.cdr.detectChanges();
});
}
async openModalList(data, preset) {
if (preset){
data['preset'] = preset;
}
const modal = await this.modalCtrl.create({
component: ModalSelectList,
componentProps: data
});
await modal.present();
modal.onDidDismiss().then(d => {
const _data = d.data;
if (_data) {
this.tags.filter(tag => tag.key === _data.key)[0].value = _data.value;
if (_data.tags) { // add or remplace tags...
this.tags = this.addTags(_data.tags, this.tags)
this.initComponent(this.tagConfig )
}
}
this.cdr.detectChanges();
});
}
// add or remplace tags [] from tags {}
addTags(newTags, existingTags){
let _existingTags = [...existingTags]
for (let t in newTags) {
const tagIndex = _existingTags.findIndex(o => o.key == t);
if (tagIndex !== -1) {
_existingTags[tagIndex] = { "key": t, "value": newTags[t] };
} else {
_existingTags = [..._existingTags, { "key": t, "value": newTags[t] }]
}
}
return _existingTags;
}
addPresetsTags(newTags){
if (newTags){
this.tags = this.addTags(newTags, this.tags)
this.initComponent(this.tagConfig )
}
this.cdr.detectChanges();
}
cancelChange() {
this.dataService.cancelFeatureChange(this.feature);
this.dismiss({ redraw: true });
}
async presentToast(message) {
const toast = await this.toastCtrl.create({
message: message,
duration: 4000,
position: 'bottom',
buttons: [
{
text: 'X',
role: 'cancel',
handler: () => {
}
}
]
});
toast.present();
// this.toastCtrl.create({
// message: message,
// duration: 5000,
// showCloseButton: true,
// closeButtonText: 'X'
// }).then(toast => {
// toast.present();
// });
}
confirmAddSurveyDate() {
this.alertCtrl.create({
header: this.translate.instant('MODAL_SELECTED_ITEM.ADD_SURVEY_DATE_CONFIRM_HEADER'),
subHeader: this.translate.instant('MODAL_SELECTED_ITEM.ADD_SURVEY_DATE_CONFIRM_MESSAGE'),
buttons: [
{
text: this.translate.instant('SHARED.NO'),
role: 'cancel',
handler: data => {
}
},
{
text: this.translate.instant('SHARED.YES'),
handler: data => {
this.addSurveyDate();
this.updateOsmElement(null);
}
}
]
})
.then(alert => {
alert.present();
});
}
addSurveyDate() {
const now = new Date;
const YYYY = now.getFullYear();
const MM = ((now.getMonth()) + 1 < 10) ? '0' + (now.getMonth() + 1) : '' + (now.getMonth() + 1);
const DD = (now.getDate() < 10) ? '0' + now.getDate() : '' + now.getDate();
const isoDate = YYYY + '-' + MM + '-' + DD;
let tagSurveyIndex = -1;
for (let i = 0; i < this.tags.length; i++) {
if (this.tags[i].key === this.configService.config.checkedKey) {
tagSurveyIndex = i;
break;
}
}
if (tagSurveyIndex !== -1) { // le tag existe déjà, on l'écrase
this.tags[tagSurveyIndex].value = isoDate;
} else {
this.tags.push({ 'key': this.configService.config.checkedKey, 'value': isoDate });
}
}
saveFields(tagId, tags) {
const savedTags = tags.map(t => { return { key: t.key, value: t.value } })
.filter(t => t.key !== 'name')
.filter(t => t.key !== 'survey:date')
.filter(t => t.key !== 'check_date')
this.tagsService.addSavedField(tagId, savedTags);
if (!this.savedFields) this.savedFields = {};
this.savedFields['tags'] = [...savedTags];
}
restoreFields(tagId, tags) {
const fields = this.tagsService.savedFields[tagId];
const newTags = [...tags];
if (fields) {
for (let stags of fields.tags) {
let t = newTags.find(o => o.key === stags.key)
if (t) {
t['value'] = stags.value
} else {
newTags.push(stags)
}
}
}
this.tags = [...newTags];
this.initComponent(this.tagConfig);
this.cdr.detectChanges();
}
fixDeprecated(deprecated: any) {
const deprecadetKeys = Object.keys(deprecated.old)
// delete old tags
this.tags = this.tags.filter(t => !deprecadetKeys.includes(t.key))
for (let depold of deprecadetKeys) {
if (this.feature.properties[depold]) {
delete this.feature.properties[depold];
}
}
this.feature.properties.tags = { ...this.feature.properties.tags , ...deprecated.replace }
// add new
for (let k in deprecated.replace) {
this.tags = [{ 'key': k, 'value': deprecated.replace[k] }, ...this.tags]
}
if (this.mode !== 'Update') {
this.mode = 'Update';
this.typeFiche = 'Edit'
}
this.initComponent();
this.cdr.detectChanges();
}
addOrRemoveBookmark(tag : TagConfig) {
if (!this.tagsService.bookmarksIds.includes(tag.id)) {
this.tagsService.addBookMark(tag)
} else {
this.tagsService.removeBookMark(tag)
}
this.cdr.detectChanges();
}
} | the_stack |
export function createSnippetV5(snipConfig) {
let win = window;
let doc = document;
var locn = win.location;
var helpLink = "https://go.microsoft.com/fwlink/?linkid=2128109";
var scriptText = "script";
var strInstrumentationKey = "instrumentationKey";
var strIngestionendpoint = "ingestionendpoint";
var strDisableExceptionTracking = "disableExceptionTracking";
var strAiDevice = "ai.device.";
var strAiOperationName = "ai.operation.name";
var strAiSdkVersion = "ai.internal.sdkVersion";
var strToLowerCase = "toLowerCase";
var strEmpty = "";
var strUndefined = "undefined";
var strCrossOrigin = "crossOrigin";
var strPostMethod = "POST";
var sdkInstanceName = "appInsightsSDK"; // required for Initialization to find the current instance
var aiName = snipConfig.name || "appInsights"; // provide non default instance name through snipConfig name value
if (snipConfig.name || win[sdkInstanceName]) {
// Only set if supplied or another name is defined to avoid polluting the global namespace
win[sdkInstanceName] = aiName;
}
var aiSdk = win[aiName] || (function (aiConfig) {
var loadFailed = false;
var handled = false;
var appInsights: any = {
initialize: true, // initialize sdk on download
queue: [],
sv: "5", // Track the actual snippet version for reporting.
version: 2.0, // initialization version, if this is not 2.0 the previous scripts fail to initialize
config: aiConfig
};
function _parseConnectionString() {
var fields: any = {};
var connectionString = aiConfig.connectionString;
if (connectionString) {
var kvPairs = connectionString.split(";");
for (var lp = 0; lp < kvPairs.length; lp++) {
var kvParts = kvPairs[lp].split("=");
if (kvParts.length === 2) { // only save fields with valid formats
fields[kvParts[0][strToLowerCase]()] = kvParts[1];
}
}
}
// apply the default endpoints
if (!fields[strIngestionendpoint]) {
// use endpoint suffix where overrides are not provided
var endpointSuffix = fields.endpointsuffix;
// Only fetch the location if a suffix was supplied
var fLocation = endpointSuffix ? fields.location : null;
fields[strIngestionendpoint] = "https://" + (fLocation ? fLocation + "." : strEmpty) + "dc." + (endpointSuffix || "services.visualstudio.com");
}
return fields;
}
function _sendEvents(evts, endpointUrl) {
if (JSON) {
var sender = win.fetch;
if (sender && !snipConfig.useXhr) {
sender(endpointUrl, { method:strPostMethod, body: JSON.stringify(evts), mode:"cors"});
} else if (XMLHttpRequest) {
// IE doesn't support fetch and private clouds may only be using IE
var xhr = new XMLHttpRequest();
xhr.open(strPostMethod, endpointUrl);
xhr.setRequestHeader("Content-type", "application/json");
xhr.send(JSON.stringify(evts));
}
}
}
function _reportFailure(targetSrc) {
var conString = _parseConnectionString();
var iKey = conString[strInstrumentationKey] || aiConfig[strInstrumentationKey] || strEmpty;
var ingest = conString[strIngestionendpoint];
var endpointUrl = ingest ? ingest + "/v2/track" : aiConfig.endpointUrl; // only add /v2/track when from connectionstring
var message = "SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details)";
var evts = [];
evts.push(_createException(iKey, message, targetSrc, endpointUrl));
evts.push(_createInternal(iKey, message, targetSrc, endpointUrl));
_sendEvents(evts, endpointUrl);
}
// Gets the time as an ISO date format, using a function as IE7/8 doesn't support toISOString
function _getTime() {
var date = new Date();
function pad(num) {
var r = strEmpty + num;
if (r.length === 1) {
r = "0" + r;
}
return r;
}
return date.getUTCFullYear()
+ "-" + pad(date.getUTCMonth() + 1)
+ "-" + pad(date.getUTCDate())
+ "T" + pad(date.getUTCHours())
+ ":" + pad(date.getUTCMinutes())
+ ":" + pad(date.getUTCSeconds())
+ "." + String((date.getUTCMilliseconds() / 1000).toFixed(3)).slice(2, 5)
+ "Z";
}
function _createEnvelope(iKey, theType): any {
var tags = {};
var type = "Browser";
tags[strAiDevice + "id"] = type[strToLowerCase]();
tags[strAiDevice + "type"] = type;
tags[strAiOperationName] = locn && locn.pathname || "_unknown_";
tags[strAiSdkVersion] = "javascript:snippet_" + (appInsights.sv || appInsights.version);
return {
time: _getTime(),
iKey: iKey,
name: "Microsoft.ApplicationInsights." + iKey.replace(/-/g, strEmpty) + "." + theType,
sampleRate: 100,
tags: tags,
data: {
baseData: {
ver: 2
}
}
};
}
function _createInternal(iKey, message, targetSrc, endpointUrl) {
var envelope = _createEnvelope(iKey, "Message");
var data = envelope.data;
data.baseType = "MessageData";
var baseData = data.baseData;
baseData.message = "AI (Internal): 99 message:\"" + (message + " (" + targetSrc + ")").replace(/\"/g, strEmpty) + "\"";
baseData.properties = {
endpoint: endpointUrl
};
return envelope;
}
function _createException(iKey, message, targetSrc, endpointUrl) {
var envelope = _createEnvelope(iKey, "Exception");
var data = envelope.data;
data.baseType = "ExceptionData";
data.baseData.exceptions = [{
typeName: "SDKLoadFailed",
message: message.replace(/\./g, "-"), // Replacing '.' characters as it causes the portal to hide the start of the message in the summary
hasFullStack: false,
stack: message + "\nSnippet failed to load [" + targetSrc + "] -- Telemetry is disabled\nHelp Link: " + helpLink + "\nHost: " + (locn && locn.pathname || "_unknown_") + "\nEndpoint: " + endpointUrl,
parsedStack: []
}];
return envelope;
}
// Commented out as we don't want to load from the CDN
// -------------------------------------------------------------
// Assigning these to local variables allows them to be minified to save space:
// var targetSrc = aiConfig.url || snipConfig.src;
// if (targetSrc) {
// function _handleError(evt) {
// loadFailed = true;
// appInsights.queue = []; // Clear the queue
// if (!handled) {
// handled = true;
// _reportFailure(targetSrc);
// }
// }
// function _handleLoad(evt, isAbort) {
// if (!handled) {
// // IE10, Opera calls loaded before the script is processed.
// // so delaying to give the script a chance to be processed
// setTimeout(function() {
// if (isAbort || !appInsights.core) {
// _handleError();
// }
// }, 500);
// }
// }
// function _createScript() {
// var scriptElement = doc.createElement(scriptText);
// scriptElement.src = targetSrc;
// // Allocate Cross origin only if defined and available
// var crossOrigin = snipConfig[strCrossOrigin];
// if ((crossOrigin || crossOrigin === "") && scriptElement[strCrossOrigin] != strUndefined) {
// scriptElement[strCrossOrigin] = crossOrigin;
// }
// scriptElement.onload = _handleLoad;
// scriptElement.onerror = _handleError;
// // Some browsers support onload while others onreadystatechange and others both
// scriptElement.onreadystatechange = function (evt, isAbort) {
// if (scriptElement.readyState === "loaded" || scriptElement.readyState === "complete") {
// _handleLoad(evt, isAbort);
// }
// };
// return scriptElement;
// }
// var theScript = _createScript();
// if (snipConfig.ld < 0) {
// // if user wants to append tag to document head, blocking page load
// var headNode = doc.getElementsByTagName("head")[0];
// headNode.appendChild(theScript);
// } else {
// setTimeout(function () {
// // Attempts to place the script tag in the same location as the first script on the page
// doc.getElementsByTagName(scriptText)[0].parentNode.appendChild(theScript);
// }, snipConfig.ld || 0);
// }
// }
// capture initial cookie
try {
appInsights.cookie = doc.cookie;
} catch (e) { }
function _createMethods(methods) {
while (methods.length) {
(function (name) {
// Define a temporary method that queues-up a the real method call
appInsights[name] = function () {
// Capture the original arguments passed to the method
var originalArguments = arguments;
if (!loadFailed) { // If we have detected that the main script failed to load then stop queuing events that will never be processed
// Queue-up a call to the real method
appInsights.queue.push(function () {
// Invoke the real method with the captured original arguments
appInsights[name].apply(appInsights, originalArguments);
});
}
};
})(methods.pop());
}
}
var track = "track";
var trackPage = "TrackPage";
var trackEvent = "TrackEvent";
_createMethods([track + "Event",
track + "PageView",
track + "Exception",
track + "Trace",
track + "DependencyData",
track + "Metric",
track + "PageViewPerformance",
"start" + trackPage,
"stop" + trackPage,
"start" + trackEvent,
"stop" + trackEvent,
"addTelemetryInitializer",
"setAuthenticatedUserContext",
"clearAuthenticatedUserContext",
"flush"]);
// expose SeverityLevel enum
appInsights['SeverityLevel'] = {
Verbose : 0,
Information : 1,
Warning : 2,
Error : 3,
Critical : 4
};
// Collect global errors
// Note: ApplicationInsightsAnalytics is the extension string identifier for
// AppAnalytics. It is defined in ApplicationInsights.ts:ApplicationInsights.identifer
var analyticsCfg = ((aiConfig.extensionConfig || {}).ApplicationInsightsAnalytics ||{});
if (!(aiConfig[strDisableExceptionTracking] === true || analyticsCfg[strDisableExceptionTracking] === true)) {
var method = "onerror";
_createMethods(["_" + method]);
var originalOnError = win[method];
win[method] = function(message, url, lineNumber, columnNumber, error) {
var handled = originalOnError && originalOnError(message, url, lineNumber, columnNumber, error);
if (handled !== true) {
appInsights["_" + method]({
message: message,
url: url,
lineNumber: lineNumber,
columnNumber: columnNumber,
error: error
});
}
return handled;
};
aiConfig.autoExceptionInstrumented = true;
}
return appInsights;
})(snipConfig.cfg);
function _onInit() {
if (snipConfig.onInit) {
snipConfig.onInit(aiSdk);
}
}
// if somebody calls the snippet twice, don't report page view again
if (aiSdk.queue && aiSdk.queue.length === 0) {
aiSdk.queue.push(_onInit);
// aiSdk.trackPageView({});
} else {
// Already loaded so just call the onInit
_onInit();
}
return aiSdk;
} | the_stack |
import { assert } from "node-opcua-assert";
import { CertificateInternals, exploreCertificate } from "node-opcua-crypto/dist/source/crypto_explore_certificate";
import { AccessRestrictionsFlag, allPermissions, AttributeIds, PermissionFlag } from "node-opcua-data-model";
import { PreciseClock } from "node-opcua-date-time";
import { NodeId, NodeIdLike, resolveNodeId, sameNodeId } from "node-opcua-nodeid";
import {
AnonymousIdentityToken,
MessageSecurityMode,
PermissionType,
RolePermissionType,
UserNameIdentityToken,
X509IdentityToken
} from "node-opcua-types";
import { ISessionContext, UAObject, UAObjectType, UAVariable, BaseNode, ISessionBase } from "node-opcua-address-space-base";
import { ObjectIds } from "node-opcua-constants";
import { StatusCodes } from "node-opcua-status-code";
import { NamespacePrivate } from "../src/namespace_private";
export { RolePermissionType, RolePermissionTypeOptions, PermissionType } from "node-opcua-types";
type UserIdentityToken = UserNameIdentityToken | AnonymousIdentityToken | X509IdentityToken;
function getUserName(userIdentityToken: UserIdentityToken): string {
if (userIdentityToken instanceof AnonymousIdentityToken) {
return "anonymous";
}
if (userIdentityToken instanceof X509IdentityToken) {
const certInfo: CertificateInternals = exploreCertificate(userIdentityToken.certificateData);
const userName = certInfo.tbsCertificate.subject.commonName || "";
if (typeof userName !== "string") {
throw new Error("Invalid username");
}
return userName;
}
if (userIdentityToken instanceof UserNameIdentityToken) {
if (userIdentityToken.policyId === "anonymous") {
return "anonymous";
}
assert(Object.prototype.hasOwnProperty.call(userIdentityToken, "userName"));
return userIdentityToken.userName!;
}
throw new Error("Invalid user identity token");
}
/**
*
*/
export enum WellKnownRoles {
Anonymous = ObjectIds.WellKnownRole_Anonymous,
AuthenticatedUser = ObjectIds.WellKnownRole_AuthenticatedUser,
ConfigureAdmin = ObjectIds.WellKnownRole_ConfigureAdmin,
Engineer = ObjectIds.WellKnownRole_Engineer,
Observer = ObjectIds.WellKnownRole_Observer,
Operator = ObjectIds.WellKnownRole_Operator,
SecurityAdmin = ObjectIds.WellKnownRole_SecurityAdmin,
Supervisor = ObjectIds.WellKnownRole_Supervisor
}
export enum WellKnownRolesNodeId {
Anonymous = ObjectIds.WellKnownRole_Anonymous,
AuthenticatedUser = ObjectIds.WellKnownRole_AuthenticatedUser,
ConfigureAdmin = ObjectIds.WellKnownRole_ConfigureAdmin,
Engineer = ObjectIds.WellKnownRole_Engineer,
Observer = ObjectIds.WellKnownRole_Observer,
Operator = ObjectIds.WellKnownRole_Operator,
SecurityAdmin = ObjectIds.WellKnownRole_SecurityAdmin,
Supervisor = ObjectIds.WellKnownRole_Supervisor
}
/**
* OPC Unified Architecture, Part 3 13 Release 1.04
* 4.8.2 Well Known Roles
* All Servers should support the well-known Roles which are defined in Table 2. The NodeIds
* for the well-known Roles are defined in Part 6.
* Table 2 – Well-Known Roles
* BrowseName Suggested Permissions
*
* Anonymous The Role has very limited access for use when a Session has anonymous credentials.
* AuthenticatedUser The Role has limited access for use when a Session has valid non-anonymous credentials
* but has not been explicitly granted access to a Role.
* Observer The Role is allowed to browse, read live data, read historical data/events or subscribe to data/events.
* Operator The Role is allowed to browse, read live data, read historical data/events or subscribe to data/events.
* In addition, the Session is allowed to write some live data and call some Methods.
* Engineer The Role is allowed to browse, read/write configuration data, read historical data/events,
* call Methods or subscribe to data/events.
* Supervisor The Role is allowed to browse, read live data, read historical data/events, call Methods or
* subscribe to data/events.
* ConfigureAdmin The Role is allowed to change the non-security related config
* SecurityAdmin The Role is allowed to change security related settings.
*/
export type WellKnownRolesSemiColumnSeparated = string;
export interface IUserManager {
/**
* retrieve the roles of the given user
* @returns semicolon separated list of roles
*/
getUserRoles?: (user: string) => NodeId[];
}
export interface IServerBase {
userManager?: IUserManager;
}
export interface SessionContextOptions {
session?: ISessionBase /* ServerSession */;
object?: UAObject | UAObjectType;
server?: IServerBase /* OPCUAServer*/;
}
function getPermissionForRole(rolePermissions: RolePermissionType[] | null, role: NodeId): PermissionFlag {
if (rolePermissions === null) {
return allPermissions;
}
const a = rolePermissions.find((r) => {
return sameNodeId(resolveNodeId(r.roleId!), role);
});
return a !== undefined ? a.permissions! | PermissionFlag.None : PermissionFlag.None;
}
function isDefaultContext(context: SessionContext) {
return context === SessionContext.defaultContext;
}
function getAccessRestrictionsOnNamespace(namespace: NamespacePrivate, context: SessionContext): AccessRestrictionsFlag {
// ignore permission when default context is provided (to avoid recursion)
if (isDefaultContext(context)) {
return AccessRestrictionsFlag.None;
}
const namespaces = namespace.addressSpace.rootFolder?.objects?.server?.namespaces;
if (!namespaces) {
return AccessRestrictionsFlag.None;
}
const namespaceObject = namespaces.getChildByName(namespace.namespaceUri);
if (!namespaceObject) {
return AccessRestrictionsFlag.None;
}
const defaultAccessRestriction = namespaceObject.getChildByName("defaultAccessRestriction");
if (defaultAccessRestriction) {
const dataValue = defaultAccessRestriction.readAttribute(null, AttributeIds.Value);
if (dataValue && dataValue.statusCode === StatusCodes.Good) {
return dataValue.value.value as AccessRestrictionsFlag;
}
}
return AccessRestrictionsFlag.None;
}
function getDefaultUserRolePermissionsOnNamespace(
namespace: NamespacePrivate,
context: SessionContext
): RolePermissionType[] | null {
// ignore permission when default context is provided
if (isDefaultContext(context)) {
return null;
}
const namespaces = namespace.addressSpace.rootFolder?.objects?.server?.namespaces;
if (!namespaces) {
return null;
}
const uaNamespaceObject = namespaces.getChildByName(namespace.namespaceUri);
if (!uaNamespaceObject) {
return null;
}
const defaultUserRolePermissions = uaNamespaceObject.getChildByName("DefaultUserRolePermissions") as UAVariable;
if (defaultUserRolePermissions) {
const dataValue = defaultUserRolePermissions.readValue();
if (dataValue && dataValue.statusCode === StatusCodes.Good && dataValue.value.value && dataValue.value.value.length > 0) {
return dataValue.value.value as RolePermissionType[];
}
}
const defaultRolePermissions = uaNamespaceObject.getChildByName("DefaultRolePermissions") as UAVariable;
if (defaultRolePermissions) {
const dataValue = defaultRolePermissions.readValue();
if (dataValue && dataValue.statusCode === StatusCodes.Good) {
return dataValue.value.value as RolePermissionType[] | null;
}
}
return null;
}
export function makeRoles(roleIds: NodeIdLike[] | string | WellKnownRoles): NodeId[] {
if (typeof roleIds === "number") {
roleIds = [roleIds];
}
if (typeof roleIds === "string") {
roleIds = roleIds.split(";").map((r) => resolveNodeId("WellKnownRole_" + r));
}
return roleIds.map((r) => resolveNodeId(r));
}
export class SessionContext implements ISessionContext {
public static defaultContext = new SessionContext({});
public object: any;
public currentTime?: PreciseClock;
public continuationPoints: any = {};
public userIdentity?: string;
public readonly session?: ISessionBase;
public readonly server?: IServerBase;
constructor(options?: SessionContextOptions) {
options = options || {};
this.session = options.session;
this.object = options.object;
this.server = options.server;
this.currentTime = undefined;
}
/**
* getCurrentUserRoles
*
* guest => anonymous user (unauthenticated)
* default => default authenticated user
*
*/
public getCurrentUserRoles(): NodeId[] {
if (!this.session) {
return []; // default context => no Session
}
assert(this.session != null, "expecting a session");
const userIdentityToken = this.session.userIdentityToken;
if (!userIdentityToken) {
return [];
}
const anonymous = makeRoles([WellKnownRoles.Anonymous]);
const username = getUserName(userIdentityToken);
if (username === "anonymous") {
return anonymous;
}
if (!this.server || !this.server.userManager) {
return anonymous;
}
assert(this.server != null, "expecting a server");
if (typeof this.server.userManager.getUserRoles !== "function") {
return anonymous;
}
const rolesNodeId = this.server.userManager.getUserRoles(username);
if (rolesNodeId.findIndex((r) => r.namespace === 0 && r.value === WellKnownRoles.AuthenticatedUser) < 0) {
rolesNodeId.push(resolveNodeId(WellKnownRoles.AuthenticatedUser));
}
return rolesNodeId;
}
public getApplicableRolePermissions(node: BaseNode): RolePermissionType[] | null {
if (!node.rolePermissions) {
const namespace = node.namespace as NamespacePrivate;
const defaultUserRolePermissions = getDefaultUserRolePermissionsOnNamespace(namespace, this);
return defaultUserRolePermissions;
}
return node.rolePermissions;
}
public getPermissions(node: BaseNode): PermissionFlag {
const applicableRolePermissions = this.getApplicableRolePermissions(node);
const roles = this.getCurrentUserRoles();
if (roles.length === 0) {
return allPermissions;
}
let orFlags: PermissionFlag = 0;
for (const role of roles) {
orFlags = orFlags | getPermissionForRole(applicableRolePermissions, role);
}
return orFlags;
}
public getAccessRestrictions(node: BaseNode): AccessRestrictionsFlag {
if (node.accessRestrictions === undefined) {
const namespace = node.namespace as NamespacePrivate;
const accessRestrictions = getAccessRestrictionsOnNamespace(namespace, this);
return accessRestrictions;
}
return node.accessRestrictions;
}
/**
*
* @param node
* @returns true if the browse is denied (access is restricted)
*/
public isBrowseAccessRestricted(node: BaseNode): boolean {
if (this.checkPermission(node, PermissionType.Browse)) {
return false; // can browse
}
return true; // browse restriction
}
/**
*
* @param node
* @returns true if the context is access restricted
*/
public isAccessRestricted(node: BaseNode): boolean {
const accessRestrictions = this.getAccessRestrictions(node);
if (accessRestrictions === AccessRestrictionsFlag.None) {
return false;
}
if (accessRestrictions & AccessRestrictionsFlag.SessionRequired) {
if (!this.session) {
return true;
}
}
const securityMode = this.session?.channel?.securityMode;
if (accessRestrictions & AccessRestrictionsFlag.SigningRequired) {
if (securityMode !== MessageSecurityMode.Sign && securityMode !== MessageSecurityMode.SignAndEncrypt) {
return true;
}
}
if (accessRestrictions & AccessRestrictionsFlag.EncryptionRequired) {
if (securityMode !== MessageSecurityMode.SignAndEncrypt) {
return true;
}
}
return false;
}
/**
* @method checkPermission
* @param node
* @param requestedPermission
* @return {Boolean} returns true of the current user is granted the requested Permission
*/
public checkPermission(node: BaseNode, requestedPermission: PermissionType): boolean {
const permissions = this.getPermissions(node);
return (permissions & requestedPermission) === requestedPermission;
}
public currentUserHasRole(role: NodeIdLike): boolean {
const currentUserRole = this.getCurrentUserRoles();
const n = resolveNodeId(role);
return currentUserRole.findIndex((r) => sameNodeId(r, n)) >= 0;
}
} | the_stack |
import { join } from 'path';
import tar from 'tar';
import {
readdirSync,
statSync,
writeFileSync,
copySync,
ensureDirSync,
pathExistsSync,
readJsonSync,
removeSync,
PathOrFileDescriptor,
} from 'fs-extra';
import fetch from 'electron-fetch';
import ServiceModel from '../../models/Service';
import RecipePreviewModel from '../../models/RecipePreview';
import RecipeModel from '../../models/Recipe';
import UserModel from '../../models/User';
import { sleep } from '../../helpers/async-helpers';
import { SERVER_NOT_LOADED } from '../../config';
import { userDataRecipesPath, userDataPath } from '../../environment-remote';
import { asarRecipesPath } from '../../helpers/asar-helpers';
import apiBase from '../apiBase';
import { prepareAuthRequest, sendAuthRequest } from '../utils/auth';
import {
getRecipeDirectory,
getDevRecipeDirectory,
loadRecipeConfig,
} from '../../helpers/recipe-helpers';
import { removeServicePartitionDirectory } from '../../helpers/service-helpers';
const debug = require('debug')('Ferdi:ServerApi');
module.paths.unshift(getDevRecipeDirectory(), getRecipeDirectory());
export default class ServerApi {
recipePreviews: any[] = [];
recipes: any[] = [];
// User
async login(email: string, passwordHash: string) {
const request = await sendAuthRequest(
`${apiBase()}/auth/login`,
{
method: 'POST',
headers: {
Authorization: `Basic ${window.btoa(`${email}:${passwordHash}`)}`,
},
},
false,
);
if (!request.ok) {
throw new Error(request.statusText);
}
const u = await request.json();
debug('ServerApi::login resolves', u);
return u.token;
}
async signup(data: any) {
const request = await sendAuthRequest(
`${apiBase()}/auth/signup`,
{
method: 'POST',
body: JSON.stringify(data),
},
false,
);
if (!request.ok) {
throw new Error(request.statusText);
}
const u = await request.json();
debug('ServerApi::signup resolves', u);
return u.token;
}
async inviteUser(data: any) {
const request = await sendAuthRequest(`${apiBase()}/invite`, {
method: 'POST',
body: JSON.stringify(data),
});
if (!request.ok) {
throw new Error(request.statusText);
}
debug('ServerApi::inviteUser');
return true;
}
async retrievePassword(email: string) {
const request = await sendAuthRequest(
`${apiBase()}/auth/password`,
{
method: 'POST',
body: JSON.stringify({
email,
}),
},
false,
);
if (!request.ok) {
throw new Error(request.statusText);
}
const r = await request.json();
debug('ServerApi::retrievePassword');
return r;
}
async userInfo() {
if (apiBase() === SERVER_NOT_LOADED) {
throw new Error('Server not loaded');
}
const request = await sendAuthRequest(`${apiBase()}/me`);
if (!request.ok) {
throw new Error(request.statusText);
}
const data = await request.json();
const user = new UserModel(data);
debug('ServerApi::userInfo resolves', user);
return user;
}
async updateUserInfo(data: any) {
const request = await sendAuthRequest(`${apiBase()}/me`, {
method: 'PUT',
body: JSON.stringify(data),
});
if (!request.ok) {
throw new Error(request.statusText);
}
const updatedData = await request.json();
const user = Object.assign(updatedData, {
data: new UserModel(updatedData.data),
});
debug('ServerApi::updateUserInfo resolves', user);
return user;
}
async deleteAccount() {
const request = await sendAuthRequest(`${apiBase()}/me`, {
method: 'DELETE',
});
if (!request.ok) {
throw new Error(request.statusText);
}
const data = await request.json();
debug('ServerApi::deleteAccount resolves', data);
return data;
}
// Services
async getServices() {
if (apiBase() === SERVER_NOT_LOADED) {
throw new Error('Server not loaded');
}
const request = await sendAuthRequest(`${apiBase()}/me/services`);
if (!request.ok) {
throw new Error(request.statusText);
}
const data = await request.json();
const services = await this._mapServiceModels(data);
const filteredServices = services.filter(service => !!service);
debug('ServerApi::getServices resolves', filteredServices);
return filteredServices;
}
async createService(recipeId: string, data: { iconFile: any }) {
const request = await sendAuthRequest(`${apiBase()}/service`, {
method: 'POST',
body: JSON.stringify({ recipeId, ...data }),
});
if (!request.ok) {
throw new Error(request.statusText);
}
const serviceData = await request.json();
if (data.iconFile) {
const iconData = await this.uploadServiceIcon(
serviceData.data.id,
data.iconFile,
);
serviceData.data = iconData;
}
const service = Object.assign(serviceData, {
data: await this._prepareServiceModel(serviceData.data),
});
debug('ServerApi::createService resolves', service);
return service;
}
async updateService(serviceId: string, rawData: any) {
const data = rawData;
if (data.iconFile) {
await this.uploadServiceIcon(serviceId, data.iconFile);
}
const request = await sendAuthRequest(`${apiBase()}/service/${serviceId}`, {
method: 'PUT',
body: JSON.stringify(data),
});
if (!request.ok) {
throw new Error(request.statusText);
}
const serviceData = await request.json();
const service = Object.assign(serviceData, {
data: await this._prepareServiceModel(serviceData.data),
});
debug('ServerApi::updateService resolves', service);
return service;
}
async uploadServiceIcon(serviceId: string, icon: string | Blob) {
const formData = new FormData();
formData.append('icon', icon);
const requestData = prepareAuthRequest({
method: 'PUT',
// @ts-expect-error Argument of type '{ method: string; body: FormData; }' is not assignable to parameter of type '{ method: string; }'.
body: formData,
});
delete requestData.headers['Content-Type'];
const request = await window.fetch(
`${apiBase()}/service/${serviceId}`,
// @ts-expect-error Argument of type '{ method: string; } & { mode: string; headers: any; }' is not assignable to parameter of type 'RequestInit | undefined'.
requestData,
);
if (!request.ok) {
throw new Error(request.statusText);
}
const serviceData = await request.json();
return serviceData.data;
}
async reorderService(data: any) {
const request = await sendAuthRequest(`${apiBase()}/service/reorder`, {
method: 'PUT',
body: JSON.stringify(data),
});
if (!request.ok) {
throw new Error(request.statusText);
}
const serviceData = await request.json();
debug('ServerApi::reorderService resolves', serviceData);
return serviceData;
}
async deleteService(id: string) {
const request = await sendAuthRequest(`${apiBase()}/service/${id}`, {
method: 'DELETE',
});
if (!request.ok) {
throw new Error(request.statusText);
}
const data = await request.json();
removeServicePartitionDirectory(id, true);
debug('ServerApi::deleteService resolves', data);
return data;
}
// Features
async getDefaultFeatures() {
const request = await sendAuthRequest(`${apiBase()}/features/default`);
if (!request.ok) {
throw new Error(request.statusText);
}
const data = await request.json();
const features = data;
debug('ServerApi::getDefaultFeatures resolves', features);
return features;
}
async getFeatures() {
if (apiBase() === SERVER_NOT_LOADED) {
throw new Error('Server not loaded');
}
const request = await sendAuthRequest(`${apiBase()}/features`);
if (!request.ok) {
throw new Error(request.statusText);
}
const data = await request.json();
const features = data;
debug('ServerApi::getFeatures resolves', features);
return features;
}
// Recipes
async getInstalledRecipes() {
const recipesDirectory = getRecipeDirectory();
const paths = readdirSync(recipesDirectory).filter(
file =>
statSync(join(recipesDirectory, file)).isDirectory() &&
file !== 'temp' &&
file !== 'dev',
);
this.recipes = paths
.map(id => {
// eslint-disable-next-line import/no-dynamic-require
const Recipe = require(id)(RecipeModel);
return new Recipe(loadRecipeConfig(id));
})
.filter(recipe => recipe.id);
// eslint-disable-next-line unicorn/prefer-spread
this.recipes = this.recipes.concat(this._getDevRecipes());
debug('StubServerApi::getInstalledRecipes resolves', this.recipes);
return this.recipes;
}
async getRecipeUpdates(recipeVersions: any) {
const request = await sendAuthRequest(`${apiBase()}/recipes/update`, {
method: 'POST',
body: JSON.stringify(recipeVersions),
});
if (!request.ok) {
throw new Error(request.statusText);
}
const recipes = await request.json();
debug('ServerApi::getRecipeUpdates resolves', recipes);
return recipes;
}
// Recipes Previews
async getRecipePreviews() {
const request = await sendAuthRequest(`${apiBase()}/recipes`);
if (!request.ok) throw new Error(request.statusText);
const data = await request.json();
const recipePreviews = this._mapRecipePreviewModel(data);
debug('ServerApi::getRecipes resolves', recipePreviews);
return recipePreviews;
}
async getFeaturedRecipePreviews() {
// TODO: If we are hitting the internal-server, we need to return an empty list, else we can hit the remote server and get the data
const request = await sendAuthRequest(`${apiBase()}/recipes/popular`);
if (!request.ok) throw new Error(request.statusText);
const data = await request.json();
const recipePreviews = this._mapRecipePreviewModel(data);
debug('ServerApi::getFeaturedRecipes resolves', recipePreviews);
return recipePreviews;
}
async searchRecipePreviews(needle: string) {
const url = `${apiBase()}/recipes/search?needle=${needle}`;
const request = await sendAuthRequest(url);
if (!request.ok) throw new Error(request.statusText);
const data = await request.json();
const recipePreviews = this._mapRecipePreviewModel(data);
debug('ServerApi::searchRecipePreviews resolves', recipePreviews);
return recipePreviews;
}
async getRecipePackage(recipeId: string) {
try {
const recipesDirectory = userDataRecipesPath();
const recipeTempDirectory = join(recipesDirectory, 'temp', recipeId);
const tempArchivePath = join(recipeTempDirectory, 'recipe.tar.gz');
const internalRecipeFile = asarRecipesPath(`${recipeId}.tar.gz`);
ensureDirSync(recipeTempDirectory);
let archivePath: PathOrFileDescriptor;
if (pathExistsSync(internalRecipeFile)) {
debug('[ServerApi::getRecipePackage] Using internal recipe file');
archivePath = internalRecipeFile;
} else {
debug('[ServerApi::getRecipePackage] Downloading recipe from server');
archivePath = tempArchivePath;
const packageUrl = `${apiBase()}/recipes/download/${recipeId}`;
const res = await fetch(packageUrl);
debug('Recipe downloaded', recipeId);
const buffer = await res.buffer();
writeFileSync(archivePath, buffer);
}
debug(archivePath);
await sleep(10);
// @ts-expect-error No overload matches this call.
await tar.x({
file: archivePath,
cwd: recipeTempDirectory,
preservePaths: true,
unlink: true,
preserveOwner: false,
onwarn: x => debug('warn', recipeId, x),
});
await sleep(10);
const { id } = readJsonSync(join(recipeTempDirectory, 'package.json'));
const recipeDirectory = join(recipesDirectory, id);
copySync(recipeTempDirectory, recipeDirectory);
removeSync(recipeTempDirectory);
removeSync(join(recipesDirectory, recipeId, 'recipe.tar.gz'));
return id;
} catch (error) {
console.error(error);
return false;
}
}
// Health Check
async healthCheck() {
if (apiBase() === SERVER_NOT_LOADED) {
throw new Error('Server not loaded');
}
const request = await sendAuthRequest(
`${apiBase(false)}/health`,
{
method: 'GET',
},
false,
);
if (!request.ok) {
throw new Error(request.statusText);
}
debug('ServerApi::healthCheck resolves');
}
async getLegacyServices() {
const file = userDataPath('settings', 'services.json');
try {
const config = readJsonSync(file);
if (Object.prototype.hasOwnProperty.call(config, 'services')) {
const services = await Promise.all(
config.services.map(async (s: { service: any }) => {
const service = s;
const request = await sendAuthRequest(
`${apiBase()}/recipes/${s.service}`,
);
if (request.status === 200) {
const data = await request.json();
// @ts-expect-error Property 'recipe' does not exist on type '{ service: any; }'.
service.recipe = new RecipePreviewModel(data);
}
return service;
}),
);
debug('ServerApi::getLegacyServices resolves', services);
return services;
}
} catch {
console.error('ServerApi::getLegacyServices no config found');
}
return [];
}
// Helper
async _mapServiceModels(services: any[]) {
const recipes = services.map((s: { recipeId: string }) => s.recipeId);
await this._bulkRecipeCheck(recipes);
/* eslint-disable no-return-await */
return Promise.all(
services.map(async (service: any) => this._prepareServiceModel(service)),
);
/* eslint-enable no-return-await */
}
async _prepareServiceModel(service: { recipeId: string }) {
let recipe: undefined;
try {
recipe = this.recipes.find(r => r.id === service.recipeId);
if (!recipe) {
console.warn(`Recipe ${service.recipeId} not loaded`);
return null;
}
return new ServiceModel(service, recipe);
} catch (error) {
debug(error);
return null;
}
}
async _bulkRecipeCheck(unfilteredRecipes: any[]) {
// Filter recipe duplicates as we don't need to download 3 Slack recipes
const recipes = unfilteredRecipes.filter(
(elem: any, pos: number, arr: string | any[]) =>
arr.indexOf(elem) === pos,
);
return Promise.all(
recipes.map(async (recipeId: string) => {
let recipe = this.recipes.find(r => r.id === recipeId);
if (!recipe) {
console.warn(
`Recipe '${recipeId}' not installed, trying to fetch from server`,
);
await this.getRecipePackage(recipeId);
debug('Rerun ServerAPI::getInstalledRecipes');
await this.getInstalledRecipes();
recipe = this.recipes.find(r => r.id === recipeId);
if (!recipe) {
console.warn(`Could not load recipe ${recipeId}`);
return null;
}
}
return recipe;
}),
).catch(error => console.error("Can't load recipe", error));
}
_mapRecipePreviewModel(recipes: any[]) {
return recipes
.map(recipe => {
try {
return new RecipePreviewModel(recipe);
} catch (error) {
console.error(error);
return null;
}
})
.filter(recipe => recipe !== null);
}
_getDevRecipes() {
const recipesDirectory = getDevRecipeDirectory();
try {
const paths = readdirSync(recipesDirectory).filter(
file =>
statSync(join(recipesDirectory, file)).isDirectory() &&
file !== 'temp',
);
const recipes = paths
.map(id => {
let Recipe;
try {
// eslint-disable-next-line import/no-dynamic-require
Recipe = require(id)(RecipeModel);
return new Recipe(loadRecipeConfig(id));
} catch (error) {
console.error(error);
}
return false;
})
.filter(recipe => recipe.id)
.map(data => {
const recipe = data;
recipe.icons = {
svg: `${recipe.path}/icon.svg`,
};
recipe.local = true;
return data;
});
return recipes;
} catch {
debug('Could not load dev recipes');
return false;
}
}
} | the_stack |
import { Evt } from "../lib";
import { getPromiseAssertionApi } from "../tools/testing";
import {getHandlerPr } from "./getHandlerPr";
const { mustResolve, mustReject } = getPromiseAssertionApi();
let op = (object: Object): object is Array<any> => object instanceof Array;
let boundTo = Evt.newCtx();
let timeout = 10;
function mkCb(expect: Object[]) {
expect = [...expect];
let timer = setTimeout(() => console.assert(!expect.length), 2000);
return (object: Object) => {
console.assert(expect.shift() === object);
clearTimeout(timer);
}
}
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = posts.filter(op);
mustResolve({
"promise": evt.attach(op, boundTo, timeout, mkCb(expect)),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = posts.filter(op);
mustResolve({
"promise": evt.attach(op, timeout, mkCb(expect)),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = posts.filter(op);
mustResolve({
"promise": getHandlerPr(
evt,
()=>evt.attach(op, mkCb(expect))
),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = [...posts];
mustResolve({
"promise": getHandlerPr(evt, () => evt.attach(mkCb(expect))),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = [...posts];
mustResolve({
"promise": evt.attach(timeout, mkCb(expect)),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = [...posts];
mustResolve({
"promise": getHandlerPr(evt, ()=> evt.attach(boundTo, mkCb(expect))),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = [...posts];
mustResolve({
"promise": evt.attach(boundTo, timeout, mkCb(expect)),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
mustReject({ "promise": evt.attach(op, timeout, () => { }), "delay": 3000 });
posts.filter(object => !op(object)).forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
mustReject({ "promise": evt.attach(op, boundTo, timeout, () => { }), "delay": 2000 });
posts.filter(object => !op(object)).forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
mustReject({ "promise": evt.attach(boundTo, timeout, () => { }), "delay": 2000 });
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = posts.filter(op);
mustResolve({
"promise": evt.attachPrepend(op, boundTo, timeout, mkCb(expect)),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = posts.filter(op);
mustResolve({
"promise": evt.attachPrepend(op, timeout, mkCb(expect)),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = posts.filter(op);
mustResolve({
"promise": getHandlerPr(evt, ()=> evt.attachPrepend(op, mkCb(expect))),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = [...posts];
mustResolve({
"promise": getHandlerPr(evt, ()=> evt.attachPrepend(mkCb(expect))),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = [...posts];
mustResolve({
"promise": evt.attachPrepend(timeout, mkCb(expect)),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = [...posts];
mustResolve({
"promise": getHandlerPr(evt, ()=>evt.attachPrepend(boundTo, mkCb(expect))),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = [...posts];
mustResolve({
"promise": evt.attachPrepend(boundTo, timeout, mkCb(expect)),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
mustReject({
"promise": evt.attachPrepend(op, timeout, () => { }),
"delay": 2000
});
posts.filter(object => !op(object)).forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
mustReject({ "promise": evt.attachPrepend(op, boundTo, timeout, () => { }), "delay": 2000 });
posts.filter(object => !op(object)).forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
mustReject({ "promise": evt.attachPrepend(boundTo, timeout, () => { }), "delay": 2000 });
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = posts.filter(op);
mustResolve({
"promise": evt.attachOnce(op, boundTo, timeout, mkCb([expect[0]])),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = posts.filter(op);
mustResolve({
"promise": evt.attachOnce(op, timeout, mkCb([expect[0]])),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = posts.filter(op);
mustResolve({
"promise": getHandlerPr(evt, ()=> evt.attachOnce(op, mkCb([expect[0]]))),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = [...posts];
mustResolve({
"promise": getHandlerPr(evt,()=> evt.attachOnce(mkCb([expect[0]]))),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = [...posts];
mustResolve({
"promise": evt.attachOnce(timeout, mkCb([expect[0]])),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = [...posts];
mustResolve({
"promise": getHandlerPr(evt, () => evt.attachOnce(boundTo, mkCb([expect[0]]))),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = [...posts];
mustResolve({
"promise": evt.attachOnce(boundTo, timeout, mkCb([expect[0]])),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
mustReject({
"promise": evt.attachOnce(op, timeout, () => { }),
"delay": 2000
});
posts.filter(object => !op(object)).forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
mustReject({ "promise": evt.attachOnce(op, boundTo, timeout, () => { }), "delay": 2000 });
posts.filter(object => !op(object)).forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
mustReject({ "promise": evt.attachOnce(boundTo, timeout, () => { }), "delay": 2000 });
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = posts.filter(op);
mustResolve({
"promise": evt.attachOnce(op, boundTo, timeout, mkCb([expect[1]])),
"expectedData": expect[1],
"delay": 2000
});
mustResolve({
"promise": evt.attachOnceExtract(op, boundTo, timeout, mkCb([expect[0]])),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = posts.filter(op);
mustResolve({
"promise": evt.attachOnce(op, timeout, mkCb([expect[1]])),
"expectedData": expect[1],
"delay": 2000
});
mustResolve({
"promise": evt.attachOnceExtract(op, timeout, mkCb([expect[0]])),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = posts.filter(op);
mustResolve({
"promise": getHandlerPr(evt,()=> evt.attachOnce(op, mkCb([expect[1]]))),
"expectedData": expect[1],
"delay": 2000
});
mustResolve({
"promise": getHandlerPr(evt, () => evt.attachOnceExtract(op, mkCb([expect[0]]))),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = [...posts];
mustResolve({
"promise": getHandlerPr(evt,()=> evt.attachOnce(mkCb([expect[1]]))),
"expectedData": expect[1],
"delay": 2000
});
mustResolve({
"promise": getHandlerPr(evt,()=> evt.attachOnceExtract(mkCb([expect[0]]))),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = [...posts];
mustResolve({
"promise": evt.attachOnce(timeout, mkCb([expect[1]])),
"expectedData": expect[1],
"delay": 2000
});
mustResolve({
"promise": evt.attachOnceExtract(timeout, mkCb([expect[0]])),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = [...posts];
mustResolve({
"promise": getHandlerPr(evt, ()=> evt.attachOnce(boundTo, mkCb([expect[1]]))),
"expectedData": expect[1],
"delay": 2000
});
mustResolve({
"promise": getHandlerPr(evt, ()=> evt.attachOnceExtract(boundTo, mkCb([expect[0]]))),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
let expect = [...posts];
mustResolve({
"promise": evt.attachOnce(boundTo, timeout, mkCb([expect[1]])),
"expectedData": expect[1],
"delay": 2000
});
mustResolve({
"promise": evt.attachOnceExtract(boundTo, timeout, mkCb([expect[0]])),
"expectedData": expect[0],
"delay": 2000
});
posts.forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
mustReject({
"promise": evt.attachOnceExtract(op, timeout, () => { }),
"delay": 2000
});
posts.filter(object => !op(object)).forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
let posts = [[], [], [], "foo", {}, []];
mustReject({ "promise": evt.attachOnceExtract(op, boundTo, timeout, () => { }), "delay": 2000 });
posts.filter(object => !op(object)).forEach(object => evt.post(object));
})();
(() => {
let evt = new Evt<Object>();
//evt.enableTrace("evt");
mustReject({ "promise": evt.attachOnceExtract(boundTo, timeout, () => { }), "delay": 2000 });
})();
setTimeout(() => {
console.log("PASS");
}, 2100); | the_stack |
import {Mutable, Arrays, Cursor} from "@swim/util";
import {AnyValue, Value, Form} from "@swim/structure";
import {Inlet, Outlet, OutletCombinators} from "@swim/streamlet";
import type {AnyUri, Uri} from "@swim/uri";
import type {DownlinkContext} from "./DownlinkContext";
import type {DownlinkOwner} from "./DownlinkOwner";
import {DownlinkType, DownlinkObserver, DownlinkInit, DownlinkFlags, Downlink} from "./Downlink";
import {ValueDownlinkModel} from "./ValueDownlinkModel";
/** @public */
export type ValueDownlinkWillSet<V, VU = never> = (newValue: V, downlink: ValueDownlink<V, VU>) => V | void;
/** @public */
export type VaueDownlinkDidSet<V, VU = never> = (newValue: V, oldValue: V, downlink: ValueDownlink<V, VU>) => void;
/** @public */
export interface ValueDownlinkObserver<V, VU = never> extends DownlinkObserver {
willSet?: ValueDownlinkWillSet<V, VU>;
didSet?: VaueDownlinkDidSet<V, VU>;
}
/** @public */
export interface ValueDownlinkInit<V, VU = never> extends ValueDownlinkObserver<V, VU>, DownlinkInit {
valueForm?: Form<V, VU>;
}
/** @public */
export class ValueDownlink<V, VU = never> extends Downlink implements Inlet<V>, Outlet<V> {
/** @internal */
constructor(context: DownlinkContext, owner: DownlinkOwner | null, init?: ValueDownlinkInit<V, VU>,
hostUri?: Uri, nodeUri?: Uri, laneUri?: Uri, prio?: number, rate?: number,
body?: Value, flags: number = DownlinkFlags.KeepLinkedSynced,
observers?: ReadonlyArray<ValueDownlinkObserver<V, VU>> | ValueDownlinkObserver<V, VU>,
valueForm?: Form<V, VU>, state0: Value = Value.absent()) {
super(context, owner, init, hostUri, nodeUri, laneUri, prio, rate, body, flags, observers);
if (init !== void 0) {
const observer = this.observers[this.observers.length - 1]!;
observer.willSet = init.willSet ?? observer.willSet;
observer.didSet = init.didSet ?? observer.didSet;
valueForm = init.valueForm !== void 0 ? init.valueForm : valueForm;
}
this.ownValueForm = valueForm !== void 0 ? valueForm : Form.forValue() as unknown as Form<V, VU>;
this.state0 = state0;
this.input = null;
this.outputs = Arrays.empty;
this.version = -1;
}
/** @internal */
override readonly model!: ValueDownlinkModel | null;
/** @internal */
override observers!: ReadonlyArray<ValueDownlinkObserver<V, VU>>;
/** @internal */
readonly ownValueForm: Form<V, VU>;
/** @internal */
readonly state0: Value;
override get type(): DownlinkType {
return "value";
}
/** @internal */
protected override copy<V, VU>(context: DownlinkContext, owner: DownlinkOwner | null,
hostUri: Uri, nodeUri: Uri, laneUri: Uri, prio: number, rate: number,
body: Value, flags: number, observers: ReadonlyArray<ValueDownlinkObserver<V, VU>>,
valueForm?: Form<V, VU>, state0?: Value): ValueDownlink<V, VU> {
if (arguments.length === 10) {
state0 = this.state0;
valueForm = this.ownValueForm as unknown as Form<V, VU>;
}
return new ValueDownlink(context, owner, void 0, hostUri, nodeUri, laneUri,
prio, rate, body, flags, observers, valueForm, state0);
}
valueForm(): Form<V, VU>;
valueForm<V2, V2U = never>(valueForm: Form<V2, V2U>): ValueDownlink<V2, V2U>;
valueForm<V2, V2U = never>(valueForm?: Form<V2, V2U>): Form<V, VU> | ValueDownlink<V2, V2U> {
if (valueForm === void 0) {
return this.ownValueForm;
} else {
return this.copy(this.context, this.owner, this.ownHostUri, this.ownNodeUri, this.ownLaneUri,
this.ownPrio, this.ownRate, this.ownBody, this.flags, this.observers as any,
valueForm, this.state0);
}
}
get(): V {
const value = this.model!.get();
const object = value.coerce(this.ownValueForm);
return object;
}
set(newObject: V | VU): void {
const newValue = this.ownValueForm.mold(newObject);
this.model!.set(newValue);
}
setState(state: Value): void {
this.model!.setState(state);
}
override observe(observer: ValueDownlinkObserver<V, VU>): this {
return super.observe(observer);
}
willSet(willSet: ValueDownlinkWillSet<V, VU>): this {
return this.observe({willSet});
}
didSet(didSet: VaueDownlinkDidSet<V, VU>): this {
return this.observe({didSet});
}
/** @internal */
valueWillSet(newValue: Value): Value {
let newObject: V | undefined;
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.willSet !== void 0) {
if (newObject === void 0) {
newObject = newValue.coerce(this.ownValueForm);
}
const newResult = observer.willSet(newObject, this);
if (newResult !== void 0) {
newObject = newResult;
newValue = this.ownValueForm.mold(newObject);
}
}
}
return newValue;
}
/** @internal */
valueDidSet(newValue: Value, oldValue: Value): void {
let newObject: V | undefined;
let oldObject: V | undefined;
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.didSet !== void 0) {
if (newObject === void 0) {
newObject = newValue.coerce(this.ownValueForm);
}
if (oldObject === void 0) {
oldObject = oldValue.coerce(this.ownValueForm);
}
observer.didSet(newObject, oldObject, this);
}
}
this.decohere();
this.recohere(0); // TODO: debounce update; track version
}
initialState(): Value;
initialState(state0: Value): ValueDownlink<V, VU>;
initialState(state0?: Value): Value | ValueDownlink<V, VU> {
if (state0 === void 0) {
return this.state0;
} else {
return this.copy(this.context, this.owner, this.ownHostUri, this.ownNodeUri, this.ownLaneUri,
this.ownPrio, this.ownRate, this.ownBody, this.flags, this.observers,
this.ownValueForm, state0);
}
}
/** @internal */
protected didAliasModel(): void {
this.onLinkedResponse();
this.valueDidSet(this.model!.get(), Value.absent());
this.onSyncedResponse();
}
override open(): this {
const laneUri = this.ownLaneUri;
if (laneUri.isEmpty()) {
throw new Error("no lane");
}
let nodeUri = this.ownNodeUri;
if (nodeUri.isEmpty()) {
throw new Error("no node");
}
let hostUri = this.ownHostUri;
if (hostUri.isEmpty()) {
hostUri = nodeUri.endpoint();
nodeUri = hostUri.unresolve(nodeUri);
}
let model = this.context.getDownlink(hostUri, nodeUri, laneUri);
if (model !== void 0) {
if (!(model instanceof ValueDownlinkModel)) {
throw new Error("downlink type mismatch");
}
model.addDownlink(this);
(this as Mutable<this>).model = model as ValueDownlinkModel;
setTimeout(this.didAliasModel.bind(this));
} else {
model = new ValueDownlinkModel(this.context, hostUri, nodeUri, laneUri, this.ownPrio,
this.ownRate, this.ownBody, this.state0);
model.addDownlink(this);
this.context.openDownlink(model);
(this as Mutable<this>).model = model as ValueDownlinkModel;
}
if (this.owner !== null) {
this.owner.addDownlink(this);
}
return this;
}
readonly input: Outlet<V> | null;
/** @internal */
readonly outputs: ReadonlyArray<Inlet<V>>;
/** @internal */
readonly version: number;
bindInput(newInput: Outlet<V> | null): void {
const oldInput = this.input;
if (oldInput !== newInput) {
if (oldInput !== null) {
oldInput.unbindOutput(this);
}
(this as Mutable<this>).input = newInput;
if (newInput !== null) {
newInput.bindOutput(this);
}
}
}
unbindInput(): void {
const oldInput = this.input;
if (oldInput !== null) {
oldInput.unbindOutput(this);
(this as Mutable<this>).input = null;
}
}
disconnectInputs(): void {
const oldInput = this.input;
if (oldInput !== null) {
oldInput.unbindOutput(this);
(this as Mutable<this>).input = null;
oldInput.disconnectInputs();
}
}
outputIterator(): Cursor<Inlet<V>> {
return Cursor.array(this.outputs);
}
bindOutput(output: Inlet<V>): void {
(this as Mutable<this>).outputs = Arrays.inserted(output, this.outputs);
}
unbindOutput(output: Inlet<V>): void {
(this as Mutable<this>).outputs = Arrays.removed(output, this.outputs);
}
unbindOutputs(): void {
const oldOutputs = this.outputs;
(this as Mutable<this>).outputs = Arrays.empty;
for (let i = 0, n = oldOutputs.length; i < n; i += 1) {
const output = oldOutputs[i]!;
output.unbindInput();
}
}
disconnectOutputs(): void {
const oldOutputs = this.outputs;
(this as Mutable<this>).outputs = Arrays.empty;
for (let i = 0, n = oldOutputs.length; i < n; i += 1) {
const output = oldOutputs[i]!;
output.unbindInput();
output.disconnectOutputs();
}
}
decohereOutput(): void {
this.decohere();
}
decohereInput(): void {
this.decohere();
}
decohere(): void {
if (this.version >= 0) {
this.willDecohere();
(this as Mutable<this>).version = -1;
this.onDecohere();
const outputs = this.outputs;
for (let i = 0, n = outputs.length; i < n; i += 1) {
outputs[i]!.decohereOutput();
}
this.didDecohere();
}
}
recohereOutput(version: number): void {
this.recohere(version);
}
recohereInput(version: number): void {
this.recohere(version);
}
recohere(version: number): void {
if (this.version < 0) {
this.willRecohere(version);
(this as Mutable<this>).version = version;
if (this.input !== null) {
this.input.recohereInput(version);
}
this.onRecohere(version);
const outputs = this.outputs;
for (let i = 0, n = outputs.length; i < n; i += 1) {
outputs[i]!.recohereOutput(version);
}
this.didRecohere(version);
}
}
protected willDecohere(): void {
// hook
}
protected onDecohere(): void {
// hook
}
protected didDecohere(): void {
// hook
}
protected willRecohere(version: number): void {
// hook
}
protected onRecohere(version: number): void {
const input = this.input;
if (input !== null) {
const value = input.get();
if (value !== void 0) {
this.set(value);
}
}
}
protected didRecohere(version: number): void {
// hook
}
}
/** @public */
export interface ValueDownlink<V, VU> {
hostUri(): Uri;
hostUri(hostUri: AnyUri): ValueDownlink<V, VU>;
nodeUri(): Uri;
nodeUri(nodeUri: AnyUri): ValueDownlink<V, VU>;
laneUri(): Uri;
laneUri(laneUri: AnyUri): ValueDownlink<V, VU>;
prio(): number;
prio(prio: number): ValueDownlink<V, VU>;
rate(): number;
rate(rate: number): ValueDownlink<V, VU>;
body(): Value;
body(body: AnyValue): ValueDownlink<V, VU>;
keepLinked(): boolean;
keepLinked(keepLinked: boolean): ValueDownlink<V, VU>;
keepSynced(): boolean;
keepSynced(keepSynced: boolean): ValueDownlink<V, VU>;
}
/** @public */
export interface ValueDownlink<V, VU> extends OutletCombinators<V> {
}
OutletCombinators.define(ValueDownlink.prototype); | the_stack |
import mapValues from 'lodash/mapValues'
import type { Action, Error } from '../../types'
import { HOME } from '../../robot-controls'
import type { Mount, Slot } from '../types'
import { actionTypes } from '../actions'
import type {
ConfirmProbedAction,
PipetteCalibrationAction,
LabwareCalibrationAction,
CalibrationSuccessAction,
CalibrationFailureAction,
SetModulesReviewedAction,
ReturnTipResponseAction,
ReturnTipAction,
SetDeckPopulatedAction,
MoveToFrontAction,
MoveToFrontResponseAction,
ProbeTipAction,
ProbeTipResponseAction,
ConfirmLabwareAction,
} from '../actions'
// calibration request types
// TODO(mc, 2018-01-10): these should match up with the request actions;
// explore how to link these concepts effectively
type CalibrationRequestType =
| ''
| 'MOVE_TO_FRONT'
| 'PROBE_TIP'
| 'MOVE_TO'
| 'JOG'
| 'PICKUP_AND_HOME'
| 'DROP_TIP_AND_HOME'
| 'CONFIRM_TIPRACK'
| 'UPDATE_OFFSET'
| 'SET_MODULES_REVIEWED'
| 'RETURN_TIP'
export interface CalibrationRequest {
readonly type: CalibrationRequestType
readonly mount?: Mount
readonly slot?: Slot
readonly inProgress: boolean
readonly error: Error | null
}
export interface CalibrationState {
readonly deckPopulated: boolean | null | undefined
readonly modulesReviewed: boolean | null | undefined
readonly probedByMount: { [mount in Mount]?: boolean }
readonly tipOnByMount: { [mount in Mount]?: boolean }
readonly confirmedBySlot: { [slot in Slot]?: boolean }
readonly calibrationRequest: CalibrationRequest
}
// TODO(mc, 2018-01-11): replace actionType constants with Flow types
const {
SET_DECK_POPULATED,
MOVE_TO_FRONT,
MOVE_TO_FRONT_RESPONSE,
PROBE_TIP,
PROBE_TIP_RESPONSE,
CONFIRM_LABWARE,
} = actionTypes
const INITIAL_STATE: CalibrationState = {
deckPopulated: null,
modulesReviewed: null,
// TODO(mc, 2018-01-22): combine these into subreducer
probedByMount: {},
tipOnByMount: {},
confirmedBySlot: {},
calibrationRequest: { type: '', inProgress: false, error: null },
}
export function calibrationReducer(
state: CalibrationState = INITIAL_STATE,
action: Action
): CalibrationState {
switch (action.type) {
case 'robot:DISCONNECT_RESPONSE':
case 'robot:REFRESH_SESSION':
case 'protocol:UPLOAD':
return INITIAL_STATE
// reset calibration state on robot home
case HOME:
case 'robot:CLEAR_CALIBRATION_REQUEST':
return {
...state,
calibrationRequest: { type: '', inProgress: false, error: null },
}
case 'robot:CONFIRM_PROBED':
return handleConfirmProbed(state, action)
case 'robot:MOVE_TO':
return handleMoveTo(state, action)
case 'robot:MOVE_TO_SUCCESS':
return handleMoveToSuccess(state, action)
case 'robot:MOVE_TO_FAILURE':
return handleMoveToFailure(state, action)
case 'robot:JOG':
return handleJog(state, action)
case 'robot:JOG_SUCCESS':
return handleJogSuccess(state, action)
case 'robot:JOG_FAILURE':
return handleJogFailure(state, action)
case 'robot:PICKUP_AND_HOME':
return handlePickupAndHome(state, action)
case 'robot:PICKUP_AND_HOME_SUCCESS':
return handlePickupAndHomeSuccess(state, action)
case 'robot:PICKUP_AND_HOME_FAILURE':
return handlePickupAndHomeFailure(state, action)
case 'robot:DROP_TIP_AND_HOME':
return handleDropTipAndHome(state, action)
case 'robot:DROP_TIP_AND_HOME_SUCCESS':
return handleDropTipAndHomeSuccess(state, action)
case 'robot:DROP_TIP_AND_HOME_FAILURE':
return handleDropTipAndHomeFailure(state, action)
case 'robot:CONFIRM_TIPRACK':
return handleConfirmTiprack(state, action)
case 'robot:CONFIRM_TIPRACK_SUCCESS':
return handleConfirmTiprackSuccess(state, action)
case 'robot:CONFIRM_TIPRACK_FAILURE':
return handleConfirmTiprackFailure(state, action)
case 'robot:UPDATE_OFFSET':
return handleUpdateOffset(state, action)
case 'robot:UPDATE_OFFSET_SUCCESS':
return handleUpdateOffsetSuccess(state, action)
case 'robot:UPDATE_OFFSET_FAILURE':
return handleUpdateOffsetFailure(state, action)
case 'robot:SET_MODULES_REVIEWED':
return handleSetModulesReviewed(state, action)
case 'robot:RETURN_TIP':
return handleReturnTip(state, action)
case 'robot:RETURN_TIP_RESPONSE':
return handleReturnTipResponse(state, action)
// TODO(mc, 20187-01-26): caution - not covered by flow yet
case SET_DECK_POPULATED:
return handleSetDeckPopulated(state, action as any)
case MOVE_TO_FRONT:
return handleMoveToFront(state, action as any)
case MOVE_TO_FRONT_RESPONSE:
return handleMoveToFrontResponse(state, action as any)
case PROBE_TIP:
return handleProbeTip(state, action as any)
case PROBE_TIP_RESPONSE:
return handleProbeTipResponse(state, action as any)
case CONFIRM_LABWARE:
return handleConfirmLabware(state, action as any)
}
return state
}
function handleSetDeckPopulated(
state: CalibrationState,
action: SetDeckPopulatedAction
): CalibrationState {
return { ...state, deckPopulated: action.payload }
}
function handleSetModulesReviewed(
state: CalibrationState,
action: SetModulesReviewedAction
): CalibrationState {
return { ...state, modulesReviewed: action.payload }
}
function handleMoveToFront(
state: CalibrationState,
action: MoveToFrontAction
): CalibrationState {
if (!action.payload || !action.payload.mount) return state
const {
payload: { mount },
} = action
return {
...state,
deckPopulated: false,
modulesReviewed: false,
calibrationRequest: {
type: 'MOVE_TO_FRONT',
inProgress: true,
error: null,
mount,
},
}
}
function handleMoveToFrontResponse(
state: CalibrationState,
action: MoveToFrontResponseAction
): CalibrationState {
const error = action.error && action.payload ? action.payload : null
return {
...state,
calibrationRequest: {
...state.calibrationRequest,
inProgress: false,
error,
},
}
}
function handleProbeTip(
state: CalibrationState,
action: ProbeTipAction
): CalibrationState {
if (!action.payload || !action.payload.mount) return state
const { mount } = action.payload
const probedByMount = { ...state.probedByMount }
probedByMount[mount] = false
return {
...state,
calibrationRequest: {
type: 'PROBE_TIP',
mount: mount,
inProgress: true,
error: null,
},
probedByMount,
}
}
function handleProbeTipResponse(
state: CalibrationState,
action: ProbeTipResponseAction
): CalibrationState {
const { payload, error } = action
return {
...state,
calibrationRequest: {
...state.calibrationRequest,
inProgress: false,
error: error && payload ? payload : null,
},
confirmedBySlot: {},
}
}
function handleConfirmProbed(
state: CalibrationState,
action: ConfirmProbedAction
): CalibrationState {
const nextProbedByMount = { ...state.probedByMount }
nextProbedByMount[action.payload] = true
return { ...state, probedByMount: nextProbedByMount }
}
function handleMoveTo(
state: CalibrationState,
action: LabwareCalibrationAction
): CalibrationState {
const { mount, slot } = action.payload
return {
...state,
deckPopulated: true,
modulesReviewed: true,
calibrationRequest: {
type: 'MOVE_TO',
inProgress: true,
error: null,
mount,
slot,
},
}
}
function handleMoveToSuccess(
state: CalibrationState,
action: CalibrationSuccessAction
): CalibrationState {
const {
calibrationRequest: { slot },
} = state
if (!slot) return state
return {
...state,
calibrationRequest: {
...state.calibrationRequest,
inProgress: false,
error: null,
},
}
}
function handleMoveToFailure(
state: CalibrationState,
action: CalibrationFailureAction
): CalibrationState {
const {
calibrationRequest: { slot },
} = state
if (!slot) return state
const error = action.payload
return {
...state,
calibrationRequest: {
...state.calibrationRequest,
inProgress: false,
error: error,
},
}
}
function handlePickupAndHome(
state: CalibrationState,
action: LabwareCalibrationAction
): CalibrationState {
const {
payload: { mount, slot },
} = action
return {
...state,
deckPopulated: true,
modulesReviewed: true,
calibrationRequest: {
type: 'PICKUP_AND_HOME',
inProgress: true,
error: null,
mount,
slot,
},
}
}
function handlePickupAndHomeSuccess(
state: CalibrationState,
action: CalibrationSuccessAction
): CalibrationState {
const { calibrationRequest, tipOnByMount } = state
const { mount, slot } = calibrationRequest
if (!slot || !mount) return state
// assume that only one tip can be on at a time
const nextTipOnByMount = mapValues(tipOnByMount, () => false)
nextTipOnByMount[mount] = true
return {
...state,
calibrationRequest: {
...calibrationRequest,
inProgress: false,
error: null,
},
tipOnByMount: nextTipOnByMount,
}
}
function handlePickupAndHomeFailure(
state: CalibrationState,
action: CalibrationFailureAction
): CalibrationState {
const {
calibrationRequest: { mount, slot },
} = state
if (!slot || !mount) return state
const error = action.payload
return {
...state,
calibrationRequest: {
...state.calibrationRequest,
inProgress: false,
error,
},
}
}
function handleDropTipAndHome(
state: CalibrationState,
action: LabwareCalibrationAction
): CalibrationState {
const {
payload: { mount, slot },
} = action
return {
...state,
calibrationRequest: {
type: 'DROP_TIP_AND_HOME',
inProgress: true,
error: null,
mount,
slot,
},
}
}
function handleDropTipAndHomeSuccess(
state: CalibrationState,
action: CalibrationSuccessAction
): CalibrationState {
const { calibrationRequest, tipOnByMount } = state
const { mount, slot } = calibrationRequest
if (!slot || !mount) return state
// assume that only one tip can be on at a time
const nextTipOnByMount = { ...tipOnByMount }
nextTipOnByMount[mount] = false
return {
...state,
calibrationRequest: {
...calibrationRequest,
inProgress: false,
error: null,
},
tipOnByMount: nextTipOnByMount,
}
}
function handleDropTipAndHomeFailure(
state: CalibrationState,
action: CalibrationFailureAction
): CalibrationState {
const {
calibrationRequest: { mount, slot },
} = state
if (!slot || !mount) return state
const error = action.payload
return {
...state,
calibrationRequest: {
...state.calibrationRequest,
inProgress: false,
error,
},
}
}
function handleConfirmTiprack(
state: CalibrationState,
action: LabwareCalibrationAction
): CalibrationState {
const {
payload: { mount, slot },
} = action
return {
...state,
calibrationRequest: {
type: 'CONFIRM_TIPRACK',
inProgress: true,
error: null,
mount,
slot,
},
}
}
function handleConfirmTiprackSuccess(
state: CalibrationState,
action: CalibrationSuccessAction
): CalibrationState {
const { calibrationRequest, tipOnByMount, confirmedBySlot } = state
const { mount, slot } = calibrationRequest
if (!slot || !mount) return state
const tipOn = action.payload.tipOn || false
const nextTipOnByMount = { ...tipOnByMount }
const nextConfirmedBySlot = { ...confirmedBySlot }
nextTipOnByMount[mount] = tipOn
nextConfirmedBySlot[slot] = true
return {
...state,
calibrationRequest: {
...calibrationRequest,
inProgress: false,
error: null,
},
tipOnByMount: nextTipOnByMount,
confirmedBySlot: nextConfirmedBySlot,
}
}
function handleConfirmTiprackFailure(
state: CalibrationState,
action: CalibrationFailureAction
): CalibrationState {
const {
calibrationRequest: { mount, slot },
} = state
if (!slot || !mount) return state
const error = action.payload
return {
...state,
calibrationRequest: {
...state.calibrationRequest,
inProgress: false,
error,
},
}
}
function handleJog(
state: CalibrationState,
action: PipetteCalibrationAction
): CalibrationState {
const {
payload: { mount },
} = action
return {
...state,
calibrationRequest: {
// make sure we hang on to any state from a previous labware calibration
...state.calibrationRequest,
type: 'JOG',
inProgress: true,
error: null,
mount,
},
}
}
function handleJogSuccess(
state: CalibrationState,
action: CalibrationSuccessAction
): CalibrationState {
return {
...state,
calibrationRequest: {
...state.calibrationRequest,
inProgress: false,
error: null,
},
}
}
function handleJogFailure(
state: CalibrationState,
action: CalibrationFailureAction
): CalibrationState {
const error = action.payload
return {
...state,
calibrationRequest: {
...state.calibrationRequest,
inProgress: false,
error,
},
}
}
function handleUpdateOffset(
state: CalibrationState,
action: LabwareCalibrationAction
): CalibrationState {
const {
payload: { mount, slot },
} = action
return {
...state,
calibrationRequest: {
type: 'UPDATE_OFFSET',
inProgress: true,
error: null,
mount,
slot,
},
}
}
function handleUpdateOffsetSuccess(
state: CalibrationState,
action: CalibrationSuccessAction
): CalibrationState {
const { calibrationRequest, confirmedBySlot } = state
const { mount, slot } = calibrationRequest
if (!slot || !mount) return state
const nextConfirmBySlot = { ...confirmedBySlot }
nextConfirmBySlot[slot] = true
return {
...state,
calibrationRequest: {
...calibrationRequest,
inProgress: false,
error: null,
},
confirmedBySlot: nextConfirmBySlot,
}
}
function handleUpdateOffsetFailure(
state: CalibrationState,
action: CalibrationFailureAction
): CalibrationState {
const {
calibrationRequest: { mount, slot },
} = state
if (!mount || !slot) return state
const error = action.payload
return {
...state,
calibrationRequest: {
...state.calibrationRequest,
inProgress: false,
error,
},
}
}
function handleConfirmLabware(
state: CalibrationState,
action: ConfirmLabwareAction
): CalibrationState {
if (!action.payload || !action.payload.labware) return state
const { labware: slot } = action.payload
const confirmedBySlot = { ...state.confirmedBySlot }
confirmedBySlot[slot] = true
return { ...state, confirmedBySlot }
}
function handleReturnTip(
state: CalibrationState,
action: ReturnTipAction
): CalibrationState {
const {
payload: { mount },
} = action
return {
...state,
calibrationRequest: {
type: 'RETURN_TIP',
inProgress: true,
error: null,
mount,
},
}
}
function handleReturnTipResponse(
state: CalibrationState,
action: ReturnTipResponseAction
): CalibrationState {
const { calibrationRequest, tipOnByMount } = state
const { mount } = calibrationRequest
if (!mount) return state
const error = action.error && action.payload ? action.payload : null
const nextTipOnByMount = { ...tipOnByMount }
nextTipOnByMount[mount] = false
return {
...state,
calibrationRequest: {
...calibrationRequest,
inProgress: false,
error,
},
tipOnByMount: nextTipOnByMount,
}
} | the_stack |
import { Injectable } from '@angular/core';
import { CoreFileUploaderStoreFilesResult } from '@features/fileuploader/services/fileuploader';
import { CoreFile } from '@services/file';
import { CoreSites } from '@services/sites';
import { CoreTextUtils } from '@services/utils/text';
import { makeSingleton } from '@singletons';
import { AddonModForumProvider } from './forum';
import {
AddonModForumOfflineDiscussionDBRecord,
AddonModForumOfflineReplyDBRecord,
DISCUSSIONS_TABLE,
REPLIES_TABLE,
} from './database/offline';
/**
* Service to handle offline forum.
*/
@Injectable({ providedIn: 'root' })
export class AddonModForumOfflineProvider {
/**
* Delete a forum offline discussion.
*
* @param forumId Forum ID.
* @param timeCreated The time the discussion was created.
* @param siteId Site ID. If not defined, current site.
* @param userId User the discussion belongs to. If not defined, current user in site.
* @return Promise resolved if stored, rejected if failure.
*/
async deleteNewDiscussion(forumId: number, timeCreated: number, siteId?: string, userId?: number): Promise<void> {
const site = await CoreSites.getSite(siteId);
const conditions = {
forumid: forumId,
userid: userId || site.getUserId(),
timecreated: timeCreated,
};
await site.getDb().deleteRecords(DISCUSSIONS_TABLE, conditions);
}
/**
* Get a forum offline discussion.
*
* @param forumId Forum ID.
* @param timeCreated The time the discussion was created.
* @param siteId Site ID. If not defined, current site.
* @param userId User the discussion belongs to. If not defined, current user in site.
* @return Promise resolved if stored, rejected if failure.
*/
async getNewDiscussion(
forumId: number,
timeCreated: number,
siteId?: string,
userId?: number,
): Promise<AddonModForumOfflineDiscussion> {
const site = await CoreSites.getSite(siteId);
const conditions = {
forumid: forumId,
userid: userId || site.getUserId(),
timecreated: timeCreated,
};
const record = await site.getDb().getRecord<AddonModForumOfflineDiscussionDBRecord>(DISCUSSIONS_TABLE, conditions);
return this.parseRecordOptions(record);
}
/**
* Get all offline new discussions.
*
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with discussions.
*/
async getAllNewDiscussions(siteId?: string): Promise<AddonModForumOfflineDiscussion[]> {
const site = await CoreSites.getSite(siteId);
const records = await site.getDb().getRecords<AddonModForumOfflineDiscussionDBRecord>(DISCUSSIONS_TABLE);
return this.parseRecordsOptions(records);
}
/**
* Check if there are offline new discussions to send.
*
* @param forumId Forum ID.
* @param siteId Site ID. If not defined, current site.
* @param userId User the discussions belong to. If not defined, current user in site.
* @return Promise resolved with boolean: true if has offline answers, false otherwise.
*/
async hasNewDiscussions(forumId: number, siteId?: string, userId?: number): Promise<boolean> {
try {
const discussions = await this.getNewDiscussions(forumId, siteId, userId);
return !!discussions.length;
} catch (error) {
// No offline data found, return false.
return false;
}
}
/**
* Get new discussions to be synced.
*
* @param forumId Forum ID to get.
* @param siteId Site ID. If not defined, current site.
* @param userId User the discussions belong to. If not defined, current user in site.
* @return Promise resolved with the object to be synced.
*/
async getNewDiscussions(forumId: number, siteId?: string, userId?: number): Promise<AddonModForumOfflineDiscussion[]> {
const site = await CoreSites.getSite(siteId);
const conditions = {
forumid: forumId,
userid: userId || site.getUserId(),
};
const records = await site.getDb().getRecords<AddonModForumOfflineDiscussionDBRecord>(DISCUSSIONS_TABLE, conditions);
return this.parseRecordsOptions(records);
}
/**
* Offline version for adding a new discussion to a forum.
*
* @param forumId Forum ID.
* @param name Forum name.
* @param courseId Course ID the forum belongs to.
* @param subject New discussion's subject.
* @param message New discussion's message.
* @param options Options (subscribe, pin, ...).
* @param groupId Group this discussion belongs to.
* @param timeCreated The time the discussion was created. If not defined, current time.
* @param siteId Site ID. If not defined, current site.
* @param userId User the discussion belong to. If not defined, current user in site.
* @return Promise resolved when new discussion is successfully saved.
*/
async addNewDiscussion(
forumId: number,
name: string,
courseId: number,
subject: string,
message: string,
options?: AddonModForumDiscussionOptions,
groupId?: number,
timeCreated?: number,
siteId?: string,
userId?: number,
): Promise<void> {
const site = await CoreSites.getSite(siteId);
const data: AddonModForumOfflineDiscussionDBRecord = {
forumid: forumId,
name: name,
courseid: courseId,
subject: subject,
message: message,
options: JSON.stringify(options || {}),
groupid: groupId || AddonModForumProvider.ALL_PARTICIPANTS,
userid: userId || site.getUserId(),
timecreated: timeCreated || new Date().getTime(),
};
await site.getDb().insertRecord(DISCUSSIONS_TABLE, data);
}
/**
* Delete forum offline replies.
*
* @param postId ID of the post being replied.
* @param siteId Site ID. If not defined, current site.
* @param userId User the reply belongs to. If not defined, current user in site.
* @return Promise resolved if stored, rejected if failure.
*/
async deleteReply(postId: number, siteId?: string, userId?: number): Promise<void> {
const site = await CoreSites.getSite(siteId);
const conditions = {
postid: postId,
userid: userId || site.getUserId(),
};
await site.getDb().deleteRecords(REPLIES_TABLE, conditions);
}
/**
* Get all offline replies.
*
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with replies.
*/
async getAllReplies(siteId?: string): Promise<AddonModForumOfflineReply[]> {
const site = await CoreSites.getSite(siteId);
const records = await site.getDb().getRecords<AddonModForumOfflineReplyDBRecord>(REPLIES_TABLE);
return this.parseRecordsOptions(records);
}
/**
* Check if there is an offline reply for a forum to be synced.
*
* @param forumId ID of the forum being replied.
* @param siteId Site ID. If not defined, current site.
* @param userId User the replies belong to. If not defined, current user in site.
* @return Promise resolved with boolean: true if has offline answers, false otherwise.
*/
async hasForumReplies(forumId: number, siteId?: string, userId?: number): Promise<boolean> {
try {
const replies = await this.getForumReplies(forumId, siteId, userId);
return !!replies.length;
} catch (error) {
// No offline data found, return false.
return false;
}
}
/**
* Get the replies of a forum to be synced.
*
* @param forumId ID of the forum being replied.
* @param siteId Site ID. If not defined, current site.
* @param userId User the replies belong to. If not defined, current user in site.
* @return Promise resolved with replies.
*/
async getForumReplies(forumId: number, siteId?: string, userId?: number): Promise<AddonModForumOfflineReply[]> {
const site = await CoreSites.getSite(siteId);
const conditions = {
forumid: forumId,
userid: userId || site.getUserId(),
};
const records = await site.getDb().getRecords<AddonModForumOfflineReplyDBRecord>(REPLIES_TABLE, conditions);
return this.parseRecordsOptions(records);
}
/**
* Check if there is an offline reply to be synced.
*
* @param discussionId ID of the discussion the user is replying to.
* @param siteId Site ID. If not defined, current site.
* @param userId User the replies belong to. If not defined, current user in site.
* @return Promise resolved with boolean: true if has offline answers, false otherwise.
*/
async hasDiscussionReplies(discussionId: number, siteId?: string, userId?: number): Promise<boolean> {
try {
const replies = await this.getDiscussionReplies(discussionId, siteId, userId);
return !!replies.length;
} catch (error) {
// No offline data found, return false.
return false;
}
}
/**
* Get the replies of a discussion to be synced.
*
* @param discussionId ID of the discussion the user is replying to.
* @param siteId Site ID. If not defined, current site.
* @param userId User the replies belong to. If not defined, current user in site.
* @return Promise resolved with discussions.
*/
async getDiscussionReplies(discussionId: number, siteId?: string, userId?: number): Promise<AddonModForumOfflineReply[]> {
const site = await CoreSites.getSite(siteId);
const conditions = {
discussionid: discussionId,
userid: userId || site.getUserId(),
};
const records = await site.getDb().getRecords<AddonModForumOfflineReplyDBRecord>(REPLIES_TABLE, conditions);
return this.parseRecordsOptions(records);
}
/**
* Offline version for replying to a certain post.
*
* @param postId ID of the post being replied.
* @param discussionId ID of the discussion the user is replying to.
* @param forumId ID of the forum the user is replying to.
* @param name Forum name.
* @param courseId Course ID the forum belongs to.
* @param subject New post's subject.
* @param message New post's message.
* @param options Options (subscribe, attachments, ...).
* @param siteId Site ID. If not defined, current site.
* @param userId User the post belong to. If not defined, current user in site.
* @return Promise resolved when the post is created.
*/
async replyPost(
postId: number,
discussionId: number,
forumId: number,
name: string,
courseId: number,
subject: string,
message: string,
options?: AddonModForumReplyOptions,
siteId?: string,
userId?: number,
): Promise<void> {
const site = await CoreSites.getSite(siteId);
const data: AddonModForumOfflineReplyDBRecord = {
postid: postId,
discussionid: discussionId,
forumid: forumId,
name: name,
courseid: courseId,
subject: subject,
message: message,
options: JSON.stringify(options || {}),
userid: userId || site.getUserId(),
timecreated: new Date().getTime(),
};
await site.getDb().insertRecord(REPLIES_TABLE, data);
}
/**
* Get the path to the folder where to store files for offline attachments in a forum.
*
* @param forumId Forum ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with the path.
*/
async getForumFolder(forumId: number, siteId?: string): Promise<string> {
const site = await CoreSites.getSite(siteId);
const siteFolderPath = CoreFile.getSiteFolder(site.getId());
return CoreTextUtils.concatenatePaths(siteFolderPath, 'offlineforum/' + forumId);
}
/**
* Get the path to the folder where to store files for a new offline discussion.
*
* @param forumId Forum ID.
* @param timeCreated The time the discussion was created.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with the path.
*/
async getNewDiscussionFolder(forumId: number, timeCreated: number, siteId?: string): Promise<string> {
const folderPath = await this.getForumFolder(forumId, siteId);
return CoreTextUtils.concatenatePaths(folderPath, 'newdisc_' + timeCreated);
}
/**
* Get the path to the folder where to store files for a new offline reply.
*
* @param forumId Forum ID.
* @param postId ID of the post being replied.
* @param siteId Site ID. If not defined, current site.
* @param userId User the replies belong to. If not defined, current user in site.
* @return Promise resolved with the path.
*/
async getReplyFolder(forumId: number, postId: number, siteId?: string, userId?: number): Promise<string> {
const folderPath = await this.getForumFolder(forumId, siteId);
const site = await CoreSites.getSite(siteId);
userId = userId || site.getUserId();
return CoreTextUtils.concatenatePaths(folderPath, 'reply_' + postId + '_' + userId);
}
/**
* Parse "options" column of fetched record.
*
* @param records List of records.
* @return List of records with options parsed.
*/
protected parseRecordsOptions<
R extends { options: string },
O extends Record<string, unknown> = Record<string, unknown>
>(records: R[]): (Omit<R, 'options'> & { options: O })[] {
return records.map(record => this.parseRecordOptions(record));
}
/**
* Parse "options" column of fetched record.
*
* @param record Record.
* @return Record with options parsed.
*/
protected parseRecordOptions<
R extends { options: string },
O extends Record<string, unknown> = Record<string, unknown>
>(record: R): Omit<R, 'options'> & { options: O } {
record.options = CoreTextUtils.parseJSON(record.options);
return record as unknown as Omit<R, 'options'> & { options: O };
}
}
export const AddonModForumOffline = makeSingleton(AddonModForumOfflineProvider);
export type AddonModForumDiscussionOptions = {
attachmentsid?: number | CoreFileUploaderStoreFilesResult;
discussionsubscribe?: boolean;
discussionpinned?: boolean;
};
export type AddonModForumReplyOptions = {
private?: boolean;
attachmentsid?: number | CoreFileUploaderStoreFilesResult;
};
export type AddonModForumOfflineDiscussion = {
forumid: number;
name: string;
courseid: number;
subject: string;
message: string;
options: AddonModForumDiscussionOptions;
groupid: number;
groupname?: string;
userid: number;
timecreated: number;
};
export type AddonModForumOfflineReply = {
postid: number;
discussionid: number;
forumid: number;
name: string;
courseid: number;
subject: string;
message: string;
options: AddonModForumReplyOptions;
userid: number;
timecreated: number;
}; | the_stack |
import { autobind } from "core-decorators";
import * as _ from "lodash";
import { inject, observer } from "mobx-react";
import * as React from "react";
import * as DayPicker from "react-day-picker";
import * as ReactQuill from "react-quill/src/";
import { Quill } from "react-quill/src/";
import * as Modal from "boron/FadeModal";
import * as lamejs from "lamejs";
import * as ImageResize from "quill-image-resize-module";
import { Button, Form, Header, Icon, Input, Menu, Popup, Progress, Segment, TextArea } from "semantic-ui-react";
import { storage } from "../../../lib/constants";
import { IEpisode, IPodcast } from "../../../lib/interfaces";
import { colors, globalStyles } from "../../../lib/styles";
import { RootState } from "../../../state/RootState";
import AudioEditor from "../generic/AudioEditor";
import EpisodeImageUpload from "../generic/EpisodeImageUpload";
import AdForm from "./AdForm";
import "react-day-picker/lib/style.css";
const summaryPlaceholder =
`This is what appears on iTunes for the episode. Keep this short and interesting so that people click to listen.`;
const showNotesPlaceholder =
`Add a full description of your episode for the podcast website. Include images or videos.`
const fullContentPlaceholder =
`Add information about the episode, show notes, additional links.
This appears in the show website.`;
interface IEpisodeFormProps {
rootState: RootState;
onSubmit: (formState: IEpisodeFields) => void;
onPreview: (formState: IEpisodeFields) => void;
currentEpisode?: IEpisode;
getUploadPolicy?: (file: File) => Promise<{ uploadUrl: string, publicFileUrl: string }>;
uploadFile?: (file: File, policyUrl: string, publicFileUrl?: string) => Promise<void>;
currentPodcast?: IPodcast;
publishItemHandler: (item: IEpisode) => void;
unpublishItemHandler: (item: IEpisode) => void;
uploadProgress?: any;
error?: string;
}
export interface IEpisodeFields {
title: string;
summary: string;
fullContent: string;
audioUrl: string;
uploadUrl?: string;
audioDuration?: number;
publishedAt?: Date;
published?: boolean;
adPlacement?: object;
}
export interface IEpisodeFormState {
fields: IEpisodeFields;
uploading: boolean;
uploadProgress: number;
publicFileUrl?: string;
pickingDate?: boolean;
previewDevice: string;
local_url?: string;
local_mime?: string;
time_of_day?: string;
scheduledDate?: Date;
scheduledHours?: string;
scheduledMinutes?: string;
editingAudio: boolean;
renderedFile?: any;
isUploadingImage: boolean;
section: string;
}
@inject("rootState")
@observer
export default class EpisodeForm extends React.Component<IEpisodeFormProps, IEpisodeFormState> {
public state: IEpisodeFormState = {
uploading: false,
uploadProgress: 0,
fields: {
title: "",
summary: "",
fullContent: "",
audioUrl: "",
uploadUrl: "",
},
pickingDate: false,
previewDevice: "desktop",
time_of_day: "AM",
scheduledDate: new Date(),
scheduledHours: "00",
scheduledMinutes: "00",
editingAudio: false,
isUploadingImage: false,
section: "Episode",
};
public modules = {
toolbar: {
container: [
[{ header: [1, 2, false] }],
["bold", "italic", "underline", "strike", "blockquote"],
[{ list: "ordered" }, { list: "bullet" }, { indent: "-1" }, { indent: "+1" }],
["link", "image"],
["clean"],
],
handlers: {
image: () => {
this.setState({ isUploadingImage: true });
},
},
modules: {
ImageResize: {},
},
},
};
public adPlacement = null;
public quill = null;
public formats = [
"header",
"bold", "italic", "underline", "strike", "blockquote",
"list", "bullet", "indent",
"link", "image",
];
public fileInput: any = null;
constructor(props: IEpisodeFormProps) {
super(props);
if (props.currentEpisode) {
// tslint:disable-next-line:max-line-length
const { title, summary, fullContent, audioUrl, uploadUrl, audioDuration, publishedAt, published } = props.currentEpisode;
this.state = {
uploading: false,
uploadProgress: 0,
fields: {
title, summary, fullContent, audioUrl, uploadUrl, audioDuration, publishedAt, published,
},
previewDevice: "desktop",
time_of_day: "AM",
scheduledDate: new Date(),
scheduledHours: "00",
scheduledMinutes: "00",
editingAudio: false,
isUploadingImage: false,
section: "Episode",
};
}
}
public componentDidMount() {
if (!this.props.currentEpisode) {
return;
}
const { title, summary, fullContent, audioUrl, uploadUrl, audioDuration, publishedAt, published } = this.props.currentEpisode;
this.setState({
uploading: false,
uploadProgress: 0,
fields: {
title, summary, fullContent, audioUrl, uploadUrl, audioDuration, publishedAt, published,
},
previewDevice: "desktop",
time_of_day: "AM",
scheduledDate: new Date(),
scheduledHours: "00",
scheduledMinutes: "00",
editingAudio: false,
isUploadingImage: false,
section: "Episode",
});
}
public render() {
const storageLimit = _.get(this.props, "currentPodcast.subscription.storageLimit", storage.free);
const usedStorage = _.get(this.props, "currentPodcast.usedStorage", 0).toFixed(2);
const uploadDisabled = Number(usedStorage) >= storageLimit;
const uploadError = this.uploadError();
const audioUrl = this.state.fields.audioUrl || "";
const uploadUrl = this.state.fields.uploadUrl || "";
const splitAudioUrl = audioUrl.split("/");
const splitUploadUrl = uploadUrl.split("/");
const { title, summary, fullContent} = this.state.fields;
const shouldDisablePublish = false; // !(title && summary && (audioUrl || uploadUrl));
let fileName = "";
if (audioUrl || uploadUrl) {
fileName = splitAudioUrl[splitAudioUrl.length - 1] || splitUploadUrl[splitUploadUrl.length - 1];
}
return (
<Segment style={{ paddingBottom: 25 }} basic>
<Form onSubmit={this.onSubmit} enctype="multipart/form-data">
{this.props.rootState.env.AUDIO_EDITOR === "true" ?
<Menu style={{ width: "75%" }} tabular>
<Menu.Item
name="Episode"
active={!this.state.editingAudio}
onClick={(e, { name }) => this.handleItemClick(e, name)} />
<Menu.Item
name="Audio Editor"
active={this.state.editingAudio}
onClick={(e, { name }) => this.handleItemClick(e, name)} />
</Menu>
:
null
}
{this.props.rootState.podcast.advertisingEnabled ?
<Menu style={{ width: "75%" }} tabular>
<Menu.Item
name="Episode"
active={this.state.section === "Episode"}
onClick={(e, { section }) => this.setState({ section: "Episode" })} />
<Menu.Item
name="Ad Placements"
active={this.state.section === "Ad Placements"}
onClick={(e, { section }) => this.setState({ section: "Ad Placements" })} />
</Menu>
:
null
}
<div style={{
width: "100%",
display: !this.state.editingAudio ? "none" : "flex",
flex: 1,
justifyContent: "flex-start",
}}>
{/*<AudioEditor
onAudio={(file) => this.setState({ renderedFile: file })} />*/}
</div>
<div style={{
width: "100%",
display: this.state.section === "Ad Placements" ? "flex" : "none",
flex: 1,
justifyContent: "flex-start",
}}>
{/*<AdForm
adPlacement={this.props.currentEpisode.adPlacement} onChange={(adPlacement) => {
const fields = this.state.fields;
this.adPlacement = adPlacement;
}} episodeState={this.state} />*/}
</div>
<div style={{
display: this.state.section === "Episode" ? "block" : "none",
}}>
<div style={style.formLabel}>Title</div>
<Form.Group>
<Form.Input
placeholder="New Episode Title"
width="12"
name="title"
style={style.titleInput}
value={this.state.fields.title}
onChange={this.onChangeInputField}
required />
</Form.Group>
{!!uploadError ?
<div style={{ color: "tomato" }}>
{uploadError}
</div>
:
null
}
<div style={{ marginTop: 50 }}>
<div style={style.formLabel}>Audio File</div>
<Segment style={style.uploadSegment} disabled={this.state.uploading} basic>
<div style={{
display: "flex",
flex: 1,
flexDirection: "row",
alignItems: "center",
marginBottom: 15,
}}>
<Form.Field style={{
display: "flex",
flexDirection: "row",
width: "75%",
alignItems: "center",
}} inline>
<input disabled={uploadDisabled} id={"episodeFormFileInput"} onChange={this.onFileInput} type="file" />
</Form.Field>
{this.state.renderedFile ?
<Button
onClick={(e) => this.onUploadFromEditor(e)}
style={{
marginLeft: -165,
backgroundColor: colors.mainDark,
color: "white",
}}>Upload From Editor</Button>
:
null}
</div>
{this.renderUploadProgressBar()}
{this.state.fields.audioUrl || uploadUrl ?
<div>
<Icon name="attach" size="big" />
<strong>{fileName}</strong>
</div>
:
null
}
<Form.Input
style={{ display: "none" }}
width="12"
name="audioUrl"
placeholder="Audio URL Generated from Google Cloud Storage"
value={this.state.fields.audioUrl}
readOnly
disabled={this.state.uploading} />
</Segment>
</div>
<div style={{ marginTop: 50 }} className="formBoxInput">
<div style={style.formLabel}>Description</div>
<Form.Field
style={{ height: 120 }}
control={TextArea}
width="12"
name="summary"
placeholder={summaryPlaceholder}
value={this.state.fields.summary}
onChange={this.onChangeInputField} />
<div style={{ width: "75%", marginTop: 50 }}>
<div style={style.formLabel}>Show Notes</div>
<div style={{ height: 320 }}>
<ReactQuill
ref={(component) => {
if (component) {
this.quill = component.getEditor();
}
}}
style={{ height: 250 }}
theme="snow"
modules={this.modules}
placeholder={showNotesPlaceholder}
formats={this.formats}
value={this.state.fields.fullContent}
onChange={this.onChangeContentField} />
</div>
</div>
</div>
</div>
<Form.Group style={{ width: "75%" }}>
<div style={{
display: "flex",
flex: 1,
justifyContent: "flex-start" as "flex-start",
}}>
<Popup
trigger={
<Button
style={{ marginTop: "1em", fontWeight: 550, fontSize: "120%", color: "#787878", backgroundColor: "white", border: "solid 0.1em #E6E6E6"}}>
Save
</Button>}
style={style.tooltip}
basic
size="tiny"
content="Save changes to your podcast episode" />
{this.renderPublishButton()}
{!(this.props.currentEpisode && this.props.currentEpisode.published) && <Popup
trigger={
<span>
<Button
onClick={(e) => {
e.preventDefault();
this.setState({ pickingDate: true });
}}
style={{ marginTop: "1em", fontWeight: 550, fontSize: "120%", color: "#5FC67A", backgroundColor: "white", border: "solid 0.1em #5FC67A"}}>
Schedule
</Button>
</span>}
style={style.calendarTooltip}
on="click"
position="bottom center"
size="tiny"
open={this.state.pickingDate}
onClose={() => this.setState({ pickingDate: false })}
onOpen={() => this.setState({ pickingDate: true })}
content={
<div>
<Header textAlign="center" as="h3">
Schedule Publish
</Header>
<DayPicker
initialMonth={this.state.scheduledDate}
selectedDays={this.state.scheduledDate}
onDayClick={(e: Date) => {
this.setState({ scheduledDate: e });
}} />
<Segment style={{
paddingBottom: 0,
paddingTop: 0,
}} basic>
<Input
value={this.state.scheduledHours}
onChange={(e, input) => {
let val = input.value;
if (Number(val) > 12) {
val = "12";
}
if (Number(val) < 0) {
val = "00";
}
this.setState({ scheduledHours: val });
}}
style={{ width: 47, padding: 0 }}
type={"number"}
placeholder="00" />
<span style={{ marginLeft: 5, marginRight: 5 }}>:</span>
<Input
value={this.state.scheduledMinutes}
// tslint:disable-next-line:max-line-length
onChange={(e, input) => {
let val = input.value;
if (Number(val) > 60) {
val = "60";
}
if (Number(val) < 0) {
val = "00";
}
this.setState({ scheduledMinutes: val });
}}
type={"number"}
style={{ width: 47, padding: 0 }} placeholder="00" />
<Button.Group floated="right" style={{ marginLeft: 5 }}>
<Button style={{
padding: 10.5,
paddingLeft: 10,
paddingRight: 10,
// tslint:disable-next-line:max-line-length
backgroundColor: this.state.time_of_day === "AM" ? "lightgray" : "#EEE",
}}
onClick={() => this.switchTimeOfDay("AM")}>AM</Button>
<Button style={{
padding: 10.5,
paddingLeft: 10,
paddingRight: 10,
// tslint:disable-next-line:max-line-length
backgroundColor: this.state.time_of_day === "PM" ? "lightgray" : "#EEE",
}}
onClick={() => this.switchTimeOfDay("PM")}>PM</Button>
</Button.Group>
</Segment>
<Segment basic>
<Button
onClick={() => this.setState({ pickingDate: false })}
basic
size="small"
floated="left"
negative>Cancel</Button>
<Button
onClick={(e) => {
const schedule = this.state.scheduledDate;
let hours = this.state.scheduledHours;
const minutes = this.state.scheduledMinutes;
if (this.state.time_of_day === "PM") {
hours = String(Number(hours) + 12);
}
schedule.setHours(Number(hours));
schedule.setMinutes(Number(minutes));
schedule.setSeconds(0);
schedule.setMilliseconds(0);
const item = {
...this.state.fields,
publishedAt: schedule,
};
this.setState({ fields: item });
if (this.state.uploading && item.audioUrl) {
const url = item.audioUrl;
item.audioUrl = "";
item.uploadUrl = url;
}
this.props.publishItemHandler(item);
}}
size="small"
floated="right"
positive>Schedule</Button>
</Segment>
</div>
} />}
<Popup
trigger={
<Button
onClick={this.onPreview(this.state.fields)}
style={{ marginTop: "1em", fontWeight: 550, fontSize: "120%", color: "#6B7BE1", backgroundColor: "white", border: "solid 0.1em #6B7BE1"}}>
Preview
</Button>}
style={style.tooltip}
basic
size="tiny"
content="Preview the episode on your website" />
</div>
</Form.Group>
</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}/preview/`}>
</iframe>
</div>
</Modal>
<EpisodeImageUpload
onImage={(url) => this.onImagePick(url)}
onClose={() => this.setState({ isUploadingImage: !this.state.isUploadingImage })}
episode={this.props.currentEpisode}
podcast={this.props.currentPodcast}
isOpen={this.state.isUploadingImage} />
</Segment>
);
}
protected onImagePick(url: string) {
const range = this.quill.getSelection() || { index: 0 };
const value = url;
if (value) {
this.quill.insertEmbed(range.index, "image", value, ReactQuill.Quill.sources.USER);
this.setState({ isUploadingImage: false });
}
}
protected onUploadFromEditor(e) {
e.preventDefault();
const ev = e;
const file = this.state.renderedFile;
file.filename = file.name;
ev.target.files = [file];
this.onFileInput(ev);
}
protected handleItemClick(e, name) {
this.setState({ editingAudio: name !== "Episode" });
}
protected switchTimeOfDay(new_time) {
this.setState({
time_of_day: new_time,
});
}
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 onAdvancedEditor(e) {
e.preventDefault();
}
@autobind
protected uploadProgress() {
const publicFileUrl = this.state.publicFileUrl ?
this.state.publicFileUrl
:
_.get(this.props, "currentEpisode.uploadUrl", "");
const currentProgress = _.find(this.props.uploadProgress, { publicFileUrl });
const progressEvent = _.get(currentProgress, "progress", {
loaded: false,
total: 0,
});
if (publicFileUrl && progressEvent && progressEvent.loaded && progressEvent.total) {
const uploadProgress = Math.ceil((+progressEvent.loaded / progressEvent.total) * 100);
if (this.state.uploading && (uploadProgress === 0 || uploadProgress === 100)) {
this.setState({ uploading: false });
} else if (!this.state.uploading && (uploadProgress > 0 && uploadProgress < 100)) {
this.setState({ uploading: true });
}
return uploadProgress;
} else {
if (this.state.uploading) {
this.setState({ uploading: false });
}
return 0;
}
}
@autobind
protected uploadError() {
const publicFileUrl = this.state.publicFileUrl ?
this.state.publicFileUrl
:
_.get(this.props, "currentEpisode.uploadUrl", "");
const currentProgress = _.find(this.props.uploadProgress, { publicFileUrl });
const uploadError = _.get(currentProgress, "error", "");
const fileInput = document.getElementById("episodeFormFileInput");
if (!!uploadError && this.fileInput && this.fileInput.value) {
this.fileInput.value = "";
}
if (!!uploadError && this.state.uploading) {
this.setState({ uploading: false });
}
return uploadError;
}
@autobind
protected renderUploadProgressBar() {
const uploadProgress = this.uploadProgress();
if (uploadProgress === 0 || uploadProgress === 100) { return null; }
return (
<Form.Field width="12">
<Progress percent={uploadProgress} style={style.uploadProgress} size="tiny">
{uploadProgress}%
</Progress>
</Form.Field>
);
}
@autobind
protected renderPublishButton() {
const episode = this.props.currentEpisode;
if (episode && episode.published) {
return (
<Button
onClick={this.onUnpublishItem(this.state.fields)}
style={{ marginTop: "1em", fontWeight: 550, fontSize: "120%", color: "#C95959", backgroundColor: "white", border: "solid 0.1em #C95959"}}>
Unpublish
</Button>
);
}
const { title, summary, fullContent, audioUrl, uploadUrl } = this.state.fields;
const shouldDisablePublish = false; // !(title && summary && (audioUrl || uploadUrl));
return (
<Button
style={{ marginTop: "1em", fontWeight: 550, fontSize: "120%", color: "white", backgroundColor: "#6B7BE1"}}
onClick={this.onPublishItem(this.state.fields)}
disabled={shouldDisablePublish}>
Publish
</Button>
);
}
@autobind
protected onPublishItem(item: IEpisode) {
return (e: React.MouseEvent<HTMLButtonElement>) => {
if (this.state.uploading && item.audioUrl) {
const uploadUrl = item.audioUrl;
item.audioUrl = "";
item.uploadUrl = uploadUrl;
}
item.publishedAt = new Date();
this.props.publishItemHandler(item);
e.preventDefault();
};
}
@autobind
protected onPreview(item: IEpisodeFields) {
return (e: React.MouseEvent<HTMLButtonElement>) => {
this.props.onPreview(item);
this.showPreview();
e.preventDefault();
};
}
@autobind
protected onUnpublishItem(item: IEpisode) {
return (e: React.MouseEvent<HTMLButtonElement>) => {
if (this.state.fields.published) {
this.setState({
fields: {
...this.state.fields,
published: false,
},
});
}
this.props.unpublishItemHandler(item);
e.preventDefault();
};
}
@autobind
protected async onFileInput(e: React.ChangeEvent<HTMLInputElement>) {
e.preventDefault();
this.fileInput = e.target;
if (e.target && e.target.files && e.target.files.length) {
const file = e.target.files[0];
const duration = await this.getFileDuration(e);
this.props.getUploadPolicy(file).then(async (policyData) => {
const { uploadUrl, publicFileUrl } = policyData;
this.setState({ publicFileUrl });
this.props.uploadFile(file, uploadUrl, publicFileUrl);
// tslint:disable-next-line:max-line-length
// tslint:disable-next-line:prefer-object-spread
const fields = Object.assign({}, this.state.fields, { audioUrl: publicFileUrl, audioDuration: duration });
this.setState({ fields });
}).catch((err: Error) => {
alert(err.message);
});
}
}
protected getFileDuration(e: React.ChangeEvent<HTMLInputElement>) {
const file = e.target.files[0];
const mime = file.type;
const rd = new FileReader();
const fileEl = document.querySelector("input");
return new Promise((resolve, reject) => {
try {
// tslint:disable-next-line:no-shadowed-variable
rd.onload = function (e) {
const blob = new Blob([(e.target as any).result], { type: mime });
const url = (URL).createObjectURL(blob);
const video = document.createElement("video");
video.preload = "metadata";
video.addEventListener("loadedmetadata", function () {
resolve(video.duration);
});
video.src = url;
};
rd.readAsArrayBuffer(file);
} catch (err) {
reject(1);
}
});
}
@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 onChangeContentField(content: any) {
if (content) {
const fields = { ...this.state.fields, fullContent: content };
this.setState({ fields });
}
}
@autobind
protected onSubmit(e: React.FormEvent<Event>) {
e.preventDefault();
if (!Boolean(this.state.fields.audioUrl)) {
alert("Could not save episode. Please upload an audio file.");
return;
}
const fields = this.state.fields;
fields.adPlacement = this.adPlacement;
if (this.state.uploading && fields.audioUrl) {
const uploadUrl = fields.audioUrl;
fields.audioUrl = "";
fields.uploadUrl = uploadUrl;
}
this.props.onSubmit(fields);
}
}
const style = {
uploadSegment: {
padding: 0,
},
uploadProgress: {
marginBottom: 35,
},
actionIcon: {
fontSize: "160%",
backgroundColor: "transparent",
paddingLeft: 0,
paddingRight: 0,
alignSelf: "flex-end",
},
calendarIcon: {
fontSize: "155%",
backgroundColor: "transparent",
paddingLeft: 0,
paddingRight: 0,
paddingBottom: 15,
marginRight: 0,
alignSelf: "flex-end" as "flex-end",
},
publishIcon: {
marginTop: 2,
fontSize: "160%",
backgroundColor: "transparent",
paddingLeft: 0,
paddingRight: 0,
marginRight: 20,
alignSelf: "flex-end",
},
unpublishIcon: {
marginTop: -3,
fontSize: "155%",
marginBottom: 3,
backgroundColor: "transparent",
paddingLeft: 0,
paddingRight: 0,
marginRight: 20,
alignSelf: "flex-end",
},
previewIcon: {
fontSize: "160%",
backgroundColor: "transparent",
paddingLeft: 0,
paddingRight: 0,
alignSelf: "flex-end",
marginRight: 30,
},
tooltip: {
...globalStyles.tooltip,
margin: 0,
marginBottom: -10,
marginLeft: 15,
},
formLabel: {
display: "flex",
minWidth: 80,
textAlign: "left",
fontSize: "120%" as "120%",
color: colors.mainDark,
fontWeight: 600,
marginBottom: 15,
marginTop: 40,
} as React.CSSProperties,
calendarTooltip: {
},
titleInput: {
color: colors.mainDark,
borderStyle: "none",
height: 40,
},
fullContentLabel: {
fontSize: "120%",
fontWeight: 100 as 100,
color: colors.mainLight,
paddingBottom: 15,
},
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",
},
}; | the_stack |
import { Components, registerComponent, } from '../../lib/vulcan-lib';
import React, { useState, useEffect, useRef } from 'react';
import { createStyles } from '@material-ui/core/styles';
import Geosuggest from 'react-geosuggest';
import { useUserLocation } from '../../lib/collections/users/helpers';
import { useCurrentUser } from '../common/withUser';
import { useUpdate } from '../../lib/crud/withUpdate';
import { useLocation, useNavigation } from '../../lib/routeUtil';
import { useDialog } from '../common/withDialog'
import { AnalyticsContext, useTracking } from "../../lib/analyticsEvents";
import { useGoogleMaps, geoSuggestStyles } from '../form-components/LocationFormComponent';
import { pickBestReverseGeocodingResult } from '../../server/mapsUtils';
import { getBrowserLocalStorage } from '../async/localStorageHandlers';
import { userIsAdmin } from '../../lib/vulcan-users';
import { Link } from '../../lib/reactRouterWrapper';
import Button from '@material-ui/core/Button';
import NotificationsIcon from '@material-ui/icons/Notifications';
import NotificationsNoneIcon from '@material-ui/icons/NotificationsNone';
import OpenInNewIcon from '@material-ui/icons/OpenInNew';
import OutlinedInput from '@material-ui/core/OutlinedInput';
import Search from '@material-ui/icons/Search';
import Tab from '@material-ui/core/Tab';
import Tabs from '@material-ui/core/Tabs';
import Chip from '@material-ui/core/Chip';
const styles = createStyles((theme: ThemeType): JssStyles => ({
section: {
maxWidth: 1200,
margin: 'auto',
},
sectionHeadingRow: {
display: 'flex',
justifyContent: 'space-between',
maxWidth: 800,
padding: '0 20px',
margin: '0 auto 40px',
[theme.breakpoints.down('sm')]: {
flexDirection: 'column',
marginTop: 30,
},
},
sectionHeading: {
...theme.typography.headline,
fontSize: 34,
margin: 0
},
sectionDescription: {
...theme.typography.commentStyle,
textAlign: 'left',
fontSize: 15,
lineHeight: '1.8em',
marginLeft: 60,
[theme.breakpoints.down('sm')]: {
marginTop: 20,
marginLeft: 0
},
},
filtersRow: {
display: 'flex',
flexWrap: 'wrap',
alignItems: 'baseline',
columnGap: 10,
rowGap: '15px',
minHeight: 47,
marginTop: 15,
'@media (max-width: 1200px)': {
padding: '0 20px',
},
[theme.breakpoints.down('sm')]: {
padding: '0 6px',
},
},
activeFilterChip: {
marginTop: 5
},
keywordSearch: {
maxWidth: '100%',
},
keywordSearchInput: {
width: 350,
maxWidth: '100%',
verticalAlign: 'sub',
paddingLeft: 10,
'& input': {
padding: '15px 14px 15px 0'
}
},
searchIcon: {
color: theme.palette.primary.main,
marginRight: 6
},
where: {
display: 'inline-block',
...theme.typography.commentStyle,
fontSize: 13,
color: theme.palette.grey[700],
paddingLeft: 3
},
whereTextDesktop: {
[theme.breakpoints.down('xs')]: {
display: 'none'
}
},
whereTextMobile: {
display: 'none',
[theme.breakpoints.down('xs')]: {
display: 'inline'
}
},
geoSuggest: {
...geoSuggestStyles(theme),
display: 'inline-block',
marginLeft: 6
},
notifications: {
flex: '1 0 0',
textAlign: 'right',
[theme.breakpoints.down('md')]: {
display: 'none'
}
},
notificationsBtn: {
textTransform: 'none',
fontSize: 14,
},
notificationsIcon: {
fontSize: 18,
marginRight: 6
},
tabs: {
maxWidth: 634,
margin: '0 auto 40px',
'& .MuiTab-labelContainer': {
fontSize: '1rem'
}
},
localGroupsBtns: {
display: 'flex',
justifyContent: 'space-between',
marginTop: 20,
'@media (max-width: 1200px)': {
padding: '0 20px',
},
[theme.breakpoints.down('sm')]: {
display: 'none'
},
},
localGroupsBtn: {
textTransform: 'none',
fontSize: 12
},
localGroupsBtnIcon: {
fontSize: 15,
marginLeft: 8
},
localGroupsBtnEmailIcon: {
fontSize: 20,
marginLeft: 10,
marginRight: 5
},
eventsPageLinkRow: {
display: 'flex',
flexWrap: 'wrap',
alignItems: 'baseline',
...theme.typography.commentStyle,
marginTop: 40,
'@media (max-width: 1200px)': {
padding: '0 20px',
},
[theme.breakpoints.down('sm')]: {
display: 'none'
}
},
eventsPagePrompt: {
color: theme.palette.grey[600],
fontSize: 14,
marginRight: 16
},
eventsPageLink: {
backgroundColor: theme.palette.primary.main,
color: theme.palette.text.invertedBackgroundText,
fontSize: 13,
padding: '8px 16px',
borderRadius: 4,
marginTop: 10
},
addGroup: {
marginTop: 40
},
}))
const Community = ({classes}: {
classes: ClassesType,
}) => {
const currentUser = useCurrentUser();
const { openDialog } = useDialog();
const { history } = useNavigation();
const { location, query } = useLocation();
const { captureEvent } = useTracking();
// local, online, or individuals
const [tab, setTab] = useState('local')
const [distanceUnit, setDistanceUnit] = useState<"km"|"mi">('km')
const [keywordSearch, setKeywordSearch] = useState('')
const [includeInactive, setIncludeInactive] = useState(query?.includeInactive === 'true')
useEffect(() => {
// unfortunately the hash is unavailable on the server, so we check it here instead
if (location.hash === '#online') {
setTab('online')
} else if (location.hash === '#individuals') {
setTab('individuals')
}
// only US and UK default to miles - everyone else defaults to km
// (this is checked here to allow SSR to work properly)
if (['en-US', 'en-GB'].some(lang => lang === window?.navigator?.language)) {
setDistanceUnit('mi')
}
//No exhaustive deps because this is supposed to run only on mount
//eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
// used to set the user's location if they did not already have one
const { mutate: updateUser } = useUpdate({
collectionName: "Users",
fragmentName: 'UsersProfile',
});
/**
* Given a location, update the page query to use that location,
* then save it to the user's settings (if they are logged in)
* or to the browser's local storage (if they are logged out).
*
* @param {Object} location - The location to save for the user.
* @param {number} location.lat - The location's latitude.
* @param {number} location.lng - The location's longitude.
* @param {Object} location.gmaps - The Google Maps location data.
* @param {string} location.gmaps.formatted_address - The user-facing address (ex: Cambridge, MA, USA).
*/
const saveUserLocation = ({lat, lng, gmaps}) => {
// save it in the page state
userLocation.setLocationData({lat, lng, loading: false, known: true, label: gmaps.formatted_address})
if (currentUser) {
// save it on the user document
void updateUser({
selector: {_id: currentUser._id},
data: {
location: gmaps.formatted_address,
googleLocation: gmaps
}
})
} else {
// save it in local storage
const ls = getBrowserLocalStorage()
try {
ls?.setItem('userlocation', JSON.stringify({lat, lng, known: true, label: gmaps.formatted_address}))
} catch(e) {
// eslint-disable-next-line no-console
console.error(e);
}
}
}
// if the current user provides their browser location and we don't have a location saved for them,
// save it accordingly
const [mapsLoaded, googleMaps] = useGoogleMaps()
const [geocodeError, setGeocodeError] = useState(false)
const saveReverseGeocodedLocation = async ({lat, lng, known}) => {
if (
mapsLoaded && // we need Google Maps to be loaded before we can call the Geocoder
!geocodeError && // if we've ever gotten a geocoding error, don't try again
known // skip if we've received the default location
) {
try {
// get a list of matching Google locations for the current lat/lng (reverse geocoding)
const geocoder = new googleMaps.Geocoder();
const geocodingResponse = await geocoder.geocode({
location: {lat, lng}
});
const results = geocodingResponse?.results;
if (results?.length) {
const location = pickBestReverseGeocodingResult(results)
saveUserLocation({lat, lng, gmaps: location})
} else {
// update the page state to indicate that we're not waiting on a location name
userLocation.setLocationData({...userLocation, label: null})
}
} catch (e) {
setGeocodeError(true)
// eslint-disable-next-line no-console
console.error(e?.message)
// update the page state to indicate that we're not waiting on a location name
userLocation.setLocationData({...userLocation, label: null})
}
}
}
// on page load, try to get the user's location from:
// 1. (logged in user) user settings
// 2. (logged out user) browser's local storage
// 3. failing those, browser's geolocation API (which we then try to save in #1 or #2)
const userLocation = useUserLocation(currentUser)
useEffect(() => {
// if we've gotten a location from the browser's geolocation API, save it
if (!userLocation.loading && userLocation.known && userLocation.label === '') {
void saveReverseGeocodedLocation(userLocation)
}
//eslint-disable-next-line react-hooks/exhaustive-deps
}, [userLocation])
const keywordSearchTimer = useRef<any>(null)
const openEventNotificationsForm = () => {
openDialog({
componentName: currentUser ? "EventNotificationsDialog" : "LoginPopup",
});
}
const openSetPersonalLocationForm = () => {
openDialog({
componentName: currentUser ? "SetPersonalMapLocationDialog" : "LoginPopup",
});
}
const { CommunityBanner, LocalGroups, OnlineGroups, CommunityMembers, GroupFormLink, DistanceUnitToggle } = Components
const handleChangeTab = (e, value) => {
setTab(value)
setKeywordSearch('')
history.replace({...location, hash: `#${value}`})
}
const handleKeywordSearch = (e) => {
const newKeyword = e.target.value
setKeywordSearch(newKeyword)
// log the event after typing has stopped for 1 second
clearTimeout(keywordSearchTimer.current)
keywordSearchTimer.current = setTimeout(
() => captureEvent(`keywordSearchGroups`, {tab, keyword: newKeyword}),
1000
)
}
const handleToggleIncludeInactive = () => {
setIncludeInactive(!includeInactive)
history.replace({...location, search: `?includeInactive=${!includeInactive}`})
}
const canCreateGroups = currentUser && userIsAdmin(currentUser)
return (
<AnalyticsContext pageContext="Community">
<div className={classes.section}>
<div className={classes.sectionHeadingRow}>
<h1 className={classes.sectionHeading}>
Community
</h1>
<div className={classes.sectionDescription}>
Effective altruism is a global community with thousands of members. Reach out to learn how you can have the most impact.
</div>
</div>
</div>
<CommunityBanner />
<div className={classes.section}>
<Tabs value={tab} onChange={handleChangeTab} className={classes.tabs} scrollable aria-label='view local or online groups, or individual community members'>
<Tab label="Local Groups" value="local" />
<Tab label="Online Groups" value="online" />
<Tab label="Community Members" value="individuals" />
</Tabs>
{tab === 'local' && <div key="local">
<div className={classes.filtersRow}>
<div className={classes.keywordSearch}>
<OutlinedInput
labelWidth={0}
startAdornment={<Search className={classes.searchIcon}/>}
placeholder="Search groups"
onChange={handleKeywordSearch}
className={classes.keywordSearchInput}
/>
</div>
<div>
<div className={classes.where}>
<span className={classes.whereTextDesktop}>Groups near</span>
<span className={classes.whereTextMobile}>Near</span>
{mapsLoaded
&& <div className={classes.geoSuggest}>
<Geosuggest
placeholder="search for a location"
onSuggestSelect={(suggestion) => {
if (suggestion?.location) {
saveUserLocation({
...suggestion.location,
gmaps: suggestion.gmaps
})
}
}}
initialValue={userLocation?.label}
/>
</div>
}
</div>
{userLocation.known && <DistanceUnitToggle distanceUnit={distanceUnit} onChange={setDistanceUnit} skipDefaultEffect />}
</div>
<div className={classes.notifications}>
<Button variant="text" color="primary" onClick={openEventNotificationsForm} className={classes.notificationsBtn}>
{currentUser?.nearbyEventsNotifications ?
<NotificationsIcon className={classes.notificationsIcon} /> :
<NotificationsNoneIcon className={classes.notificationsIcon} />
} Notify me
</Button>
</div>
</div>
{includeInactive && <div className={classes.filtersRow}>
<Chip variant="outlined" color="primary" label="Include inactive groups" onDelete={handleToggleIncludeInactive} className={classes.activeFilterChip} />
</div>}
<LocalGroups
keywordSearch={keywordSearch}
userLocation={userLocation}
distanceUnit={distanceUnit}
includeInactive={includeInactive}
toggleIncludeInactive={handleToggleIncludeInactive}
/>
<div className={classes.localGroupsBtns}>
<Button href="https://resources.eagroups.org/start-a-group"
variant="outlined" color="primary" target="_blank" rel="noopener noreferrer" className={classes.localGroupsBtn}
>
Start your own group
<OpenInNewIcon className={classes.localGroupsBtnIcon} />
</Button>
<Button href="https://docs.google.com/forms/d/e/1FAIpQLScMolewy1P1z9XNyFIN1mQFZQ1LE64QXJrIaX6enrfItWR9LQ/viewform"
color="primary" target="_blank" rel="noopener noreferrer" className={classes.localGroupsBtn}
>
Claim your group, or add a missing group
<OpenInNewIcon className={classes.localGroupsBtnIcon} />
</Button>
</div>
<div className={classes.eventsPageLinkRow}>
<div className={classes.eventsPagePrompt}>Want to see what's happening now?</div>
<Link to="/events" className={classes.eventsPageLink}>Explore all upcoming events</Link>
</div>
</div>}
{tab === 'online' && <div key="online">
<div className={classes.filtersRow}>
<div className={classes.keywordSearch}>
<OutlinedInput
labelWidth={0}
startAdornment={<Search className={classes.searchIcon}/>}
placeholder="Search groups"
onChange={handleKeywordSearch}
className={classes.keywordSearchInput}
/>
</div>
</div>
{includeInactive && <div className={classes.filtersRow}>
<Chip variant="outlined" color="primary" label="Include inactive groups" onDelete={handleToggleIncludeInactive} className={classes.activeFilterChip} />
</div>}
<OnlineGroups keywordSearch={keywordSearch} includeInactive={includeInactive} toggleIncludeInactive={handleToggleIncludeInactive} />
</div>}
{tab === 'individuals' && <div key="individuals">
<CommunityMembers
currentUser={currentUser}
userLocation={userLocation}
distanceUnit={distanceUnit}
locationFilterNode={(
<div>
<div className={classes.where}>
<span className={classes.whereTextDesktop}>People near</span>
<span className={classes.whereTextMobile}>Near</span>
{mapsLoaded
&& <div className={classes.geoSuggest}>
<Geosuggest
placeholder="search for a location"
onSuggestSelect={(suggestion) => {
if (suggestion?.location) {
saveUserLocation({
...suggestion.location,
gmaps: suggestion.gmaps
})
}
}}
initialValue={userLocation?.label}
/>
</div>
}
</div>
{userLocation.known && <DistanceUnitToggle distanceUnit={distanceUnit} onChange={setDistanceUnit} skipDefaultEffect />}
</div>
)}
/>
<div className={classes.localGroupsBtns}>
<Button variant="outlined" color="primary" className={classes.localGroupsBtn} onClick={openSetPersonalLocationForm}>
{currentUser?.mapLocation ? "Edit my location on the map" : "Add me to the map"}
</Button>
</div>
</div>}
{tab !== 'individuals' && <>
{canCreateGroups && <div className={classes.addGroup} title="Currently only visible to admins">
<GroupFormLink isOnline={tab === 'online'} />
</div>}
</>}
</div>
</AnalyticsContext>
)
}
const CommunityComponent = registerComponent('Community', Community, {styles});
declare global {
interface ComponentTypes {
Community: typeof CommunityComponent
}
} | the_stack |
"use strict";
import loadSender from "../lib/loadSender";
import logger from "../lib/logger";
import options from "../lib/options";
import { stringify } from "../lib/utils";
import {
ReceiverSelectionActionType,
ReceiverSelectorMediaType
} from "./receiverSelector";
import ReceiverSelectorManager from "./receiverSelector/ReceiverSelectorManager";
const _ = browser.i18n.getMessage;
const URL_PATTERN_HTTP = "http://*/*";
const URL_PATTERN_HTTPS = "https://*/*";
const URL_PATTERN_FILE = "file://*/*";
const URL_PATTERNS_REMOTE = [URL_PATTERN_HTTP, URL_PATTERN_HTTPS];
const URL_PATTERNS_ALL = [...URL_PATTERNS_REMOTE, URL_PATTERN_FILE];
type MenuId = string | number;
let menuIdCast: MenuId;
let menuIdMediaCast: MenuId;
let menuIdWhitelist: MenuId;
let menuIdWhitelistRecommended: MenuId;
const whitelistChildMenuPatterns = new Map<MenuId, string>();
export async function initMenus() {
logger.info("init (menus)");
const opts = await options.getAll();
// Global "Cast..." menu item
menuIdCast = browser.menus.create({
contexts: ["browser_action", "page", "tools_menu"],
title: _("contextCast")
});
// <video>/<audio> "Cast..." context menu item
menuIdMediaCast = browser.menus.create({
contexts: ["audio", "video", "image"],
title: _("contextCast"),
visible: opts.mediaEnabled,
targetUrlPatterns: opts.localMediaEnabled
? URL_PATTERNS_ALL
: URL_PATTERNS_REMOTE
});
menuIdWhitelist = browser.menus.create({
contexts: ["browser_action"],
title: _("contextAddToWhitelist"),
enabled: false
});
menuIdWhitelistRecommended = browser.menus.create({
title: _("contextAddToWhitelistRecommended"),
parentId: menuIdWhitelist
});
browser.menus.create({
type: "separator",
parentId: menuIdWhitelist
});
}
browser.menus.onClicked.addListener(async (info, tab) => {
if (info.parentMenuItemId === menuIdWhitelist) {
const pattern = whitelistChildMenuPatterns.get(info.menuItemId);
if (!pattern) {
throw logger.error(
`Whitelist pattern not found for menu item ID ${info.menuItemId}.`
);
}
const whitelist = await options.get("userAgentWhitelist");
if (!whitelist.includes(pattern)) {
// Add to whitelist and update options
whitelist.push(pattern);
await options.set("userAgentWhitelist", whitelist);
}
return;
}
if (tab?.id === undefined) {
throw logger.error("Menu handler tab ID not found.");
}
if (!info.pageUrl) {
throw logger.error("Menu handler page URL not found.");
}
switch (info.menuItemId) {
case menuIdCast: {
const selection = await ReceiverSelectorManager.getSelection(
tab.id,
info.frameId
);
// Selection cancelled
if (!selection) {
break;
}
loadSender({
tabId: tab.id,
frameId: info.frameId,
selection
});
break;
}
case menuIdMediaCast: {
const selection = await ReceiverSelectorManager.getSelection(
tab.id,
info.frameId,
true
);
// Selection cancelled
if (!selection) {
break;
}
switch (selection.actionType) {
case ReceiverSelectionActionType.Cast: {
/**
* If the selected media type is App, that refers to the
* media sender in this context, so load media sender.
*/
if (selection.mediaType === ReceiverSelectorMediaType.App) {
await browser.tabs.executeScript(tab.id, {
code: stringify`
window.receiver = ${selection.receiver};
window.mediaUrl = ${info.srcUrl};
window.targetElementId = ${info.targetElementId};
`,
frameId: info.frameId
});
await browser.tabs.executeScript(tab.id, {
file: "senders/media/index.js",
frameId: info.frameId
});
} else {
// Handle other responses
loadSender({
tabId: tab.id,
frameId: info.frameId,
selection
});
}
break;
}
}
break;
}
}
});
// Hide cast item on extension pages
browser.menus.onShown.addListener(info => {
if (info.pageUrl?.startsWith(browser.runtime.getURL(""))) {
browser.menus.update(menuIdCast, {
visible: false
});
browser.menus.refresh();
}
});
browser.menus.onHidden.addListener(() => {
browser.menus.update(menuIdCast, {
visible: true
});
});
browser.menus.onShown.addListener(async info => {
// Only rebuild menus if whitelist menu present
// WebExt typings are broken again here, so ugly casting
const menuIds = info.menuIds as unknown as number[];
if (!menuIds.includes(menuIdWhitelist as number)) {
return;
}
/**
* If page URL doesn't exist, we're not on a page and have
* nothing to whitelist, so disable the menu and return.
*/
if (!info.pageUrl) {
browser.menus.update(menuIdWhitelist, {
enabled: false
});
browser.menus.refresh();
return;
}
const url = new URL(info.pageUrl);
const urlHasOrigin = url.origin !== "null";
/**
* If the page URL doesn't have an origin, we're not on a
* remote page and have nothing to whitelist, so disable the
* menu and return.
*/
if (!urlHasOrigin) {
browser.menus.update(menuIdWhitelist, {
enabled: false
});
browser.menus.refresh();
return;
}
// Enable the whitelist menu
browser.menus.update(menuIdWhitelist, {
enabled: true
});
for (const [menuId] of whitelistChildMenuPatterns) {
// Clear all page-specific temporary menus
if (menuId !== menuIdWhitelistRecommended) {
browser.menus.remove(menuId);
}
whitelistChildMenuPatterns.delete(menuId);
}
// If there is more than one subdomain, get the base domain
const baseDomain =
(url.hostname.match(/\./g) || []).length > 1
? url.hostname.substring(url.hostname.indexOf(".") + 1)
: url.hostname;
const portlessOrigin = `${url.protocol}//${url.hostname}`;
const patternRecommended = `${portlessOrigin}/*`;
const patternSearch = `${portlessOrigin}${url.pathname}${url.search}`;
const patternWildcardProtocol = `*://${url.hostname}/*`;
const patternWildcardSubdomain = `${url.protocol}//*.${baseDomain}/*`;
const patternWildcardProtocolAndSubdomain = `*://*.${baseDomain}/*`;
// Update recommended menu item
browser.menus.update(menuIdWhitelistRecommended, {
title: _("contextAddToWhitelistRecommended", patternRecommended)
});
whitelistChildMenuPatterns.set(
menuIdWhitelistRecommended,
patternRecommended
);
if (url.search) {
const whitelistSearchMenuId = browser.menus.create({
title: _("contextAddToWhitelistAdvancedAdd", patternSearch),
parentId: menuIdWhitelist
});
whitelistChildMenuPatterns.set(whitelistSearchMenuId, patternSearch);
}
/**
* Split URL path into segments and add menu items for each
* partial path as the segments are removed.
*/
{
const pathTrimmed = url.pathname.endsWith("/")
? url.pathname.substring(0, url.pathname.length - 1)
: url.pathname;
const pathSegments = pathTrimmed
.split("/")
.filter(segment => segment)
.reverse();
if (pathSegments.length) {
for (let i = 0; i < pathSegments.length; i++) {
const partialPath = pathSegments.slice(i).reverse().join("/");
const pattern = `${portlessOrigin}/${partialPath}/*`;
const partialPathMenuId = browser.menus.create({
title: _("contextAddToWhitelistAdvancedAdd", pattern),
parentId: menuIdWhitelist
});
whitelistChildMenuPatterns.set(partialPathMenuId, pattern);
}
}
}
const wildcardProtocolMenuId = browser.menus.create({
title: _("contextAddToWhitelistAdvancedAdd", patternWildcardProtocol),
parentId: menuIdWhitelist
});
whitelistChildMenuPatterns.set(
wildcardProtocolMenuId,
patternWildcardProtocol
);
const wildcardSubdomainMenuId = browser.menus.create({
title: _("contextAddToWhitelistAdvancedAdd", patternWildcardSubdomain),
parentId: menuIdWhitelist
});
whitelistChildMenuPatterns.set(
wildcardSubdomainMenuId,
patternWildcardSubdomain
);
const wildcardProtocolAndSubdomainMenuId = browser.menus.create({
title: _(
"contextAddToWhitelistAdvancedAdd",
patternWildcardProtocolAndSubdomain
),
parentId: menuIdWhitelist
});
whitelistChildMenuPatterns.set(
wildcardProtocolAndSubdomainMenuId,
patternWildcardProtocolAndSubdomain
);
await browser.menus.refresh();
});
options.addEventListener("changed", async ev => {
const alteredOpts = ev.detail;
const newOpts = await options.getAll();
if (menuIdMediaCast && alteredOpts.includes("mediaEnabled")) {
browser.menus.update(menuIdMediaCast, {
visible: newOpts.mediaEnabled
});
}
if (menuIdMediaCast && alteredOpts.includes("localMediaEnabled")) {
browser.menus.update(menuIdMediaCast, {
targetUrlPatterns: newOpts.localMediaEnabled
? URL_PATTERNS_ALL
: URL_PATTERNS_REMOTE
});
}
}); | the_stack |
import childProcess = require('child_process');
import fs = require('fs');
import http = require('http');
import uuid = require('node-uuid');
import path = require('path');
import querystring = require('querystring');
import url = require('url');
import util = require('util');
import idleTimeout = require('./idleTimeout');
import logging = require('./logging');
import userManager = require('./userManager');
var SETTINGS_FILE = 'settings.json';
var DEFAULT_USER_SETTINGS_FILE = 'userSettings.json';
var METADATA_FILE = 'metadata.json';
var BASE_PATH_FILE = 'basePath.json';
const IDLE_TIMEOUT_KEY = 'idleTimeoutInterval';
let lastUpdateUserSettingPromise = Promise.resolve(false);
interface Metadata {
instanceId: string;
}
/**
* Loads the configuration settings for the application to use.
* On first run, this generates any dynamic settings and merges them into the settings result.
* @returns the settings object for the application to use.
*/
export function loadAppSettings(): common.AppSettings {
var settingsPath = path.join(__dirname, 'config', SETTINGS_FILE);
var basePathFile = path.join(__dirname, 'config', BASE_PATH_FILE);
var metadataPath = path.join(__dirname, 'config', METADATA_FILE);
if (!fs.existsSync(settingsPath)) {
_logError('App settings file %s not found.', settingsPath);
return null;
}
try {
var metadata: Metadata = null;
if (!fs.existsSync(metadataPath)) {
// Create an write out metadata on the first run if it doesn't exist.
metadata = { instanceId: uuid.v4() };
fs.writeFileSync(metadataPath, JSON.stringify(metadata, null, 2), { encoding: 'utf8' });
}
else {
// Load metadata from the file system. This is written out on the first run.
metadata = <Metadata>JSON.parse(fs.readFileSync(metadataPath, 'utf8'));
}
const settings = <common.AppSettings>JSON.parse(fs.readFileSync(settingsPath, 'utf8') || '{}');
settings.versionId = process.env['DATALAB_VERSION'] || '';
if (process.env['DATALAB_CONFIG_URL']) {
settings.configUrl = process.env['DATALAB_CONFIG_URL'];
}
if (!fs.existsSync(basePathFile)) {
_log('Base path setting file not found, falling back to empty path.');
settings.datalabBasePath = '';
} else {
settings.datalabBasePath = JSON.parse(fs.readFileSync(basePathFile, 'utf8'));
}
const settingsOverrides = process.env['DATALAB_SETTINGS_OVERRIDES'];
if (settingsOverrides) {
// Allow overriding individual settings via JSON provided as an environment variable.
const overrides = JSON.parse(settingsOverrides);
for (const key of Object.keys(overrides)) {
(<any>settings)[key] = overrides[key];
}
}
// Normalize the base path to include "/" characters.
if (settings.datalabBasePath.indexOf("/") != 0) {
settings.datalabBasePath = "/" + settings.datalabBasePath;
}
if (settings.datalabBasePath.lastIndexOf("/") != settings.datalabBasePath.length - 1) {
settings.datalabBasePath = settings.datalabBasePath + "/";
}
return settings;
}
catch (e) {
_logError(e);
return null;
}
}
/**
* Loads the path of the configuration directory for the user.
*
* @returns the path of the user's config directory.
*/
export function getUserConfigDir(userId: string): string {
var userDir = userManager.getUserDir(userId);
var configPath = path.join(userDir, 'datalab', '.config');
return configPath;
}
/**
* Copies the default user settings into the user's directory.
*/
function getDefaultUserSettings(userId: string) {
const defaultUserSettingsPath = path.join(__dirname, 'config', DEFAULT_USER_SETTINGS_FILE);
_log('Getting default settings: ' + defaultUserSettingsPath);
// Copy the default user settings file into user's directory.
const defaultUserSettings = fs.readFileSync(defaultUserSettingsPath, {encoding: 'utf8'});
const initialUserSettings = process.env.DATALAB_INITIAL_USER_SETTINGS;
const mergedUserSettings : string = initialUserSettings ?
mergeUserSettings(defaultUserSettings, initialUserSettings) : defaultUserSettings;
return mergedUserSettings;
}
/**
* Copies the default user settings into the user's directory.
*/
function copyDefaultUserSettings(userId: string) {
var userSettingsPath = path.join(getUserConfigDir(userId), SETTINGS_FILE);
_log('Copying default settings to: ' + userSettingsPath);
fs.writeFileSync(userSettingsPath, getDefaultUserSettings(userId));
// writeFileSync does not return a status; let's see if it wrote a file.
if (!fs.existsSync(userSettingsPath)) {
_log('Failed to write new user settings file ' + userSettingsPath);
}
}
/**
* Merges two sets of user settings, giving priority to the second.
* Exported for testing.
*/
export function mergeUserSettings(defaultUserSettings: string, initialUserSettings: string): string {
let parsedDefaultUserSettings;
try {
parsedDefaultUserSettings = JSON.parse(defaultUserSettings || '{}')
} catch (e) {
// File is corrupt, or a developer has updated the defaults file with an error
_log('Error parsing default user settings:', e);
// We can't merge here, and this will probably cause problems down the line, but
// this should not happen, so hopefully the developer will see this and fix
// the default settings file.
return defaultUserSettings;
}
let parsedInitialUserSettings;
try {
parsedInitialUserSettings = JSON.parse(initialUserSettings || '{}')
} catch (e) {
// The user's initial settings are not valid, we will ignore them.
_log('Error parsing initial user settings:', e);
return defaultUserSettings;
}
// Override the default settings with the specified initial settings
const merged = {...parsedDefaultUserSettings, ...parsedInitialUserSettings};
return JSON.stringify(merged);
}
/**
* Loads the configuration settings for the user.
*
* @returns the key:value mapping of settings for the user.
*/
export function loadUserSettings(userId: string): common.UserSettings {
var settingsPath = path.join(getUserConfigDir(userId), SETTINGS_FILE);
if (!fs.existsSync(settingsPath)) {
_log('User settings file %s not found, copying default settings.', settingsPath);
try {
copyDefaultUserSettings(userId);
}
catch (e) {
_log('Failed to copy default settings, using from existing location.', e);
return <common.UserSettings>JSON.parse(getDefaultUserSettings(userId));
}
}
try {
const settings = <common.UserSettings>JSON.parse(fs.readFileSync(settingsPath, 'utf8') || '{}');
return settings;
}
catch (e) {
_logError('Failed to load user settings from ' + settingsPath + ':', e);
// Move the corrupt file to another name where the user can examine the
// contents later to see what went wrong.
renameBadUserSettings(settingsPath);
return {} as common.UserSettings;
}
}
// Exported for testing
export function ensureDirExists(fullPath: string): boolean {
if (path.dirname(fullPath) == fullPath) {
// This should only happen once we hit the root directory
return true;
}
if (fs.existsSync(fullPath)) {
if (!fs.lstatSync(fullPath).isDirectory()) {
_log('Path ' + fullPath + ' is not a directory');
return false;
}
return true;
}
if (!ensureDirExists(path.dirname(fullPath))) {
return false;
}
fs.mkdirSync(fullPath);
return true;
}
/**
* Asynchronously updates the user's settings file with the new value for the given key.
* If there is already an asynchronous update in progress, this request is queued up for
* execution after the current update finishes.
*
* @param key the name of the setting to update.
* @param value the updated value of the setting.
* @returns Promise that resolves to true if the write succeeded, false if there was no change
* and thus the write was not done, rejects if the file read or write fails.
*/
export function updateUserSettingAsync(userId: string, key: string, value: string): Promise<boolean> {
var settingsDir = getUserConfigDir(userId);
var settingsPath = path.join(settingsDir, SETTINGS_FILE);
const doUpdate = () => {
if (!fs.existsSync(settingsPath)) {
_log('User settings file %s not found, copying default settings.', settingsPath);
try {
copyDefaultUserSettings(userId);
}
catch (e) {
_log('Failed to update settings.', e);
return false;
}
}
let settings: common.UserSettings;
if (fs.existsSync(settingsPath)) {
try {
settings = <common.UserSettings>JSON.parse(fs.readFileSync(settingsPath, 'utf8') || '{}');
}
catch (e) {
_log(e);
throw new Error('Failed to read settings');
}
}
if (settings[key] == value) {
_log('No change to settings for key=%s, value=%s', key, value);
return false; // No change was required
}
settings[key] = value;
try {
var settingsString = JSON.stringify(settings);
if (ensureDirExists(path.normalize(settingsDir))) {
fs.writeFileSync(settingsPath, settingsString);
}
}
catch (e) {
_log(e);
throw new Error('Failed to write settings');
}
_log('Updated settings for key=' + key + ', value=' + value);
return true; // File was updated
}
// Execute our update as soon as all the other updates are done being executed.
lastUpdateUserSettingPromise = lastUpdateUserSettingPromise.catch().then(doUpdate);
return lastUpdateUserSettingPromise;
}
/**
* Implements setting update request handling.
* @param request the incoming http request.
* @param response the outgoing http response.
*/
function requestHandler(request: http.ServerRequest, response: http.ServerResponse): void {
if (request.url.indexOf('/_appsettings') === 0) {
appSettingsHandler(request, response);
} else {
var userId = userManager.getUserId(request);
if ('POST' == request.method) {
postSettingsHandler(userId, request, response);
} else {
getSettingsHandler(userId, request, response);
}
}
}
/**
* Handles app settings requests, returns the app settings JSON.
* @param request the incoming http request.
* @param response the outgoing http response.
*/
function appSettingsHandler(request: http.ServerRequest, response: http.ServerResponse): void {
const appSettings = loadAppSettings();
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end(JSON.stringify(appSettings));
}
/**
* Handles 'GET' requests to the settings handler.
* @param request the incoming http request.
* @param response the outgoing http response.
*/
function getSettingsHandler(userId: string, request: http.ServerRequest, response: http.ServerResponse): void {
const userSettings = loadUserSettings(userId);
const parsedUrl = url.parse(request.url, true);
if ('key' in parsedUrl.query) {
const key = parsedUrl.query['key'];
if (key in userSettings) {
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end(JSON.stringify(userSettings[key]));
} else {
response.writeHead(404, { 'Content-Type': 'text/plain' });
response.end();
}
return;
} else {
const visibleSettings = JSON.parse(JSON.stringify(userSettings));
if (visibleSettings[IDLE_TIMEOUT_KEY] === undefined) {
const appSettings = loadAppSettings();
visibleSettings[IDLE_TIMEOUT_KEY] = appSettings[IDLE_TIMEOUT_KEY];
}
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end(JSON.stringify(visibleSettings));
return;
}
}
/**
* Handles 'POST' requests to the settings handler.
* @param request the incoming http request.
* @param response the outgoing http response.
*/
function postSettingsHandler(userId: string, request: http.ServerRequest, response: http.ServerResponse): void {
var formData : any;
var body : string = "";
request.on('data', function(chunk: string) { body += chunk; });
request.on('end', function() {
if (body) {
formData = querystring.parse(body);
} else {
var parsedUrl = url.parse(request.url, true);
formData = parsedUrl.query;
}
formHandler(userId, formData, request, response);
});
}
/**
* Handles updating a setting given the parsed form contents.
* @param formData the form data parsed from the incoming http request.
* @param request the incoming http request.
* @param response the outgoing http response.
*/
function formHandler(userId: string, formData: any, request: http.ServerRequest, response: http.ServerResponse): void {
if (!(('key' in formData) && ('value' in formData))) {
response.writeHead(400, { 'Content-Type': 'text/plain' });
response.end('Missing one or more required fields');
return;
}
var key = formData['key'];
var value = formData['value'];
if (key == IDLE_TIMEOUT_KEY) {
if (value) {
const { seconds, errorMessage } = idleTimeout.parseAndValidateInterval(value);
if (errorMessage) {
response.writeHead(400, { 'Content-Type': 'text/plain' });
response.end(errorMessage);
return;
}
}
}
// If dryRun was set, we don't actually update anything.
if ('dryRun' in formData) {
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.end('dryRun');
return;
}
updateUserSettingAsync(userId, key, value).then(() => {
if ('redirect' in formData) {
response.writeHead(302, { 'Location': formData['redirect'] });
} else {
response.writeHead(200, { 'Content-Type': 'text/plain' });
}
response.end();
}).catch((errorMessage) => {
response.writeHead(500, { 'Content-Type': 'text/plain' });
response.end();
});
if (key == IDLE_TIMEOUT_KEY) {
idleTimeout.setIdleTimeoutInterval(value);
}
return;
}
/**
* Creates the setting updater request handler.
* @returns the request handler to handle setting update requests.
*/
export function createHandler(): http.RequestHandler {
return requestHandler;
}
function renameBadUserSettings(settingsPath: string) {
let newPath = settingsPath + ".bad";
let n = 0;
const maxBackups = 10;
while (fs.existsSync(newPath) && n < maxBackups) {
n = n + 1;
newPath = settingsPath + ".bad-" + n;
}
if (n >= maxBackups) {
_logError('Too many backups already (%d), not renaming bad file %s',
maxBackups, settingsPath);
} else {
fs.renameSync(settingsPath, newPath);
if (fs.existsSync(newPath)) {
_logError('Moved bad file %s to %s', settingsPath, newPath);
} else {
_logError('Failed to move bad file %s to %s', settingsPath, newPath);
}
}
}
/**
* Logs a debug message if the logger has been initialized,
* else logs to console.log.
*/
function _log(...args: Object[]) {
const logger = logging.getLogger();
if (logger) {
const msg = util.format.apply(util.format, args);
logger.debug(msg);
} else {
console.log.apply(console, args);
}
}
/**
* Logs an error message if the logger has been initialized,
* else logs to console.error.
*/
function _logError(...args: Object[]) {
const logger = logging.getLogger();
if (logger) {
const msg = util.format.apply(util.format, args);
logger.error(msg);
} else {
console.error.apply(console, args);
}
} | the_stack |
import { Event, TerminalSettingsId } from '@opensumi/ide-core-common';
import { localize } from '@opensumi/ide-core-common';
import { PreferenceSchema } from '@opensumi/ide-core-common/lib/preferences';
export interface IPreferenceValue {
name: string;
value: string | number | boolean | Array<string | number | boolean>;
}
export const ITerminalPreference = Symbol('ITerminalPreference');
export interface ITerminalPreference {
get<T = any>(key: string): T;
onChange: Event<IPreferenceValue>;
toJSON(): any;
}
export interface SupportedOptions {
allowTransparency: boolean;
macOptionIsMeta: boolean;
cursorBlink: boolean;
scrollback: number;
tabStopWidth: number;
fontSize: number;
copyOnSelection: boolean;
fontFamily: string;
}
export const SupportedOptionsName = {
type: 'type',
fontFamily: 'fontFamily',
fontSize: 'fontSize',
fontWeight: 'fontWeight',
lineHeight: 'lineHeight',
cursorBlink: 'cursorBlink',
scrollback: 'scrollback',
copyOnSelection: 'copyOnSelection',
};
export const enum CodeTerminalSettingPrefix {
Shell = 'terminal.integrated.shell.',
ShellArgs = 'terminal.integrated.shellArgs.',
DefaultProfile = 'terminal.integrated.defaultProfile.',
Profiles = 'terminal.integrated.profiles.',
}
export const enum CodeTerminalSettingId {
ShellLinux = 'terminal.integrated.shell.linux',
ShellMacOs = 'terminal.integrated.shell.osx',
ShellWindows = 'terminal.integrated.shell.windows',
SendKeybindingsToShell = 'terminal.integrated.sendKeybindingsToShell',
AutomationShellLinux = 'terminal.integrated.automationShell.linux',
AutomationShellMacOs = 'terminal.integrated.automationShell.osx',
AutomationShellWindows = 'terminal.integrated.automationShell.windows',
AutomationProfileLinux = 'terminal.integrated.automationProfile.linux',
AutomationProfileMacOs = 'terminal.integrated.automationProfile.osx',
AutomationProfileWindows = 'terminal.integrated.automationProfile.windows',
ShellArgsLinux = 'terminal.integrated.shellArgs.linux',
ShellArgsMacOs = 'terminal.integrated.shellArgs.osx',
ShellArgsWindows = 'terminal.integrated.shellArgs.windows',
ProfilesWindows = 'terminal.integrated.profiles.windows',
ProfilesMacOs = 'terminal.integrated.profiles.osx',
ProfilesLinux = 'terminal.integrated.profiles.linux',
DefaultProfileLinux = 'terminal.integrated.defaultProfile.linux',
DefaultProfileMacOs = 'terminal.integrated.defaultProfile.osx',
DefaultProfileWindows = 'terminal.integrated.defaultProfile.windows',
UseWslProfiles = 'terminal.integrated.useWslProfiles',
TabsEnabled = 'terminal.integrated.tabs.enabled',
TabsEnableAnimation = 'terminal.integrated.tabs.enableAnimation',
TabsHideCondition = 'terminal.integrated.tabs.hideCondition',
TabsShowActiveTerminal = 'terminal.integrated.tabs.showActiveTerminal',
TabsShowActions = 'terminal.integrated.tabs.showActions',
TabsLocation = 'terminal.integrated.tabs.location',
TabsFocusMode = 'terminal.integrated.tabs.focusMode',
MacOptionIsMeta = 'terminal.integrated.macOptionIsMeta',
MacOptionClickForcesSelection = 'terminal.integrated.macOptionClickForcesSelection',
AltClickMovesCursor = 'terminal.integrated.altClickMovesCursor',
CopyOnSelection = 'terminal.integrated.copyOnSelection',
DrawBoldTextInBrightColors = 'terminal.integrated.drawBoldTextInBrightColors',
FontFamily = 'terminal.integrated.fontFamily',
FontSize = 'terminal.integrated.fontSize',
LetterSpacing = 'terminal.integrated.letterSpacing',
LineHeight = 'terminal.integrated.lineHeight',
MinimumContrastRatio = 'terminal.integrated.minimumContrastRatio',
FastScrollSensitivity = 'terminal.integrated.fastScrollSensitivity',
MouseWheelScrollSensitivity = 'terminal.integrated.mouseWheelScrollSensitivity',
BellDuration = 'terminal.integrated.bellDuration',
FontWeight = 'terminal.integrated.fontWeight',
FontWeightBold = 'terminal.integrated.fontWeightBold',
CursorBlinking = 'terminal.integrated.cursorBlinking',
CursorStyle = 'terminal.integrated.cursorStyle',
CursorWidth = 'terminal.integrated.cursorWidth',
Scrollback = 'terminal.integrated.scrollback',
DetectLocale = 'terminal.integrated.detectLocale',
DefaultLocation = 'terminal.integrated.defaultLocation',
GpuAcceleration = 'terminal.integrated.gpuAcceleration',
TerminalTitleSeparator = 'terminal.integrated.tabs.separator',
TerminalTitle = 'terminal.integrated.tabs.title',
TerminalDescription = 'terminal.integrated.tabs.description',
RightClickBehavior = 'terminal.integrated.rightClickBehavior',
Cwd = 'terminal.integrated.cwd',
ConfirmOnExit = 'terminal.integrated.confirmOnExit',
ConfirmOnKill = 'terminal.integrated.confirmOnKill',
EnableBell = 'terminal.integrated.enableBell',
CommandsToSkipShell = 'terminal.integrated.commandsToSkipShell',
AllowChords = 'terminal.integrated.allowChords',
AllowMnemonics = 'terminal.integrated.allowMnemonics',
EnvMacOs = 'terminal.integrated.env.osx',
EnvLinux = 'terminal.integrated.env.linux',
EnvWindows = 'terminal.integrated.env.windows',
EnvironmentChangesIndicator = 'terminal.integrated.environmentChangesIndicator',
EnvironmentChangesRelaunch = 'terminal.integrated.environmentChangesRelaunch',
ShowExitAlert = 'terminal.integrated.showExitAlert',
SplitCwd = 'terminal.integrated.splitCwd',
WindowsEnableConpty = 'terminal.integrated.windowsEnableConpty',
WordSeparators = 'terminal.integrated.wordSeparators',
EnableFileLinks = 'terminal.integrated.enableFileLinks',
UnicodeVersion = 'terminal.integrated.unicodeVersion',
ExperimentalLinkProvider = 'terminal.integrated.experimentalLinkProvider',
LocalEchoLatencyThreshold = 'terminal.integrated.localEchoLatencyThreshold',
LocalEchoEnabled = 'terminal.integrated.localEchoEnabled',
LocalEchoExcludePrograms = 'terminal.integrated.localEchoExcludePrograms',
LocalEchoStyle = 'terminal.integrated.localEchoStyle',
EnablePersistentSessions = 'terminal.integrated.enablePersistentSessions',
PersistentSessionReviveProcess = 'terminal.integrated.persistentSessionReviveProcess',
CustomGlyphs = 'terminal.integrated.customGlyphs',
PersistentSessionScrollback = 'terminal.integrated.persistentSessionScrollback',
InheritEnv = 'terminal.integrated.inheritEnv',
ShowLinkHover = 'terminal.integrated.showLinkHover',
IgnoreProcessNames = 'terminal.integrated.ignoreProcessNames',
AutoReplies = 'terminal.integrated.autoReplies',
}
const shellDeprecationMessageLinux = localize(
'terminal.integrated.shell.linux.deprecation',
'This is deprecated, the new recommended way to configure your default shell is by creating a terminal profile in {0} and setting its profile name as the default in {1}. This will currently take priority over the new profiles settings but that will change in the future.',
'`#terminal.integrated.profiles.linux#`',
);
const shellDeprecationMessageOsx = localize(
'terminal.integrated.shell.osx.deprecation',
'This is deprecated, the new recommended way to configure your default shell is by creating a terminal profile in {0} and setting its profile name as the default in {1}. This will currently take priority over the new profiles settings but that will change in the future.',
'`#terminal.integrated.profiles.osx#`',
);
const shellDeprecationMessageWindows = localize(
'terminal.integrated.shell.windows.deprecation',
'This is deprecated, the new recommended way to configure your default shell is by creating a terminal profile in {0} and setting its profile name as the default in {1}. This will currently take priority over the new profiles settings but that will change in the future.',
'`#terminal.integrated.profiles.windows#`',
);
export const terminalPreferenceSchema: PreferenceSchema = {
type: 'object',
properties: {
// 终端
[TerminalSettingsId.Type]: {
type: 'string',
enum: ['zsh', 'bash', 'sh', 'default'], // for unix
default: 'default',
description: '%preference.terminal.typeDesc%',
},
[TerminalSettingsId.FontFamily]: {
type: 'string',
},
[TerminalSettingsId.FontSize]: {
type: 'number',
default: 12,
},
[TerminalSettingsId.FontWeight]: {
type: 'string',
enum: ['normal', 'bold'],
default: 400,
},
[TerminalSettingsId.LineHeight]: {
type: 'number',
default: 1,
},
[TerminalSettingsId.CursorBlink]: {
type: 'boolean',
default: false,
},
[TerminalSettingsId.Scrollback]: {
type: 'number',
default: 5000,
},
[CodeTerminalSettingId.ShellArgsLinux]: {
type: 'array',
default: [],
description: '%preference.terminal.integrated.shellArgs.linuxDesc%',
markdownDeprecationMessage: shellDeprecationMessageLinux,
},
[CodeTerminalSettingId.ShellArgsMacOs]: {
type: 'array',
// Unlike on Linux, ~/.profile is not sourced when logging into a macOS session. This
// is the reason terminals on macOS typically run login shells by default which set up
// the environment. See http://unix.stackexchange.com/a/119675/115410
default: ['-l'],
markdownDeprecationMessage: shellDeprecationMessageOsx,
},
[CodeTerminalSettingId.ShellArgsWindows]: {
type: 'array',
default: [],
markdownDeprecationMessage: shellDeprecationMessageWindows,
},
[CodeTerminalSettingId.ProfilesWindows]: {
restricted: true,
// comment: ['{0}, {1}, and {2} are the `source`, `path` and optional `args` settings keys'],
markdownDescription: localize(
'terminal.integrated.profiles.windows',
'The Windows profiles to present when creating a new terminal via the terminal dropdown. Use the `path` property to automatically detect the shell\'s location. Or set the {1} property manually with an optional `args`.\n\nSet an existing profile to `null` to hide the profile from the list, for example: `"Ubuntu-20.04 (WSL)": null`.',
),
type: 'object',
default: {},
},
[CodeTerminalSettingId.ProfilesMacOs]: {
restricted: true,
markdownDescription: localize(
'terminal.integrated.profile.osx',
'The macOS profiles to present when creating a new terminal via the terminal dropdown. Set the `path` property manually with an optional `args`.\n\nSet an existing profile to `null` to hide the profile from the list, for example: `"bash": null`.',
),
type: 'object',
default: {
bash: {
path: 'bash',
args: ['-l'],
// icon: 'terminal-bash',
},
zsh: {
path: 'zsh',
args: ['-l'],
},
fish: {
path: 'fish',
args: ['-l'],
},
tmux: {
path: 'tmux',
// icon: 'terminal-tmux',
},
pwsh: {
path: 'pwsh',
// icon: 'terminal-powershell',
},
},
},
[CodeTerminalSettingId.ProfilesLinux]: {
restricted: true,
markdownDescription: localize(
'terminal.integrated.profile.linux',
'The Linux profiles to present when creating a new terminal via the terminal dropdown. Set the `path` property manually with an optional `args`.\n\nSet an existing profile to `null` to hide the profile from the list, for example: `"bash": null`.',
),
type: 'object',
default: {
bash: {
path: 'bash',
icon: 'terminal-bash',
},
zsh: {
path: 'zsh',
},
fish: {
path: 'fish',
},
tmux: {
path: 'tmux',
icon: 'terminal-tmux',
},
pwsh: {
path: 'pwsh',
icon: 'terminal-powershell',
},
},
},
[CodeTerminalSettingId.DefaultProfileLinux]: {
restricted: true,
markdownDescription: localize(
'terminal.integrated.defaultProfile.linux',
'The default profile used on Linux. This setting will currently be ignored if either {0} or {1} are set.',
),
type: ['string', 'null'],
default: null,
},
[CodeTerminalSettingId.DefaultProfileMacOs]: {
restricted: true,
markdownDescription: localize(
'terminal.integrated.defaultProfile.osx',
'The default profile used on macOS. This setting will currently be ignored if either {0} or {1} are set.',
),
type: ['string', 'null'],
default: null,
},
[CodeTerminalSettingId.DefaultProfileWindows]: {
restricted: true,
markdownDescription: localize(
'terminal.integrated.defaultProfile.windows',
'The default profile used on Windows. This setting will currently be ignored if either {0} or {1} are set.',
),
type: ['string', 'null'],
default: null,
},
[CodeTerminalSettingId.CopyOnSelection]: {
type: 'boolean',
description: '%preference.terminal.integrated.copyOnSelectionDesc%',
default: false,
},
[CodeTerminalSettingId.LocalEchoEnabled]: {
type: 'boolean',
description: '%preference.terminal.integrated.localEchoDesc%',
default: true,
},
[CodeTerminalSettingId.LocalEchoLatencyThreshold]: {
type: 'number',
description: '%preference.terminal.integrated.localEchoLatencyThresholdDesc%',
default: 30,
},
[CodeTerminalSettingId.LocalEchoExcludePrograms]: {
type: 'array',
description: '%preference.terminal.integrated.localEchoExcludeProgramsDesc%',
default: ['vim', 'vi', 'nano', 'tmux'],
},
[CodeTerminalSettingId.LocalEchoStyle]: {
type: 'string',
description: '%preference.terminal.integrated.localEchoStyleDesc%',
default: 'dim',
},
},
}; | the_stack |
import {Component, EventEmitter, Input, OnInit, Output} from "@angular/core";
import {AbstractControl, FormControl, FormGroup, Validators} from "@angular/forms";
import {User} from "../../../../../electron/src/sbg-api-client/interfaces/user";
import {AuthService} from "../../../auth/auth.service";
import {AuthCredentials} from "../../../auth/model/auth-credentials";
import {GetStartedNotificationComponent} from "../../../layout/notification-bar/dynamic-notifications/get-started-notification/get-started-notification.component";
import {NotificationBarService} from "../../../layout/notification-bar/notification-bar.service";
import {SystemService} from "../../../platform-providers/system.service";
import {ModalService} from "../../../ui/modal/modal.service";
import {DataGatewayService} from "../../data-gateway/data-gateway.service";
import {GlobalService} from "../../global/global.service";
import {fromPromise} from "rxjs/observable/fromPromise";
import {withLatestFrom, take} from "rxjs/operators";
@Component({
selector: "ct-platform-credentials-modal",
template: `
<form class="auth-form" data-test="credentials-modal-form" (ngSubmit)="form.valid && applyChanges()" [formGroup]="form">
<div class="m-2">
<p>Connect your Platform account to create and edit Platform apps.</p>
<input type="hidden" formControlName="user"/>
<div class="row form-group platform-row" [class.has-warning]="form.get('url').invalid">
<label class="col-xs-5 col-form-label">Platform:</label>
<div class="col-xs-7">
<ct-auto-complete [mono]="true"
[create]="true"
[sortField]="false"
formControlName="url"
[options]="platformList"
[readonly]="tokenOnly"
data-test="credentials-modal-platform-field"></ct-auto-complete>
</div>
</div>
<div class="row form-group" [class.has-warning]="form.get('token').invalid">
<label class="col-xs-5 col-form-label">Authentication Token:</label>
<div class="col-xs-7 form-inline token-form">
<input data-test="credentials-modal-token-field"
formControlName="token"
class="form-control token-control"
type="password"/>
</div>
<button class="btn btn-link"
type="button"
data-test="credentials-modal-get-token-button"
[disabled]="form.get('url').invalid"
(click)="openTokenPage()">Access your Token
</button>
</div>
<div *ngIf="form.dirty && form.invalid">
<span class="text-warning" *ngIf="form.get('token').hasError('required')">
<i class="fa fa-warning fa-fw"></i>
Token cannot be empty
</span>
<span class="text-danger" *ngIf="form.get('url').hasError('name')">
<i class="fa fa-times-circle fa-fw"></i>
<span>Given Platform does not exist.</span>
</span>
<span class="text-danger" *ngIf="form.get('token').hasError('pattern')">
<i class="fa fa-times-circle fa-fw"></i>
<span>Invalid token</span>
</span>
<span class="text-danger" *ngIf="form.hasError('tokenCheck')">
<i class="fa fa-times-circle fa-fw"></i>
<span>Token is not valid for the selected Platform. ({{ form.getError("tokenCheck") }})</span>
</span>
<span *ngIf="form.hasError('timeout')" class="text-danger">
<i class="fa fa-times-circle fa-fw"></i>
<span>Connection timed-out while trying to contact the Platform.</span>
</span>
<span *ngIf="form.hasError('notfound')" class="text-danger">
<i class="fa fa-times-circle fa-fw"></i>
<span>Cannot connect to the Platform. Are you online?</span>
</span>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" (click)="close()" data-test="credentials-modal-cancel-button">Cancel
</button>
<button class="btn btn-primary"
type="submit"
data-test="credentials-modal-apply-button"
[class.btn-loader]="form.pending"
[disabled]="!form.valid || !form.dirty">
<ng-container *ngIf="!form.pending">Add</ng-container>
<ct-circular-loader class="loader-25" *ngIf="form.pending"></ct-circular-loader>
</button>
</div>
</form>
`,
styleUrls: ["./platform-credentials-modal.component.scss"],
})
export class PlatformCredentialsModalComponent implements OnInit {
/** Allow only token update. If this is true, platform will be disabled and username of the new token must match the old one. */
@Input() tokenOnly = false;
/** Force user to be the active one in token only mode (when modal is open in order to add a specific user) */
@Input() forceActivateUser = false;
/** Public API url */
@Input() platform = "https://api.sbgenomics.com";
/** Combined with the “tokenOnly” parameter, checks whether the modified token for a given platform belongs to this user. */
@Input() user: User;
/** Modal can be given preset with a token */
@Input() token: string;
/** Submit (Apply) button stream */
@Output() submit = new EventEmitter();
/** FormGroup for modal inputs */
form: FormGroup;
platformList = [];
constructor(private system: SystemService,
private auth: AuthService,
private global: GlobalService,
private data: DataGatewayService,
private notificationBarService: NotificationBarService,
private modal: ModalService) {
const platformLookupByAPIURL = AuthCredentials.platformLookupByAPIURL;
this.platformList = Object.keys(platformLookupByAPIURL).map((item) => {
return {
text: platformLookupByAPIURL[item].name, value: item
}
});
}
applyChanges(): void {
const {url, token, user} = this.form.getRawValue();
const credentials = new AuthCredentials(url, token, user);
const activeCredentials = this.auth.getActive();
const allCredentials = this.auth.getCredentials();
const credentialsUpdate = fromPromise(this.auth.addCredentials(credentials));
credentialsUpdate.pipe(
withLatestFrom(activeCredentials, allCredentials, (_, active, all) => [active, all]),
take(1)
).subscribe((results: [AuthCredentials | undefined, AuthCredentials[]]) => {
const [active, all] = results;
// Determine whether we are adding new creds or updating old ones
const isEditing = this.tokenOnly;
const editedCredentials = new AuthCredentials(url, token, user);
let maybeUserUpdate = Promise.resolve();
if (isEditing) {
if (editedCredentials.equals(active) || this.forceActivateUser) {
// If we are editing credentials that appear to be active, update it
maybeUserUpdate = this.auth.setActiveCredentials(editedCredentials);
}
} else {
// Activate added credentials
maybeUserUpdate = this.auth.setActiveCredentials(credentials);
const component = this.notificationBarService.showDynamicNotification(GetStartedNotificationComponent, {
type: "success"
});
component.environment = AuthCredentials.getPlatformLabel(url);
component.username = user.username;
component.dismiss.pipe(
take(1)
).subscribe(() => {
this.notificationBarService.dismissDynamicNotification(component);
});
}
maybeUserUpdate.then(() => this.global.reloadPlatformData());
this.submit.next(true);
});
}
getValue(): AuthCredentials {
const {url, token, user} = this.form.getRawValue();
return new AuthCredentials(url, token, user);
}
/**
* Prepare a form for editing an existing {@link AuthCredentials} object.
* This will populate form fields with credentials properties and lock everything except token editing.
*
* @param {AuthCredentials} credentials
*/
prepareEdit(credentials: AuthCredentials): void {
this.user = credentials.user;
this.token = credentials.token;
this.platform = credentials.url;
this.tokenOnly = true;
}
ngOnInit() {
this.form = new FormGroup({
url: new FormControl(this.platform, [
Validators.required,
(ctrl: AbstractControl) => {
const val = ctrl.value;
if (!(val in AuthCredentials.platformLookupByAPIURL)) {
try {
const url = new URL(val);
if (url.hostname.endsWith(".sbgenomics.com") || url.hostname.endsWith(".nhlbi.nih.gov")) {
return null;
} else {
return {name: true};
}
} catch(ex){
return {name: true}
}
} else {
return null;
}
}
]),
token: new FormControl(this.token, [
Validators.required,
Validators.pattern(AuthCredentials.TOKEN_VALIDATION_REGEXP)
]),
user: new FormControl(this.user)
},
// No sync validators on the form level
null,
/**
* Create an async validator which checks if we can fetch a user from the selected platform with a given token
*/
this.debounce((form: FormGroup) => {
form.get("user").setValue(undefined, {emitEvent: false, onlySelf: true});
const {url, token} = form.getRawValue();
return this.data.getUserWithToken(url, token).pipe(
take(1)
).toPromise().then(user => {
form.get("user").setValue(user, {emitEvent: false, onlySelf: true});
if (this.tokenOnly && user.username !== this.user.username) {
return {tokenCheck: "Token belongs to a different user."};
}
return null;
}, rejection => {
if(rejection.error){
if (rejection.error.code === "ESOCKETTIMEDOUT") {
return {timeout: rejection.message}
} else if (rejection.error.code === "ENOTFOUND"){
return {notfound: rejection.message}
}
}
return {tokenCheck: rejection.message};
});
})
);
}
openTokenPage() {
const apiURL: string = this.form.get("url").value;
// Remove port from url
const platformAPIURL = apiURL.replace(/(:[1-9]+)$/, "");
const isPlatform =
AuthCredentials.platformLookupByAPIURL[platformAPIURL] || AuthCredentials.stagingLookupByAPIURL[platformAPIURL];
const url = isPlatform ? isPlatform.platformURL : platformAPIURL;
const devTokenPath = AuthCredentials.platformDevTokenPath;
this.system.openLink(`${url}${devTokenPath}`);
}
close() {
this.modal.close();
}
private debounce(fn: (control: AbstractControl) => Promise<any>, time = 300): (control: AbstractControl) => Promise<any> {
let timeout;
return (control: AbstractControl) => {
return new Promise((resolve, reject) => {
clearTimeout(timeout);
timeout = setTimeout(() => {
fn(control).then(resolve, reject);
}, time);
});
};
}
} | the_stack |
import {
Address,
constant,
Deploy,
Hash256,
MapStorage,
crypto,
Fixed8,
createEventNotifier,
SmartContract,
} from '@neo-one/smart-contract';
const notifyDeposited = createEventNotifier<Address, Address, Fixed8>('deposited', 'address', 'assetID', 'amount');
const notifyWithdrawn = createEventNotifier<Address, Address, Fixed8>('withdrawn', 'address', 'assetID', 'amount');
const notifyOfferCreated = createEventNotifier<Address, Address, Fixed8, Address, Fixed8, Hash256>(
'offerCreated',
'makerAddress',
'offerAssetID',
'offerAmount',
'wantAssetID',
'wantAmount',
'offerHash',
);
const notifyOfferCancelled = createEventNotifier<Hash256>('offerCancelled', 'offerHash');
const notifyBurnt = createEventNotifier<Address, Address, Fixed8>(
'burnt',
'filler',
'takerFeeAssetID',
'takerFeeAmount',
);
const notifyFilled = createEventNotifier<Address, Hash256, Fixed8, Address, Fixed8, Address, Fixed8, Fixed8>(
'offerFilled',
'filler',
'offerHash',
'amountToFill',
'offerAssetID',
'offerAmount',
'wantAssetID',
'wantAmount',
'amountToTake',
);
interface NEP17 {
readonly transfer: (from: Address, to: Address, amount: Fixed8) => boolean;
}
type Offer = {
readonly maker: Address;
readonly offerAssetID: Address;
readonly offerAmount: Fixed8;
readonly wantAssetID: Address;
readonly wantAmount: Fixed8;
readonly makerFeeAssetID: Address;
readonly makerFeeAvailableAmount: Fixed8;
readonly nonce: string;
};
// Based on the Switcheo BrokerContract: https://github.com/Switcheo/switcheo-neo
export class Exchange extends SmartContract {
private mutableFeeAddress: Address;
private readonly balances = MapStorage.for<[Address, Address], Fixed8>();
private readonly offers = MapStorage.for<Hash256, Offer>();
public constructor(public readonly owner: Address = Deploy.senderAddress) {
super();
if (!Address.isCaller(owner)) {
throw new Error('Sender was not the owner.');
}
this.mutableFeeAddress = this.address;
}
@constant
public balanceOf(address: Address, assetID: Address): Fixed8 {
const balance = this.balances.get([address, assetID]);
return balance === undefined ? 0 : balance;
}
@constant
public getOffer(offerHash: Hash256): Offer | undefined {
return this.offers.get(offerHash);
}
public depositNEP17(from: Address, assetID: Address, amount: Fixed8): void {
if (!Address.isCaller(from)) throw new Error('Caller was not the sender!');
if (amount < 1) throw new Error('Amount must be greater than 0!');
this.transferNEP17(from, this.address, assetID, amount);
this.balances.set([from, assetID], this.balanceOf(from, assetID) + amount);
notifyDeposited(from, assetID, amount);
}
public withdrawNEP17(from: Address, assetID: Address, amount: Fixed8): void {
if (amount < 0) throw new Error(`Amount must be greater than 0: ${amount}`);
const balance = this.balanceOf(from, assetID);
if (balance < amount) throw new Error(`Not enough Balance to withdraw ${amount}!`);
if (!Address.isCaller(from)) throw new Error('Caller is not authorized to withdraw funds!');
this.transferNEP17(this.address, from, assetID, amount);
this.balances.set([from, assetID], this.balanceOf(from, assetID) - amount);
notifyWithdrawn(from, assetID, amount);
}
public makeOffer(
maker: Address,
offerAssetID: Address,
offerAmount: Fixed8,
wantAssetID: Address,
wantAmount: Fixed8,
makerFeeAssetID: Address,
makerFeeAvailableAmount: Fixed8,
nonce: string,
): void {
// Check that transaction is called/signed by the maker
if (!Address.isCaller(maker)) throw new Error('Caller is not authorized to make an offer on behalf of the maker!');
// Check that the offer does not already exist
const offerHash = this.getOfferHash(
maker,
offerAssetID,
offerAmount,
wantAssetID,
wantAmount,
makerFeeAssetID,
makerFeeAvailableAmount,
nonce,
);
if (this.getOffer(offerHash) !== undefined) throw new Error('Offer does not exist!');
// Check that amounts > 0
if (offerAmount <= 0 || wantAmount <= 0) throw new Error('Invalid amount. All amounts must be > 0!');
// Check that the trade is across different assets
if (offerAssetID === wantAssetID) throw new Error('Cannot make an offer for the same asset!');
// Check fees
if (makerFeeAvailableAmount < 0) throw new Error('Fee available amount cannot be < 0!');
// Reduce available balance for the offered asset and amount
this.balances.set([maker, offerAssetID], this.balanceOf(maker, offerAssetID) - offerAmount);
// Reserve fees from the maker fee asset only if it is different from want asset
if (makerFeeAssetID !== wantAssetID && makerFeeAvailableAmount > 0) {
// Reduce fees here separately as it is a different asset type
this.balances.set([maker, makerFeeAssetID], this.balanceOf(maker, makerFeeAssetID) - makerFeeAvailableAmount);
}
// Add the offer to storage
this.offers.set(offerHash, {
maker,
offerAssetID,
offerAmount,
wantAssetID,
wantAmount,
makerFeeAssetID,
makerFeeAvailableAmount,
nonce,
});
notifyOfferCreated(maker, offerAssetID, offerAmount, wantAssetID, wantAmount, offerHash);
}
// Currently above the 10 GAS limit.
public fillOffer(
filler: Address,
offerHash: Hash256,
amountToTake: Fixed8,
takerFeeAssetID: Address,
takerFeeAmount: Fixed8,
burnTakerFee: boolean,
makerFeeAmount: Fixed8,
burnMakerFee: boolean,
): void {
// Check that transaction is called/signed by the filler
if (!Address.isCaller(filler)) throw new Error('Caller is not authorized to fill offer on behalf of the filler!');
// Check fees
if (takerFeeAmount < 0) throw new Error('takerFeeAmount must not be < 0!');
if (makerFeeAmount < 0) throw new Error('makerFeeAmount must not be < 0!');
// Check that the offer still exists
const offer = this.getOffer(offerHash);
if (offer === undefined) throw new Error('Offer does not exist!');
// Check that the filler is different from the maker
if (filler === offer.maker) throw new Error('Filler cannot be the same as the maker!');
// Check that the amount that will be taken is at least 1
if (amountToTake < 1) throw new Error('Filler must take a nonzero amount of the offered asset!');
// Check that you cannot take more than available
if (amountToTake > offer.offerAmount) throw new Error('Filler requests more than available in offer!');
// Calculate amount we have to give the offerer (what the offerer wants)
const amountToFill = (amountToTake * offer.wantAmount) / offer.offerAmount;
if (amountToFill < 1) throw new Error('Must fill a nonzero amount of the offered asset!');
// Check that there is enough balance to reduce for filler
const wantAssetBalance = this.balanceOf(filler, offer.wantAssetID);
if (wantAssetBalance < amountToFill) throw new Error('Not enough balance to fill offer!');
// Check if we should deduct fees separately from the taker amount & there is enough balance in native fees if using native fees
const deductTakerFeesSeparately = takerFeeAssetID !== offer.offerAssetID;
const feeAssetBalance = this.balanceOf(filler, takerFeeAssetID);
if (deductTakerFeesSeparately && takerFeeAmount > 0 && feeAssetBalance <= takerFeeAmount) {
throw new Error('Filler does not have enough balance for fee!');
}
// Check that maker fee does not exceed remaining amount that can be deducted as maker fees
if (offer.makerFeeAvailableAmount < makerFeeAmount) throw new Error('Maker does not have enough balance for fee!');
// Check if we should deduct fees separately from the maker receiving amount
const deductMakerFeesSeparately = offer.makerFeeAssetID !== offer.wantAssetID;
// Reduce balance from filler
this.balances.set([filler, offer.wantAssetID], this.balanceOf(filler, offer.wantAssetID) - amountToFill);
// Move filled asset to the maker balance (reduce fees if needed)
const amountForMakerAfterFees = deductMakerFeesSeparately ? amountToFill : amountToFill - makerFeeAmount;
this.balances.set(
[offer.maker, offer.wantAssetID],
this.balanceOf(offer.maker, offer.wantAssetID) + amountForMakerAfterFees,
);
// Move taken asset to the taker balance
const amountToTakeAfterFees = deductTakerFeesSeparately ? amountToTake : amountToTake - takerFeeAmount;
this.balances.set([filler, offer.offerAssetID], this.balanceOf(filler, offer.offerAssetID) + amountToTakeAfterFees);
// Move fees
if (takerFeeAmount > 0) {
if (deductTakerFeesSeparately) {
// Reduce fees here from contract balance separately as it is a different asset type
this.balances.set([filler, takerFeeAssetID], this.balanceOf(filler, takerFeeAssetID) - takerFeeAmount);
}
if (burnTakerFee) {
// Emit burnt event for easier client tracking
notifyBurnt(filler, takerFeeAssetID, takerFeeAmount);
} else {
// Only increase fee address balance if not burning
this.balances.set(
[this.feeAddress, takerFeeAssetID],
this.balanceOf(this.feeAddress, takerFeeAssetID) + takerFeeAmount,
);
}
}
let makerFeeAvailableAmount = offer.makerFeeAvailableAmount;
if (makerFeeAmount > 0) {
// Reduce from available maker fees here
makerFeeAvailableAmount = offer.makerFeeAvailableAmount - makerFeeAmount;
if (burnMakerFee) {
// Emit burnt event for easier client tracking
notifyBurnt(offer.maker, offer.makerFeeAssetID, makerFeeAmount);
} else {
// Only increase fee address balance if not burning
this.balances.set(
[this.feeAddress, offer.makerFeeAssetID],
this.balanceOf(this.feeAddress, offer.makerFeeAssetID) + makerFeeAmount,
);
}
}
const offerAmount = offer.offerAmount - amountToTake;
const wantAmount = offer.wantAmount - amountToFill;
if (offerAmount === 0) {
this.offers.delete(offerHash);
} else {
this.offers.set(offerHash, { ...offer, offerAmount, wantAmount, makerFeeAvailableAmount });
}
notifyFilled(
filler,
offerHash,
amountToFill,
offer.offerAssetID,
offer.offerAmount,
offer.wantAssetID,
offer.wantAmount,
amountToTake,
);
}
public cancelOffer(maker: Address, offerHash: Hash256): void {
if (!Address.isCaller(maker)) throw new Error('Only the offer maker may cancel an offer!');
const offer = this.getOffer(offerHash);
if (offer === undefined) throw new Error('Offer does not exist!');
this.balances.set([maker, offer.offerAssetID], this.balanceOf(maker, offer.offerAssetID) + offer.offerAmount);
this.balances.set(
[maker, offer.makerFeeAssetID],
this.balanceOf(maker, offer.makerFeeAssetID) + offer.makerFeeAvailableAmount,
);
this.offers.delete(offerHash);
notifyOfferCancelled(offerHash);
}
public set feeAddress(address: Address) {
if (!Address.isCaller(this.owner)) {
throw new Error('Only the contract owner can change the FeeAddress!');
}
this.mutableFeeAddress = address;
}
@constant
public get feeAddress(): Address {
return this.mutableFeeAddress;
}
private getOfferHash(
maker: Address,
offerAssetID: Address,
offerAmount: Fixed8,
wantAssetID: Address,
wantAmount: Fixed8,
makerFeeAssetID: Address,
makerFeeAvailableAmount: Fixed8,
nonce: string,
): Hash256 {
const offerBuffer = Buffer.concat([
maker,
offerAssetID,
wantAssetID,
makerFeeAssetID,
Buffer.from([offerAmount, wantAmount, makerFeeAvailableAmount].toString()),
Buffer.from(nonce),
]);
return crypto.hash256(offerBuffer);
}
private transferNEP17(from: Address, to: Address, assetID: Address, amount: Fixed8): void {
const nep17Asset = SmartContract.for<NEP17>(assetID);
if (!nep17Asset.transfer(from, to, amount)) {
throw new Error('Failed to transfer NEP-5 tokens!');
}
}
} | the_stack |
import Obniz from '../../../obniz';
const OK: any = true;
const ERROR: any = false;
import ObnizPartsInterface, {
ObnizPartsInfo,
} from '../../../obniz/ObnizPartsInterface';
export interface MFRC522Options {
gnd?: number;
vcc?: number;
cs: number;
clk?: number;
mosi: number;
miso: number;
spi?: number;
spi_frequency?: number;
pull?: any;
rst: number;
}
export default class MFRC522 implements ObnizPartsInterface {
public static info(): ObnizPartsInfo {
return {
name: 'MFRC522',
};
}
public PCD_Idle: any;
public PCD_Mem: any;
public PCD_GenerateRandomID: any;
public PCD_CalcCRC: any;
public PCD_Transmit: any;
public PCD_NoCmdChange: any;
public PCD_Receive: any;
public PCD_Transceive: any;
public PCD_MFAuthent: any;
public PCD_SoftReset: any;
public RxGain_18dB: any;
public RxGain_23dB: any;
public RxGain_18dB_2: any;
public RxGain_23dB_2: any;
public RxGain_33dB: any;
public RxGain_38dB: any;
public RxGain_43dB: any;
public RxGain_48dB: any;
public RxGain_min: any;
public RxGain_avg: any;
public RxGain_max: any;
public PICC_REQA: any;
public PICC_WUPA: any;
public PICC_CT: any;
public PICC_SEL_CL1: any;
public PICC_SEL_CL2: any;
public PICC_SEL_CL3: any;
public PICC_HLTA: any;
public PICC_RATS: any;
public PICC_AUTH_KEYA: any;
public PICC_AUTH_KEYB: any;
public PICC_READ: any;
public PICC_WRITE: any;
public PICC_DECREMENT: any;
public PICC_INCREMENT: any;
public PICC_RESTORE: any;
public PICC_TRANSFER: any;
public PICC_UL_WRITE: any;
public PICC_SElECTTAG: any;
public CommandReg: any;
public ComlEnReg: any;
public DivlEnReg: any;
public ComIrqReg: any;
public DivIrqReg: any;
public ErrorReg: any;
public Status1Reg: any;
public Status2Reg: any;
public FIFODataReg: any;
public FIFOLevelReg: any;
public WaterLevelReg: any;
public ControlReg: any;
public BitFramingReg: any;
public CollReg: any;
public ModeReg: any;
public TxModeReg: any;
public RxModeReg: any;
public TxControlReg: any;
public TxASKReg: any;
public TxSelReg: any;
public RxSelReg: any;
public RxThresholdReg: any;
public DemodReg: any;
public Reserved1Ah: any;
public Reserved1Bh: any;
public MfTxReg: any;
public MfRxReg: any;
public Reserved1Eh: any;
public SerialSpeedReg: any;
public CRCResultRegMSB: any;
public CRCResultRegLSB: any;
public ModWidthReg: any;
public RFCfgReg: any;
public GsNReg: any;
public CWGsPReg: any;
public ModGsPReg: any;
public TModeReg: any;
public TPrescalerReg: any;
public TReloadRegHi: any;
public TReloadRegLo: any;
public TCounterValRegHi: any;
public TCounterValRegLo: any;
public TestSel1Reg: any;
public TestSel2Reg: any;
public TestPinEnReg: any;
public TestPinValueReg: any;
public TestBusReg: any;
public AutoTestReg: any;
public VersionReg: any;
public AnalogTestReg: any;
public TestDAC1Reg: any;
public TestDAC2Reg: any;
public TestADCReg: any;
public keys: string[];
public requiredKeys: string[];
public obniz!: Obniz;
public params: any;
public rst: any;
public cs: any;
public spi: any;
constructor() {
// PCD commands. Described in chapter 10 of the datasheet.
// PCD(Proximity Coupling Device): NXP MFRC522 Contactless Reader IC.
this.PCD_Idle = 0x00; // no action, cancels current command execution.
this.PCD_Mem = 0x01; // stores 25 bytes into the internal buffer.
this.PCD_GenerateRandomID = 0x02; // generates a 10-byte random ID number.
this.PCD_CalcCRC = 0x03; // activates the CRC coprocessor or performs a self-test.
this.PCD_Transmit = 0x04; // transmits data from the FIFO buffer.
this.PCD_NoCmdChange = 0x07; // no command change, can be used to modify the CommandReg register bits without affecting the command, for example, the PowerDown bit.
this.PCD_Receive = 0x08; // activates the receiver circuits.
this.PCD_Transceive = 0x0c; // transmits data from FIFO buffer to antenna and automatically activates the receiver after transmission.
// this.PCD_Reserved0Dh = 0x0D;
this.PCD_MFAuthent = 0x0e; // performs the MIFARE standard authentication as a reader.
this.PCD_SoftReset = 0x0f; // resets the MFRC522.
// MFRC522 RxGain[2:0] masks, defines the receiver's signal voltage gain factor (on the PCD).
// Described in 9.3.3.6 / table 98 of the datasheet at http://www.nxp.com/documents/data_sheet/MFRC522.pdf
this.RxGain_18dB = 0x00 << 4; // 000b - 18 dB, minimum.
this.RxGain_23dB = 0x01 << 4; // 001b - 23 dB.
this.RxGain_18dB_2 = 0x02 << 4; // 010b - 18 dB, it seems 010b is a duplicate for 000b.
this.RxGain_23dB_2 = 0x03 << 4; // 011b - 23 dB, it seems 011b is a duplicate for 001b.
this.RxGain_33dB = 0x04 << 4; // 100b - 33 dB, average, and typical default.
this.RxGain_38dB = 0x05 << 4; // 101b - 38 dB.
this.RxGain_43dB = 0x06 << 4; // 110b - 43 dB.
this.RxGain_48dB = 0x07 << 4; // 111b - 48 dB, maximum.
this.RxGain_min = 0x00 << 4; // 000b - 18 dB, minimum, convenience for RxGain_18dB.
this.RxGain_avg = 0x04 << 4; // 100b - 33 dB, average, convenience for RxGain_33dB.
this.RxGain_max = 0x07 << 4; // 111b - 48 dB, maximum, convenience for RxGain_48dB.
// The PICC commands used by the PCD to manage communication with several PICCs (ISO 14443-3, Type A, section 6.4).
this.PICC_REQA = 0x26; // REQuest command, Type A. Invites PICCs in state IDLE to go to READY and prepare for anticollision or selection. 7 bit frame.
this.PICC_WUPA = 0x52; // Wake-UP command, Type A. Invites PICCs in state IDLE and HALT to go to READY(*) and prepare for anticollision or selection. 7 bit frame.
this.PICC_CT = 0x88; // Cascade Tag. Not really a command, but used during anti collision.
this.PICC_SEL_CL1 = 0x93; // Anti collision/Select, Cascade Level 1.
this.PICC_SEL_CL2 = 0x95; // Anti collision/Select, Cascade Level 2.
this.PICC_SEL_CL3 = 0x97; // Anti collision/Select, Cascade Level 3.
this.PICC_HLTA = 0x50; // HaLT command, Type A. Instructs an ACTIVE PICC to go to state HALT.
this.PICC_RATS = 0xe0; // Request command for Answer To Reset.
// The commands used for MIFARE Classic (from http://www.mouser.com/ds/2/302/MF1S503x-89574.pdf, Section 9)
// Use PCD_MFAuthent to authenticate access to a sector, then use these commands to read/write/modify the blocks on the sector.
// The read/write commands can also be used for MIFARE Ultralight.
this.PICC_AUTH_KEYA = 0x60; // Perform authentication with Key A.
this.PICC_AUTH_KEYB = 0x61; // Perform authentication with Key B.
this.PICC_READ = 0x30; // Reads one 16 byte block from the authenticated sector of the PICC. Also used for MIFARE Ultralight.
this.PICC_WRITE = 0xa0; // Writes one 16 byte block to the authenticated sector of the PICC. Called "COMPATIBILITY WRITE" for MIFARE Ultralight.
this.PICC_DECREMENT = 0xc0; // Decrements the contents of a block and stores the result in the internal data register.
this.PICC_INCREMENT = 0xc1; // Increments the contents of a block and stores the result in the internal data register.
this.PICC_RESTORE = 0xc2; // Reads the contents of a block into the internal data register.
this.PICC_TRANSFER = 0xb0; // Writes the contents of the internal data register to a block.
// The commands used for MIFARE Ultralight (from http://www.nxp.com/documents/data_sheet/MF0ICU1.pdf, Section 8.6)
// The PICC_CMD_MF_READ and PICC_CMD_MF_WRITE can also be used for MIFARE Ultralight.
this.PICC_UL_WRITE = 0xa2; // Writes one 4 byte page to the PICC.
this.PICC_SElECTTAG = 0x93;
// Page 0: Command and status
// this.Reserved00h = 0x00;
this.CommandReg = 0x01;
this.ComlEnReg = 0x02;
this.DivlEnReg = 0x03;
this.ComIrqReg = 0x04;
this.DivIrqReg = 0x05;
this.ErrorReg = 0x06;
this.Status1Reg = 0x07;
this.Status2Reg = 0x08;
this.FIFODataReg = 0x09;
this.FIFOLevelReg = 0x0a;
this.WaterLevelReg = 0x0b;
this.ControlReg = 0x0c;
this.BitFramingReg = 0x0d;
this.CollReg = 0x0e;
// this.Reserved0Fh = 0x0F;
// Page 1: Command
// this.Reserved10h = 0x10;
this.ModeReg = 0x11;
this.TxModeReg = 0x12;
this.RxModeReg = 0x13;
this.TxControlReg = 0x14;
this.TxASKReg = 0x15;
this.TxSelReg = 0x16;
this.RxSelReg = 0x17;
this.RxThresholdReg = 0x18;
this.DemodReg = 0x19;
this.Reserved1Ah = 0x1a;
this.Reserved1Bh = 0x1b;
this.MfTxReg = 0x1c;
this.MfRxReg = 0x1d;
this.Reserved1Eh = 0x1e;
this.SerialSpeedReg = 0x1f;
// Page 2: Configuration
// this.Reserved20h = 0x20;
this.CRCResultRegMSB = 0x21;
this.CRCResultRegLSB = 0x22;
// this.Reserved23h = 0x23;
this.ModWidthReg = 0x24;
// this.Reserved25h = 0x25;
this.RFCfgReg = 0x26;
this.GsNReg = 0x27;
this.CWGsPReg = 0x28;
this.ModGsPReg = 0x29;
this.TModeReg = 0x2a;
this.TPrescalerReg = 0x2b;
this.TReloadRegHi = 0x2c;
this.TReloadRegLo = 0x2d;
this.TCounterValRegHi = 0x2e;
this.TCounterValRegLo = 0x2f;
// Page 3: Test register
// this.Reserved30h = 0x30;
this.TestSel1Reg = 0x31;
this.TestSel2Reg = 0x32;
this.TestPinEnReg = 0x33;
this.TestPinValueReg = 0x34;
this.TestBusReg = 0x35;
this.AutoTestReg = 0x36;
this.VersionReg = 0x37;
this.AnalogTestReg = 0x38;
this.TestDAC1Reg = 0x39;
this.TestDAC2Reg = 0x3a;
this.TestADCReg = 0x3b;
// this.Reserved3Ch = 0x3C;
// this.Reserved3Dh = 0x3D;
// this.Reserved3Eh = 0x3E;
// this.Reserved3Fh = 0x3F;
// required pin of obniz
this.keys = [
'cs',
'clk',
'mosi',
'miso',
'rst',
'vcc',
'gnd',
'spi',
'spi_frequency',
];
this.requiredKeys = ['cs', 'mosi', 'miso', 'rst'];
}
public wired(obniz: Obniz) {
this.obniz = obniz;
// IO pin settings
this.obniz.setVccGnd(this.params.vcc, this.params.gnd, '5v');
this.rst = obniz.getIO(this.params.rst);
// SPI settings
this.cs = obniz.getIO(this.params.cs);
this.cs.output(true);
this.params.mode = 'master';
this.params.drive = '3v';
this.params.pull = '3v';
this.params.frequency = this.params.spi_frequency || 5 * 1000 * 1000;
this.spi = this.obniz.getSpiWithConfig(this.params);
}
/**
* @deprecated
*/
public init() {
return this.initWait();
}
public async initWait() {
// Initializes the MFRC522 chip
// Hardware and Software reset
this.rst.output(false);
await this.obniz.wait(50); // 8.8.2 says the oscillator start-up time is the start up time of the crystal + 37,74us: 50ms.
this.rst.output(true);
this.writeRegister(this.CommandReg, this.PCD_SoftReset);
// Timer setup: When communicating with a PICC we need a timeout if something goes wrong.
// f_timer = 13.56 MHz / (2*TPreScaler+1) where TPreScaler = [TPrescaler_Hi:TPrescaler_Lo].
this.writeRegister(this.TModeReg, 0x80); // TAuto=1; timer starts automatically at the end of the transmission in all communication modes at all speeds
this.writeRegister(this.TPrescalerReg, 0xa9); // TPreScaler = TModeReg[3..0]: TPrescalerReg, ie 0x0A9 = 169 => f_timer=40kHz, ie a timer period of 25us.
this.writeRegister(this.TReloadRegHi, 0x03);
this.writeRegister(this.TReloadRegLo, 0xe8); // Reload timer with 0x3E8 = 1000, ie. 25ms before timeout
this.writeRegister(this.TxASKReg, 0x40); // Default 0x00. Force a 100 % ASK modulation independent of the ModGsPReg register setting
this.writeRegister(this.ModeReg, 0x3d); // Default 0x3F. Set the preset value for the CRC coprocessor for the CalcCRC command to 0x6363 (6.2.4)
await this.antennaOnWait(); // Enable the antenna driver pins TX1 and TX2 (they were disabled by the reset)
}
public writeRegister(addr: number, val: any) {
let data: any;
if (val instanceof Array) {
// If val is Array
data = [(addr << 1) & 0x7e].concat(val);
} else {
data = [(addr << 1) & 0x7e, val];
}
this.cs.output(false);
this.spi.write(data);
this.cs.output(true);
}
/**
* @deprecated
* @param addr
*/
public readRegister(addr: number) {
return this.readRegisterWait(addr);
}
public async readRegisterWait(addr: number) {
const data = [((addr << 1) & 0x7e) | 0x80, 0];
this.cs.output(false);
const response = await this.spi.writeWait(data);
this.cs.output(true);
return response[1];
}
/**
* @deprecated
* @param addr
* @param n
*/
public readRegister_nByte(addr: any, n?: any): Promise<number[]> {
return this.readRegister_nByteWait(addr, n);
}
public async readRegister_nByteWait(addr: any, n?: any): Promise<number[]> {
const dataArray: any = [];
if (addr instanceof Array) {
// Multiple addresses(If addr is Array)
for (let i = 0; i < addr.length; i++) {
dataArray.push(((addr[i] << 1) & 0x7e) | 0x80);
}
} else {
// Single address & read n times
for (let i = 0; i < n; i++) {
dataArray.push(((addr << 1) & 0x7e) | 0x80);
}
}
dataArray.push(0); // End reading
this.cs.output(false);
const values = await this.spi.writeWait(dataArray);
this.cs.output(true);
values.shift();
return values;
}
/**
* @deprecated
* @param reg
* @param mask
*/
public setRegisterBitMask(reg: any, mask: any) {
return this.setRegisterBitMaskWait(reg, mask);
}
public async setRegisterBitMaskWait(reg: any, mask: any) {
const response: any = await this.readRegisterWait(reg);
this.writeRegister(reg, response | mask);
}
/**
* @deprecated
*
* @param reg
* @param mask
*/
public clearRegisterBitMask(reg: any, mask: any) {
return this.clearRegisterBitMaskWait(reg, mask);
}
public async clearRegisterBitMaskWait(reg: any, mask: any) {
const response: any = await this.readRegisterWait(reg);
this.writeRegister(reg, response & ~mask);
}
/**
* @deprecated
*/
public antennaOn() {
return this.antennaOnWait();
}
public async antennaOnWait() {
// Turns the antenna on by enabling pins TX1 and TX2
const response: any = await this.readRegisterWait(this.TxControlReg);
if ((response & 0x03) !== 0x03) {
// If TX1 and TX2 down
await this.setRegisterBitMaskWait(this.TxControlReg, response | 0x03);
}
}
/**
* @deprecated
*/
public antennaOff() {
return this.antennaOffWait();
}
public async antennaOffWait() {
// Turns the antenna off by disabling pins TX1 and TX2
await this.clearRegisterBitMaskWait(this.TxControlReg, 0x03);
}
/**
* @deprecated
* @param command
* @param bitsToSend
*/
public toCard(
command: any,
bitsToSend: any
): Promise<{
status: boolean;
data: any;
bitSize: number;
}> {
return this.toCardWait(command, bitsToSend);
}
// RC522 and ISO14443 card communication
public async toCardWait(
command: any,
bitsToSend: any
): Promise<{
status: boolean;
data: any;
bitSize: number;
}> {
let data: any = [];
let bitSize: any = 0;
let status: any = ERROR;
let irqEn: any = 0x00;
let waitIRq: any = 0x00;
if (command === this.PCD_MFAuthent) {
irqEn = 0x12;
waitIRq = 0x10;
}
if (command === this.PCD_Transceive) {
irqEn = 0x77;
waitIRq = 0x30;
}
this.writeRegister(this.CommandReg, this.PCD_Idle); // Stop any active command
this.writeRegister(this.ComlEnReg, irqEn | 0x80); // Interrupt request is enabled
this.writeRegister(this.ComIrqReg, 0x7f); // Clear all seven interrupt request bits
this.writeRegister(this.FIFOLevelReg, 0x80); // FlushBuffer = 1, FIFO initialization
this.writeRegister(this.FIFODataReg, bitsToSend); // Write sendData to the FIFO
this.writeRegister(this.CommandReg, command); // Execute the command
if (command === this.PCD_Transceive) {
await this.setRegisterBitMaskWait(this.BitFramingReg, 0x80); // StartSend=1, transmission of data starts
}
let TryingTimes: any = 10;
let n: any = 0;
do {
// Wait for the received data complete
n = await this.readRegisterWait(this.ComIrqReg);
TryingTimes--;
} while (TryingTimes !== 0 && !(n & 0x01) && !(n & waitIRq)); // !(Timer interrupt - nothing received before timeout) & !(One of the interrupts that signal success has been set)
// await this.clearRegisterBitMaskWait(this.BitFramingReg, 0x80); //Reset with resetAndInit()
const response: any = await this.readRegister_nByteWait([
this.ErrorReg,
this.FIFOLevelReg,
this.ControlReg,
]);
if (TryingTimes !== 0) {
if ((response[0] & 0x1b) === 0x00) {
// BufferOvfl CollErr ParityErr ProtocolErr
status = n & irqEn & 0x01 ? ERROR : OK;
if (command === this.PCD_Transceive) {
n = response[1]; // Number of bytes in the FIFO
const lastBits: any = response[2] & 0x07; // RxLastBits[2:0] indicates the number of valid bits in the last received byte. If this value is 000b, the whole byte is valid.
if (lastBits) {
bitSize = (n - 1) * 8 + lastBits;
} else {
bitSize = n * 8;
}
if (n === 0) {
n = 1;
}
if (n > 16) {
n = 16;
} // Restrict until 16bytes
data = await this.readRegister_nByteWait(this.FIFODataReg, n); // Get received data from FIFO buffer
}
} else {
status = ERROR;
}
}
return { status, data, bitSize };
}
public async findCardWait(): Promise<{
uid: any;
PICC_Type: string;
}> {
await this.initWait();
await this.searchTagWait();
const uid: any = await this.getUidWait();
const PICC_Type: any = await this.identifyCardTypeWait(uid);
return { uid, PICC_Type };
}
public async searchTagWait() {
this.writeRegister(this.BitFramingReg, 0x07);
const tagType: any = [this.PICC_REQA];
const response: any = await this.toCardWait(this.PCD_Transceive, tagType);
if (response.bitSize !== 0x10) {
throw new Error('card_search_ERROR');
}
}
public async getUidWait(): Promise<any> {
this.writeRegister(this.BitFramingReg, 0x00);
let uid: any = [this.PICC_SEL_CL1, 0x20];
const response: any = await this.toCardWait(this.PCD_Transceive, uid);
if (!response.status) {
throw new Error('uid_scan_ERROR');
}
const uidCheck: any =
response.data[0] ^ response.data[1] ^ response.data[2] ^ response.data[3];
if (uidCheck !== response.data[4]) {
throw new Error('uid_check_ERROR');
}
uid = response.data;
// (uid).pop();
return uid;
}
public async calculateCRCWait(data: any) {
this.writeRegister(this.CommandReg, this.PCD_Idle); // Stop any active command
this.writeRegister(this.DivIrqReg, 0x04); // Clear the CRCIRq interrupt request bit
this.writeRegister(this.FIFOLevelReg, 0x80); // FlushBuffer = 1, FIFO initialization
this.writeRegister(this.FIFODataReg, data); // Write data to the FIFO
this.writeRegister(this.CommandReg, this.PCD_CalcCRC); // Start the calculation
let i: any = 0xff;
let n: any;
// Wait for the CRC calculation to complete
do {
n = await this.readRegisterWait(this.DivIrqReg);
i--;
} while (i !== 0 && !(n & 0x04)); // CRCIrq = 1 (Calculation done)
// CRC calculation result
return await this.readRegister_nByteWait([
this.CRCResultRegLSB,
this.CRCResultRegMSB,
]);
}
public async identifySoftwareWait() {
let version: any = await this.readRegisterWait(this.VersionReg);
switch (version) {
case 0x88:
version = '(clone)';
break;
case 0x90:
version = 'v0.0';
break;
case 0x91:
version = 'v1.0';
break;
case 0x92:
version = 'v2.0';
break;
case 0x12:
version = 'counterfeit chip';
break;
default:
version = '(unknown)';
}
// When 0x00 or 0xFF is returned, communication probably failed
if (version === 0x00 || version === 0xff) {
throw new Error('software_version_ERROR');
}
return version;
}
public async identifyCardTypeWait(uid: any) {
// Identify type of the scanned card
let buffer: any = [this.PICC_SElECTTAG, 0x70].concat(uid);
buffer = buffer.concat(await this.calculateCRCWait(buffer));
const response: any = await this.toCardWait(this.PCD_Transceive, buffer);
let PICC_Type: any;
if (response.status && response.bitSize === 0x18) {
PICC_Type = response.data[0];
}
switch (PICC_Type) {
case 0x04:
PICC_Type = 'SAK indicates UID is not complete.';
break; // UID not complete
case 0x09:
PICC_Type = 'MIFARE Mini, 320 bytes';
break;
case 0x08:
PICC_Type = 'MIFARE 1KB';
break;
case 0x18:
PICC_Type = 'MIFARE 4KB';
break;
case 0x00:
PICC_Type = 'MIFARE Ultralight or Ultralight C';
break;
case 0x11:
PICC_Type = 'MIFARE Plus';
break;
case 0x01:
PICC_Type = 'MIFARE TNP3XXX';
break;
case 0x20:
PICC_Type = 'PICC compliant with ISO/IEC 14443-4';
break;
case 0x40:
PICC_Type = 'PICC compliant with ISO/IEC 18092 (NFC)';
break;
default:
throw new Error('PICC_type_ERROR');
}
return PICC_Type;
}
public async readSectorDataWait(Sector: any, uid: any) {
await this.authenticateSectorWait(Sector, uid);
return await this.getSectorDataWait(Sector);
}
public async readBlockDataWait(Block: any, uid: any) {
await this.authenticateBlockWait(Block, uid);
return await this.getBlockDataWait(Block);
}
public async authenticateSectorWait(Sector: any, uid: any) {
/* Password authentication mode (A or B)
* PICC_AUTH_KEYA = Verify the A key are the first 6 bit of 4th Block of each sector
* PICC_AUTH_KEYB = Verify the B key are the last 6 bit of 4th Block of each sector
*/
const KEY_A: any = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
// const KEY_B = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
const Block: any = Sector * 4;
let buffer: any = [this.PICC_AUTH_KEYA, Block].concat(KEY_A); // Append key = 6 bit of 0xFF
uid = uid.slice(0, 4); // Append the first 4 bit of the UID
buffer = buffer.concat(uid); // 12byte
// Start authentication itself
await this.toCardWait(this.PCD_MFAuthent, buffer);
if (!((await this.readRegisterWait(this.Status2Reg)) & 0x08)) {
throw new Error('password_authentication_ERROR');
}
}
public async authenticateBlockWait(Block: any, uid: any) {
/* Password authentication mode (A or B)
* PICC_AUTH_KEYA = Verify the A key (the first 6 bit of 3th Block fo each Sector)
* PICC_AUTH_KEYB = Verify the B key (the last 6 bit of 3th Block fo each Sector)
*/
const KEY_A: any = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
// const KEY_B = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
let buffer: any = [this.PICC_AUTH_KEYA, Block].concat(KEY_A); // Append key = 6 bit of 0xFF
uid = uid.slice(0, 4); // Append the first 4 bit of the UID
buffer = buffer.concat(uid); // 12byte
// Start authentication itself
await this.toCardWait(this.PCD_MFAuthent, buffer);
if (!((await this.readRegisterWait(this.Status2Reg)) & 0x08)) {
throw new Error('password_authentication_ERROR');
}
}
public async readAgainWait() {
// If you finish reading and want to read again, this can use instead of initWait()
await this.clearRegisterBitMaskWait(this.Status2Reg, 0x08);
}
public async getSectorDataWait(address: any) {
const response: any = [];
const blockData: any = [];
for (let i = 0; i < 4; i++) {
let request: any = [this.PICC_READ, address * 4 + i];
request = request.concat(await this.calculateCRCWait(request));
response[i] = await this.toCardWait(this.PCD_Transceive, request);
if (!response[i].status) {
throw new Error('data_read_ERROR');
}
blockData[i] = response[i].data;
}
return blockData;
}
public async getBlockDataWait(
address: any
): Promise<{
status: boolean;
data: any;
bitSize: number;
}> {
let request: any = [this.PICC_READ, address];
request = request.concat(await this.calculateCRCWait(request));
const response: any = await this.toCardWait(this.PCD_Transceive, request);
if (!response.status) {
throw new Error('data_read_ERROR');
}
return response.data;
}
public async appendCRCtoBufferAndSendToCardWait(
buffer: any
): Promise<{
status: boolean;
data: any;
bitSize: number;
}> {
buffer = buffer.concat(await this.calculateCRCWait(buffer));
const response: any = await this.toCardWait(this.PCD_Transceive, buffer);
if (
!response.status ||
response.bitSize !== 4 ||
(response.data[0] & 0x0f) !== 0x0a
) {
response.status = ERROR;
}
return response;
}
public async writeBlockDataWait(
Block: any,
sixteenBytes: any
): Promise<void> {
if (Block === 0 || Block % 4 === 3) {
throw new Error('deny_Write');
}
const buffer: any = [this.PICC_WRITE, Block];
let response: any = await this.appendCRCtoBufferAndSendToCardWait(buffer);
if (response.status) {
response = await this.appendCRCtoBufferAndSendToCardWait(sixteenBytes);
} else {
throw new Error('data_write_ERROR');
}
}
} | the_stack |
* @packageDocumentation
* @module core
*/
import '../data/class';
import { EDITOR, MINIGAME, JSB, RUNTIME_BASED } from 'internal:constants';
import { screenAdapter } from 'pal/screen-adapter';
import { systemInfo } from 'pal/system-info';
import { EventTarget } from '../event';
import { Rect, Size, Vec2 } from '../math';
import visibleRect from './visible-rect';
import { legacyCC } from '../global-exports';
import { logID, errorID } from './debug';
import { screen } from './screen';
import { macro } from './macro';
import { Orientation } from '../../../pal/screen-adapter/enum-type';
import { game } from '../game';
/**
* @en View represents the game window.<br/>
* It's main task include: <br/>
* - Apply the design resolution policy to the UI Canvas<br/>
* - Provide interaction with the window, like resize event on web, retina display support, etc...<br/>
* - Manage the scale and translation of canvas related to the frame on Web<br/>
* <br/>
* With {{view}} as its singleton initialized by the engine, you don't need to call any constructor or create functions,<br/>
* the standard way to use it is by calling:<br/>
* - view.methodName(); <br/>
* @zh View 代表游戏窗口视图,它的核心功能包括:
* - 对所有 UI Canvas 进行设计分辨率适配。
* - 提供窗口视图的交互,比如监听 resize 事件,控制 retina 屏幕适配,等等。
* - 控制 Canvas 节点相对于外层 DOM 节点的缩放和偏移。
* 引擎会自动初始化它的单例对象 {{view}},所以你不需要实例化任何 View,只需要直接使用 `view.methodName();`
*/
const localWinSize = new Size();
const orientationMap = {
[macro.ORIENTATION_AUTO]: Orientation.AUTO,
[macro.ORIENTATION_LANDSCAPE]: Orientation.LANDSCAPE,
[macro.ORIENTATION_PORTRAIT]: Orientation.PORTRAIT,
};
export class View extends EventTarget {
public static instance: View;
public _designResolutionSize: Size;
private _scaleX: number;
private _scaleY: number;
private _viewportRect: Rect;
private _visibleRect: Rect;
private _autoFullScreen: boolean;
private _retinaEnabled: boolean;
private _resizeCallback: (() => void) | null;
private _resolutionPolicy: ResolutionPolicy;
private _rpExactFit: ResolutionPolicy;
private _rpShowAll: ResolutionPolicy;
private _rpNoBorder: ResolutionPolicy;
private _rpFixedHeight: ResolutionPolicy;
private _rpFixedWidth: ResolutionPolicy;
constructor () {
super();
const _strategyer = ContainerStrategy;
const _strategy = ContentStrategy;
// resolution size, it is the size appropriate for the app resources.
this._designResolutionSize = new Size(0, 0);
this._scaleX = 1;
this._scaleY = 1;
// Viewport is the container's rect related to content's coordinates in pixel
this._viewportRect = new Rect(0, 0, 0, 0);
// The visible rect in content's coordinate in point
this._visibleRect = new Rect(0, 0, 0, 0);
// Auto full screen disabled by default
this._autoFullScreen = false;
// Retina disabled by default
this._retinaEnabled = false;
// Custom callback for resize event
this._resizeCallback = null;
// Setup system default resolution policies
this._rpExactFit = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.EXACT_FIT);
this._rpShowAll = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.SHOW_ALL);
this._rpNoBorder = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.NO_BORDER);
this._rpFixedHeight = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_HEIGHT);
this._rpFixedWidth = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_WIDTH);
this._resolutionPolicy = this._rpShowAll;
}
// Call init at the time Game.EVENT_ENGINE_INITED
public init () {
const windowSize = screen.windowSize;
const w = windowSize.width;
const h = windowSize.height;
this._designResolutionSize.width = w;
this._designResolutionSize.height = h;
this._viewportRect.width = w;
this._viewportRect.height = h;
this._visibleRect.width = w;
this._visibleRect.height = h;
localWinSize.width = this._visibleRect.width;
localWinSize.height = this._visibleRect.height;
if (visibleRect) {
visibleRect.init(this._visibleRect);
}
// For now, the engine UI is adapted to resolution size, instead of window size.
screenAdapter.on('window-resize', this._updateAdaptResult, this);
screenAdapter.on('orientation-change', this._updateAdaptResult, this);
}
/**
* @en
* Sets whether resize canvas automatically when browser's size changed.<br/>
* Useful only on web.
* @zh 设置当发现浏览器的尺寸改变时,是否自动调整 canvas 尺寸大小。
* 仅在 Web 模式下有效。
* @param enabled - Whether enable automatic resize with browser's resize event
*/
public resizeWithBrowserSize (enabled: boolean) {
screenAdapter.handleResizeEvent = enabled;
}
/**
* @en
* Sets the callback function for `view`'s resize action,<br/>
* this callback will be invoked before applying resolution policy, <br/>
* so you can do any additional modifications within the callback.<br/>
* Useful only on web.
* @zh 设置 `view` 调整视窗尺寸行为的回调函数,
* 这个回调函数会在应用适配模式之前被调用,
* 因此你可以在这个回调函数内添加任意附加改变,
* 仅在 Web 平台下有效。
* @param callback - The callback function
*/
public setResizeCallback (callback: (()=> void) | null) {
if (typeof callback === 'function' || callback == null) {
this._resizeCallback = callback;
}
}
/**
* @en
* Sets the orientation of the game, it can be landscape, portrait or auto.
* When set it to landscape or portrait, and screen w/h ratio doesn't fit,
* `view` will automatically rotate the game canvas using CSS.
* Note that this function doesn't have any effect in native,
* in native, you need to set the application orientation in native project settings
* @zh 设置游戏屏幕朝向,它能够是横版,竖版或自动。
* 当设置为横版或竖版,并且屏幕的宽高比例不匹配时,
* `view` 会自动用 CSS 旋转游戏场景的 canvas,
* 这个方法不会对 native 部分产生任何影响,对于 native 而言,你需要在应用设置中的设置排版。
* @param orientation - Possible values: macro.ORIENTATION_LANDSCAPE | macro.ORIENTATION_PORTRAIT | macro.ORIENTATION_AUTO
*/
public setOrientation (orientation: number) {
screenAdapter.orientation = orientationMap[orientation];
}
/**
* @en
* Sets whether the engine modify the "viewport" meta in your web page.<br/>
* It's enabled by default, we strongly suggest you not to disable it.<br/>
* And even when it's enabled, you can still set your own "viewport" meta, it won't be overridden<br/>
* Only useful on web
* @zh 设置引擎是否调整 viewport meta 来配合屏幕适配。
* 默认设置为启动,我们强烈建议你不要将它设置为关闭。
* 即使当它启动时,你仍然能够设置你的 viewport meta,它不会被覆盖。
* 仅在 Web 模式下有效
* @param enabled - Enable automatic modification to "viewport" meta
* @deprecated since v3.3
*/
public adjustViewportMeta (enabled: boolean) {
// DO NOTHING
}
/**
* @en
* Retina support is enabled by default for Apple device but disabled for other devices,<br/>
* it takes effect only when you called setDesignResolutionPolicy<br/>
* Only useful on web
* @zh 对于 Apple 这种支持 Retina 显示的设备上默认进行优化而其他类型设备默认不进行优化,
* 它仅会在你调用 setDesignResolutionPolicy 方法时有影响。
* 仅在 Web 模式下有效。
* @param enabled - Enable or disable retina display
*
* @deprecated since v3.4.0
*/
public enableRetina (enabled: boolean) {
this._retinaEnabled = !!enabled;
}
/**
* @en
* Check whether retina display is enabled.<br/>
* Only useful on web
* @zh 检查是否对 Retina 显示设备进行优化。
* 仅在 Web 模式下有效。
*
* @deprecated since v3.4.0
*/
public isRetinaEnabled (): boolean {
return this._retinaEnabled;
}
/**
* @en
* If enabled, the application will try automatically to enter full screen mode on mobile devices<br/>
* You can pass true as parameter to enable it and disable it by passing false.<br/>
* Only useful on web
* @zh 启动时,移动端游戏会在移动端自动尝试进入全屏模式。
* 你能够传入 true 为参数去启动它,用 false 参数来关闭它。
* @param enabled - Enable or disable auto full screen on mobile devices
*
* @deprecated since v3.3, please use screen.requestFullScreen() instead.
*/
public enableAutoFullScreen (enabled: boolean) {
if (enabled === this._autoFullScreen) {
return;
}
this._autoFullScreen = enabled;
if (enabled) {
screen.requestFullScreen().catch((e) => {});
}
}
/**
* @en
* Check whether auto full screen is enabled.<br/>
* Only useful on web
* @zh 检查自动进入全屏模式是否启动。
* 仅在 Web 模式下有效。
* @return Auto full screen enabled or not
*
* @deprecated since v3.3
*/
public isAutoFullScreenEnabled (): boolean {
return this._autoFullScreen;
}
/**
* @en Set the canvas size in CSS pixels on Web platform.
* This method is not supported on other platforms.
* @zh Web 平台下,可以以 CSS 像素尺寸来设置 canvas 尺寸。
* 这个方法并不支持其他平台。
* @private
* @param {Number} width
* @param {Number} height
*
* @deprecated since v3.4.0, setting size in CSS pixels is not recommended, please use screen.windowSize instead.
*/
public setCanvasSize (width: number, height: number) {
// set resolution scale to 1;
screen.resolutionScale = 1;
// set window size
const dpr = screenAdapter.devicePixelRatio;
const windowSize = new Size(width * dpr, height * dpr);
screen.windowSize = windowSize;
}
/**
* @en
* Returns the canvas size of the view.<br/>
* On native platforms, it returns the screen size since the view is a fullscreen view.<br/>
* On web, it returns the size of the canvas element.
* @zh 返回视图中 canvas 的尺寸。
* 在 native 平台下,它返回全屏视图下屏幕的尺寸。
* 在 Web 平台下,它返回 canvas 元素尺寸。
*
* @deprecated since v3.4.0, please use screen.windowSize instead.
*/
public getCanvasSize (): Size {
return screen.windowSize;
}
/**
* @en
* Returns the frame size of the view in CSS pixels.<br/>
* On native platforms, it returns the screen size since the view is a fullscreen view.<br/>
* On web, it returns the size of the canvas's outer DOM element.
* @zh 以 CSS 像素尺寸返回视图中边框尺寸。
* 在 native 平台下,它返回全屏视图下屏幕的尺寸。
* 在 web 平台下,它返回 canvas 元素的外层 DOM 元素尺寸。
*
* @deprecated since v3.4.0, getting size in CSS pixels is not recommended, please use screen.windowSize instead.
*/
public getFrameSize (): Size {
const dpr = screenAdapter.devicePixelRatio;
const sizeInCssPixels = screen.windowSize;
sizeInCssPixels.width /= dpr;
sizeInCssPixels.height /= dpr;
return sizeInCssPixels;
}
/**
* @en Setting the frame size of the view in CSS pixels.
* On native, it sets the frame size of view.<br/>
* On web, it sets the size of the canvas's outer DOM element.
* @zh 以 CSS 像素尺寸设置视图中边框尺寸。
* 在 native 平台下,设置视图框架尺寸。
* 在 web 平台下,设置 canvas 外层 DOM 元素尺寸。
* @param {Number} width
* @param {Number} height
*
* @deprecated since v3.4.0, setting size in CSS pixels is not recommended, please use screen.windowSize instead.
*/
public setFrameSize (width: number, height: number) {
const dpr = screenAdapter.devicePixelRatio;
screen.windowSize = new Size(width * dpr, height * dpr);
}
/**
* @en Returns the visible area size of the view port.
* @zh 返回视图窗口可见区域尺寸。
*/
public getVisibleSize (): Size {
return new Size(this._visibleRect.width, this._visibleRect.height);
}
/**
* @en Returns the visible area size of the view port.
* @zh 返回视图窗口可见区域像素尺寸。
*/
public getVisibleSizeInPixel (): Size {
return new Size(this._visibleRect.width * this._scaleX,
this._visibleRect.height * this._scaleY);
}
/**
* @en Returns the visible origin of the view port.
* @zh 返回视图窗口可见区域原点。
*/
public getVisibleOrigin (): Vec2 {
return new Vec2(this._visibleRect.x, this._visibleRect.y);
}
/**
* @en Returns the visible origin of the view port.
* @zh 返回视图窗口可见区域像素原点。
*/
public getVisibleOriginInPixel (): Vec2 {
return new Vec2(this._visibleRect.x * this._scaleX,
this._visibleRect.y * this._scaleY);
}
/**
* @en Returns the current resolution policy
* @zh 返回当前分辨率方案
* @see {{ResolutionPolicy}}
*/
public getResolutionPolicy (): ResolutionPolicy {
return this._resolutionPolicy;
}
/**
* @en Sets the current resolution policy
* @zh 设置当前分辨率模式
* @see {{ResolutionPolicy}}
*/
public setResolutionPolicy (resolutionPolicy: ResolutionPolicy|number) {
if (resolutionPolicy instanceof ResolutionPolicy) {
this._resolutionPolicy = resolutionPolicy;
} else {
// Ensure compatibility with JSB
const _locPolicy = ResolutionPolicy;
if (resolutionPolicy === _locPolicy.EXACT_FIT) {
this._resolutionPolicy = this._rpExactFit;
}
if (resolutionPolicy === _locPolicy.SHOW_ALL) {
this._resolutionPolicy = this._rpShowAll;
}
if (resolutionPolicy === _locPolicy.NO_BORDER) {
this._resolutionPolicy = this._rpNoBorder;
}
if (resolutionPolicy === _locPolicy.FIXED_HEIGHT) {
this._resolutionPolicy = this._rpFixedHeight;
}
if (resolutionPolicy === _locPolicy.FIXED_WIDTH) {
this._resolutionPolicy = this._rpFixedWidth;
}
}
}
/**
* @en Sets the resolution policy with designed view size in points.<br/>
* The resolution policy include: <br/>
* [1] ResolutionExactFit Fill screen by stretch-to-fit: if the design resolution ratio of width to height is different from the screen resolution ratio, your game view will be stretched.<br/>
* [2] ResolutionNoBorder Full screen without black border: if the design resolution ratio of width to height is different from the screen resolution ratio, two areas of your game view will be cut.<br/>
* [3] ResolutionShowAll Full screen with black border: if the design resolution ratio of width to height is different from the screen resolution ratio, two black borders will be shown.<br/>
* [4] ResolutionFixedHeight Scale the content's height to screen's height and proportionally scale its width<br/>
* [5] ResolutionFixedWidth Scale the content's width to screen's width and proportionally scale its height<br/>
* [ResolutionPolicy] [Web only feature] Custom resolution policy, constructed by ResolutionPolicy<br/>
* @zh 通过设置设计分辨率和匹配模式来进行游戏画面的屏幕适配。
* @param width Design resolution width.
* @param height Design resolution height.
* @param resolutionPolicy The resolution policy desired
*/
public setDesignResolutionSize (width: number, height: number, resolutionPolicy: ResolutionPolicy|number) {
// Defensive code
if (!(width > 0 && height > 0)) {
errorID(2200);
return;
}
this.setResolutionPolicy(resolutionPolicy);
const policy = this._resolutionPolicy;
if (policy) {
policy.preApply(this);
}
this._designResolutionSize.width = width;
this._designResolutionSize.height = height;
const result = policy.apply(this, this._designResolutionSize);
if (result.scale && result.scale.length === 2) {
this._scaleX = result.scale[0];
this._scaleY = result.scale[1];
}
if (result.viewport) {
const vp = this._viewportRect;
const vb = this._visibleRect;
const rv = result.viewport;
vp.x = rv.x;
vp.y = rv.y;
vp.width = rv.width;
vp.height = rv.height;
vb.x = 0;
vb.y = 0;
vb.width = rv.width / this._scaleX;
vb.height = rv.height / this._scaleY;
}
policy.postApply(this);
localWinSize.width = this._visibleRect.width;
localWinSize.height = this._visibleRect.height;
if (visibleRect) {
visibleRect.init(this._visibleRect);
}
this.emit('design-resolution-changed');
}
/**
* @en Returns the designed size for the view.
* @zh 返回视图的设计分辨率。
*/
public getDesignResolutionSize (): Size {
return new Size(this._designResolutionSize.width, this._designResolutionSize.height);
}
/**
* @en Sets the container to desired pixel resolution and fit the game content to it.
* This function is very useful for adaptation in mobile browsers.
* In some HD android devices, the resolution is very high, but its browser performance may not be very good.
* In this case, enabling retina display is very costy and not suggested, and if retina is disabled, the image may be blurry.
* But this API can be helpful to set a desired pixel resolution which is in between.
* This API will do the following:
* 1. Set viewport's width to the desired width in pixel
* 2. Set body width to the exact pixel resolution
* 3. The resolution policy will be reset with designed view size in points.
* @zh 设置容器(container)需要的像素分辨率并且适配相应分辨率的游戏内容。
* @param width Design resolution width.
* @param height Design resolution height.
* @param resolutionPolicy The resolution policy desired
*/
public setRealPixelResolution (width: number, height: number, resolutionPolicy: ResolutionPolicy|number) {
if (!JSB && !RUNTIME_BASED && !MINIGAME) {
// Set body width to the exact pixel resolution
document.documentElement.style.width = `${width}px`;
document.body.style.width = `${width}px`;
document.body.style.left = '0px';
document.body.style.top = '0px';
}
// Reset the resolution size and policy
this.setDesignResolutionSize(width, height, resolutionPolicy);
}
/**
* @en Returns the view port rectangle.
* @zh 返回视窗剪裁区域。
*/
public getViewportRect (): Rect {
return this._viewportRect;
}
/**
* @en Returns scale factor of the horizontal direction (X axis).
* @zh 返回横轴的缩放比,这个缩放比是将画布像素分辨率放到设计分辨率的比例。
*/
public getScaleX (): number {
return this._scaleX;
}
/**
* @en Returns scale factor of the vertical direction (Y axis).
* @zh 返回纵轴的缩放比,这个缩放比是将画布像素分辨率缩放到设计分辨率的比例。
*/
public getScaleY (): number {
return this._scaleY;
}
/**
* @en Returns device pixel ratio for retina display.
* @zh 返回设备或浏览器像素比例。
*
* @deprecated since v3.4.0, devicePixelRatio is a concept on web standard, please use screen.resolutionScale instead.
*/
public getDevicePixelRatio (): number {
return screenAdapter.devicePixelRatio;
}
/**
* @en Returns the real location in view for a translation based on a related position
* @zh 将屏幕坐标转换为游戏视图下的坐标。
* @param tx - The X axis translation
* @param ty - The Y axis translation
* @param relatedPos - The related position object including "left", "top", "width", "height" informations
* @param out - The out object to save the conversion result
*
* @deprecated since v3.4.0
*/
public convertToLocationInView (tx: number, ty: number, relatedPos: any, out: Vec2 = new Vec2()): Vec2 {
const x = screenAdapter.devicePixelRatio * (tx - relatedPos.left);
const y = screenAdapter.devicePixelRatio * ((relatedPos.top as number) + (relatedPos.height as number) - ty);
if (screenAdapter.isFrameRotated) {
out.x = screen.windowSize.width - y;
out.y = x;
} else {
out.x = x;
out.y = y;
}
return out;
}
// Convert location in Cocos screen coordinate to location in UI space
private _convertToUISpace (point) {
const viewport = this._viewportRect;
point.x = (point.x - viewport.x) / this._scaleX;
point.y = (point.y - viewport.y) / this._scaleY;
}
private _updateAdaptResult () {
legacyCC.director.root.resize(screen.windowSize.width, screen.windowSize.height);
// Frame size changed, do resize works
const width = this._designResolutionSize.width;
const height = this._designResolutionSize.height;
if (width > 0) {
this.setDesignResolutionSize(width, height, this._resolutionPolicy);
}
this.emit('canvas-resize');
this._resizeCallback?.();
}
}
/**
* !en
* Emit when design resolution changed.
* !zh
* 当设计分辨率改变时发送。
* @event design-resolution-changed
*/
interface AdaptResult {
scale: number[];
viewport?: null | Rect;
}
/**
* ContainerStrategy class is the root strategy class of container's scale strategy,
* it controls the behavior of how to scale the cc.game.container and cc.game.canvas object
*/
class ContainerStrategy {
public static EQUAL_TO_FRAME: any;
public static PROPORTION_TO_FRAME: any;
public name = 'ContainerStrategy';
/**
* @en Manipulation before appling the strategy
* @zh 在应用策略之前的操作
* @param view - The target view
*/
public preApply (_view: View) {
}
/**
* @en Function to apply this strategy
* @zh 策略应用方法
* @param view
* @param designedResolution
*/
public apply (_view: View, designedResolution: Size) {
}
/**
* @en
* Manipulation after applying the strategy
* @zh 策略调用之后的操作
* @param view The target view
*/
public postApply (_view: View) {
}
protected _setupContainer (_view, w, h) {
const locCanvas = game.canvas;
if (locCanvas) {
const windowSize = screen.windowSize;
locCanvas.width = windowSize.width;
locCanvas.height = windowSize.height;
}
}
}
/**
* @en
* Emit when canvas resize.
* @zh
* 当画布大小改变时发送。
* @event canvas-resize
*/
/**
* ContentStrategy class is the root strategy class of content's scale strategy,
* it controls the behavior of how to scale the scene and setup the viewport for the game
*
* @class ContentStrategy
*/
class ContentStrategy {
public static EXACT_FIT: any;
public static SHOW_ALL: any;
public static NO_BORDER: any;
public static FIXED_HEIGHT: any;
public static FIXED_WIDTH: any;
public name = 'ContentStrategy';
private _result: AdaptResult;
constructor () {
this._result = {
scale: [1, 1],
viewport: null,
};
}
/**
* @en Manipulation before applying the strategy
* @zh 策略应用前的操作
* @param view - The target view
*/
public preApply (_view: View) {
}
/**
* @en Function to apply this strategy
* The return value is {scale: [scaleX, scaleY], viewport: {new Rect}},
* The target view can then apply these value to itself, it's preferred not to modify directly its private variables
* @zh 调用策略方法
* @return The result scale and viewport rect
*/
public apply (_view: View, designedResolution: Size): AdaptResult {
return { scale: [1, 1] };
}
/**
* @en Manipulation after applying the strategy
* @zh 策略调用之后的操作
* @param view - The target view
*/
public postApply (_view: View) {
}
public _buildResult (containerW, containerH, contentW, contentH, scaleX, scaleY): AdaptResult {
// Makes content fit better the canvas
if (Math.abs(containerW - contentW) < 2) {
contentW = containerW;
}
if (Math.abs(containerH - contentH) < 2) {
contentH = containerH;
}
const viewport = new Rect(Math.round((containerW - contentW) / 2),
Math.round((containerH - contentH) / 2),
contentW, contentH);
this._result.scale = [scaleX, scaleY];
this._result.viewport = viewport;
return this._result;
}
}
(() => {
// Container scale strategys
/**
* @class EqualToFrame
* @extends ContainerStrategy
*/
class EqualToFrame extends ContainerStrategy {
public name = 'EqualToFrame';
public apply (_view) {
const windowSize = screen.windowSize;
this._setupContainer(_view, windowSize.width, windowSize.height);
}
}
/**
* @class ProportionalToFrame
* @extends ContainerStrategy
*/
class ProportionalToFrame extends ContainerStrategy {
public name = 'ProportionalToFrame';
public apply (_view, designedResolution) {
const windowSize = screen.windowSize;
const frameW = windowSize.width;
const frameH = windowSize.height;
const containerStyle = legacyCC.game.container.style;
const designW = designedResolution.width;
const designH = designedResolution.height;
const scaleX = frameW / designW;
const scaleY = frameH / designH;
let containerW;
let containerH;
if (scaleX < scaleY) {
containerW = frameW;
containerH = designH * scaleX;
} else {
containerW = designW * scaleY;
containerH = frameH;
}
// Adjust container size with integer value
const offx = Math.round((frameW - containerW) / 2);
const offy = Math.round((frameH - containerH) / 2);
containerW = frameW - 2 * offx;
containerH = frameH - 2 * offy;
this._setupContainer(_view, containerW, containerH);
if (!EDITOR) {
// Setup container's margin and padding
if (screenAdapter.isFrameRotated) {
containerStyle.margin = `0 0 0 ${frameH}px`;
} else {
containerStyle.margin = '0px';
}
containerStyle.paddingLeft = `${offx}px`;
containerStyle.paddingRight = `${offx}px`;
containerStyle.paddingTop = `${offy}px`;
containerStyle.paddingBottom = `${offy}px`;
}
}
}
// Alias: Strategy that makes the container's size equals to the frame's size
ContainerStrategy.EQUAL_TO_FRAME = new EqualToFrame();
// Alias: Strategy that scale proportionally the container's size to frame's size
ContainerStrategy.PROPORTION_TO_FRAME = new ProportionalToFrame();
// Content scale strategys
class ExactFit extends ContentStrategy {
public name = 'ExactFit';
public apply (_view: View, designedResolution: Size) {
const windowSize = screen.windowSize;
const containerW = windowSize.width;
const containerH = windowSize.height;
const scaleX = containerW / designedResolution.width;
const scaleY = containerH / designedResolution.height;
return this._buildResult(containerW, containerH, containerW, containerH, scaleX, scaleY);
}
}
class ShowAll extends ContentStrategy {
public name = 'ShowAll';
public apply (_view, designedResolution) {
const windowSize = screen.windowSize;
const containerW = windowSize.width;
const containerH = windowSize.height;
const designW = designedResolution.width;
const designH = designedResolution.height;
const scaleX = containerW / designW;
const scaleY = containerH / designH;
let scale = 0;
let contentW;
let contentH;
if (scaleX < scaleY) {
scale = scaleX;
contentW = containerW;
contentH = designH * scale;
} else {
scale = scaleY;
contentW = designW * scale;
contentH = containerH;
}
return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
}
}
class NoBorder extends ContentStrategy {
public name = 'NoBorder';
public apply (_view, designedResolution) {
const windowSize = screen.windowSize;
const containerW = windowSize.width;
const containerH = windowSize.height;
const designW = designedResolution.width;
const designH = designedResolution.height;
const scaleX = containerW / designW;
const scaleY = containerH / designH;
let scale;
let contentW;
let contentH;
if (scaleX < scaleY) {
scale = scaleY;
contentW = designW * scale;
contentH = containerH;
} else {
scale = scaleX;
contentW = containerW;
contentH = designH * scale;
}
return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
}
}
class FixedHeight extends ContentStrategy {
public name = 'FixedHeight';
public apply (_view, designedResolution) {
const windowSize = screen.windowSize;
const containerW = windowSize.width;
const containerH = windowSize.height;
const designH = designedResolution.height;
const scale = containerH / designH;
const contentW = containerW;
const contentH = containerH;
return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
}
}
class FixedWidth extends ContentStrategy {
public name = 'FixedWidth';
public apply (_view, designedResolution) {
const windowSize = screen.windowSize;
const containerW = windowSize.width;
const containerH = windowSize.height;
const designW = designedResolution.width;
const scale = containerW / designW;
const contentW = containerW;
const contentH = containerH;
return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
}
}
// Alias: Strategy to scale the content's size to container's size, non proportional
ContentStrategy.EXACT_FIT = new ExactFit();
// Alias: Strategy to scale the content's size proportionally to maximum size and keeps the whole content area to be visible
ContentStrategy.SHOW_ALL = new ShowAll();
// Alias: Strategy to scale the content's size proportionally to fill the whole container area
ContentStrategy.NO_BORDER = new NoBorder();
// Alias: Strategy to scale the content's height to container's height and proportionally scale its width
ContentStrategy.FIXED_HEIGHT = new FixedHeight();
// Alias: Strategy to scale the content's width to container's width and proportionally scale its height
ContentStrategy.FIXED_WIDTH = new FixedWidth();
})();
/**
* ResolutionPolicy class is the root strategy class of scale strategy,
* its main task is to maintain the compatibility with Cocos2d-x</p>
*/
export class ResolutionPolicy {
/**
* The entire application is visible in the specified area without trying to preserve the original aspect ratio.<br/>
* Distortion can occur, and the application may appear stretched or compressed.
*/
public static EXACT_FIT = 0;
/**
* The entire application fills the specified area, without distortion but possibly with some cropping,<br/>
* while maintaining the original aspect ratio of the application.
*/
public static NO_BORDER = 1;
/**
* The entire application is visible in the specified area without distortion while maintaining the original<br/>
* aspect ratio of the application. Borders can appear on two sides of the application.
*/
public static SHOW_ALL = 2;
/**
* The application takes the height of the design resolution size and modifies the width of the internal<br/>
* canvas so that it fits the aspect ratio of the device<br/>
* no distortion will occur however you must make sure your application works on different<br/>
* aspect ratios
*/
public static FIXED_HEIGHT = 3;
/**
* The application takes the width of the design resolution size and modifies the height of the internal<br/>
* canvas so that it fits the aspect ratio of the device<br/>
* no distortion will occur however you must make sure your application works on different<br/>
* aspect ratios
*/
public static FIXED_WIDTH = 4;
/**
* Unknown policy
*/
public static UNKNOWN = 5;
public static ContainerStrategy: typeof ContainerStrategy = ContainerStrategy;
public static ContentStrategy: typeof ContentStrategy = ContentStrategy;
public name = 'ResolutionPolicy';
private _containerStrategy: null | ContainerStrategy;
private _contentStrategy: null | ContentStrategy;
/**
* Constructor of ResolutionPolicy
* @param containerStg
* @param contentStg
*/
constructor (containerStg: ContainerStrategy, contentStg: ContentStrategy) {
this._containerStrategy = null;
this._contentStrategy = null;
this.setContainerStrategy(containerStg);
this.setContentStrategy(contentStg);
}
get canvasSize () {
return screen.windowSize;
}
/**
* @en Manipulation before applying the resolution policy
* @zh 策略应用前的操作
* @param _view The target view
*/
public preApply (_view: View) {
this._contentStrategy!.preApply(_view);
}
/**
* @en Function to apply this resolution policy
* The return value is {scale: [scaleX, scaleY], viewport: {new Rect}},
* The target view can then apply these value to itself, it's preferred not to modify directly its private variables
* @zh 调用策略方法
* @param _view - The target view
* @param designedResolution - The user defined design resolution
* @return An object contains the scale X/Y values and the viewport rect
*/
public apply (_view: View, designedResolution: Size) {
this._containerStrategy!.apply(_view, designedResolution);
return this._contentStrategy!.apply(_view, designedResolution);
}
/**
* @en Manipulation after appyling the strategy
* @zh 策略应用之后的操作
* @param _view - The target view
*/
public postApply (_view: View) {
this._contentStrategy!.postApply(_view);
}
/**
* @en Setup the container's scale strategy
* @zh 设置容器的适配策略
* @param containerStg The container strategy
*/
public setContainerStrategy (containerStg: ContainerStrategy) {
if (containerStg instanceof ContainerStrategy) {
this._containerStrategy = containerStg;
}
}
/**
* @en Setup the content's scale strategy
* @zh 设置内容的适配策略
* @param contentStg The content strategy
*/
public setContentStrategy (contentStg: ContentStrategy) {
if (contentStg instanceof ContentStrategy) {
this._contentStrategy = contentStg;
}
}
}
legacyCC.ResolutionPolicy = ResolutionPolicy;
/**
* @en view is the singleton view object.
* @zh view 是全局的视图单例对象。
*/
export const view = View.instance = legacyCC.view = new View();
/**
* @en winSize is the alias object for the size of the current game window.
* @zh winSize 为当前的游戏窗口的大小。
*
* @deprecated since v3.3, please use view.getVisibleSize() instead.
*/
legacyCC.winSize = localWinSize; | the_stack |
module armExplorer
{
angular.module("armExplorer", ["ngRoute", "ngAnimate", "ngSanitize", "ui.bootstrap", "angularBootstrapNavTree", "rx", "mp.resizer", "ui.ace"])
.controller("treeBodyController", ["$scope", "$routeParams", "$location", "$http", "$timeout", "rx", "$document", ($scope: IArmTreeScope, $routeParams: ng.route.IRouteParamsService, $location: ng.ILocationService, $http: ng.IHttpService, $timeout: ng.ITimeoutService, rx: any, $document: ng.IDocumentService) => {
$scope.treeControl = <ITreeControl>{};
$scope.createModel = <ICreateModel>{};
$scope.actionsModel = {};
$scope.resources = [];
$scope.readOnlyMode = true;
$scope.editMode = false;
$scope.treeBranchDataOverrides = ClientConfig.treeBranchDataOverrides;
$scope.aceConfig = ClientConfig.aceConfig;
const activeTab: boolean[] = [false, false, false, false, false];
$timeout(() => {
$scope.editorCollection = new EditorCollection();
$scope.editorCollection.configureEditors();
});
$document.on('mouseup', () => { $timeout(() => { $scope.editorCollection.apply(e => { e.resize() }); }); });
$scope.$createObservableFunction("selectResourceHandler")
.flatMapLatest((args: any[]) => {
var branch: TreeBranch = args[0];
var event = args[1];
$scope.loading = true;
delete $scope.errorResponse;
if (branch.is_instruction) {
var parent = $scope.treeControl.get_parent_branch(branch);
$scope.treeControl.collapse_branch(parent);
$timeout(() => {
$scope.expandResourceHandler(parent, undefined, undefined, undefined, true /*dontFilterEmpty*/);
$scope.treeControl.select_branch(parent);
});
}
const resourceDefinition = branch.resourceDefinition;
if (resourceDefinition) {
const getHttpConfig = branch.getGetHttpConfig();
if (getHttpConfig) {
return rx.Observable.fromPromise($http(getHttpConfig))
//http://stackoverflow.com/a/30878646/3234163
.map(data => { return { resourceDefinition: resourceDefinition, data: data.data, url: getHttpConfig.data.Url, branch: branch, httpMethod: getHttpConfig.data.HttpMethod};})
.catch(error => rx.Observable.of({ error: error }));
} else {
return rx.Observable.of({ branch: branch, resourceDefinition: resourceDefinition });
}
} else {
return rx.Observable.fromPromise(Promise.resolve({ branch: branch }));
}
})
.subscribe((value: ISelectHandlerReturn) => {
if (value.error) {
var error = value.error;
setStateForErrorOnResourceClick();
let apiVersion = "";
let url = "";
if (error.config && error.config.resourceDefinition) {
url = error.config.filledInUrl;
$scope.editorCollection.setValue(Editor.ResponseEditor, "");
$scope.readOnlyResponse = "";
apiVersion = error.config.resourceDefinition.apiVersion;
}
$scope.errorResponse = StringUtils.syntaxHighlight({ data: error.data, status: error.status });
$scope.selectedResource = {
url: url,
actionsAndVerbs: [],
httpMethods: ["GET"],
doc: [],
apiVersion: apiVersion,
putUrl: url
};
} else {
setStateForClickOnResource();
if (value.data === undefined) {
if (value.resourceDefinition && value.resourceDefinition.hasRequestBody()) {
$scope.editorCollection.setValue(Editor.ResponseEditor, StringUtils.stringify(value.resourceDefinition.requestBody));
} else {
$scope.editorCollection.setValue(Editor.ResponseEditor, StringUtils.stringify({ message: "No GET Url" }));
$scope.editorCollection.setValue(Editor.PowershellEditor, "");
$scope.editorCollection.setValue(Editor.AnsibleEditor, "");
$scope.editorCollection.setValue(Editor.AzureCliEditor, "");
}
} else {
var resourceDefinition = value.resourceDefinition;
var url = value.url;
var putUrl = url;
if (resourceDefinition.hasPutOrPatchAction()) {
let editable = resourceDefinition.getEditable(value.data);
$scope.editorCollection.setValue(Editor.RequestEditor, StringUtils.stringify(ObjectUtils.sortByObject(editable, value.data)));
if (url.endsWith("list")) { putUrl = url.substring(0, url.lastIndexOf("/")); }
} else {
$scope.editorCollection.setValue(Editor.RequestEditor, "");
}
$scope.editorCollection.setValue(Editor.ResponseEditor, StringUtils.stringify(value.data));
enableCreateEditorIfRequired(resourceDefinition);
let actionsAndVerbs = $scope.resourceDefinitionsCollection.getActionsAndVerbs(value.branch);
let doc = resourceDefinition.getDocBody();
let docArray = DocumentationGenerator.getDocumentationFlatArray(value.data, doc);
$scope.selectedResource = {
// Some resources may contain # or whitespace in name,
// let's selectively URL-encode (for safety)
url: StringUtils.selectiveUrlencode(url),
actionsAndVerbs: actionsAndVerbs,
httpMethods: resourceDefinition.actions.filter(e => e !== "DELETE" && e !== "CREATE").map((e) => (e === "GETPOST" ? "POST" : e)).sort(),
doc: docArray,
apiVersion: resourceDefinition.apiVersion,
putUrl: putUrl
};
$location.path(url.replace(/https:\/\/[^\/]*\//, ""));
$scope.editorCollection.setValue(Editor.AzureCliEditor, getAzureCliScriptsForResource(value));
$scope.editorCollection.setValue(Editor.PowershellEditor, getPowerShellScriptsForResource(value, actionsAndVerbs));
$scope.editorCollection.setValue(Editor.AnsibleEditor, getAnsibleScriptsForResource(value, actionsAndVerbs, resourceDefinition));
}
}
fixActiveEditor();
});
function enableCreateEditorIfRequired(resourceDefinition: ResourceDefinition) {
if (resourceDefinition.hasCreateAction()) {
$scope.creatable = true;
$scope.createMetaData = resourceDefinition.requestBody;
$scope.editorCollection.setValue(Editor.CreateEditor, StringUtils.stringify(resourceDefinition.requestBody));
}
}
function fixActiveEditor() {
const activeIndex = activeTab.indexOf(true);
if ((!$scope.creatable && activeIndex === Editor.CreateEditor) ||
(!($scope.selectedResource && $scope.selectedResource.actionsAndVerbs &&
$scope.selectedResource.actionsAndVerbs.length > 0) && activeIndex === Editor.RequestEditor)) {
$timeout(() => { activeTab[Editor.ResponseEditor] = true });
}
}
$scope.handleClick = (selectedResource: ISelectedResource, method, event) => {
if (method === "PUT" || method === "PATCH") {
const action = new Action(method, "", "");
invokePutOrPatch(selectedResource, action, event);
} else {
refreshContent();
}
};
$scope.invokeAction = (selectedResource : ISelectedResource, action: Action, event) => {
doInvokeAction(selectedResource, action, event);
};
function invokePutFinallyCallback() {
$timeout(() => { $scope.invoking = false; $scope.loading = false; });
}
function invokePutErrorCallback(response: any) {
$timeout(() => { $scope.putError = response.data ? StringUtils.syntaxHighlight(response.data) : StringUtils.syntaxHighlight(response.message) });
ExplorerScreen.fadeInAndFadeOutError();
}
function finalizePut() {
$timeout(() => {
$scope.selectResourceHandler($scope.treeControl.get_selected_branch(), undefined);
ExplorerScreen.fadeInAndFadeOutSuccess();
});
}
async function invokePutOrPatch(selectedResource: ISelectedResource, action: Action, event: Event) {
setStateForInvokePut();
if ($scope.readOnlyMode) {
if (!action.isGetAction()) {
ExplorerScreen.showReadOnlyConfirmation(event);
}
} else {
const repository = new ArmClientRepository($http);
try {
await repository.invokePut(selectedResource, action, $scope.editorCollection);
finalizePut();
} catch (error) {
invokePutErrorCallback(error);
} finally {
invokePutFinallyCallback();
}
}
return Promise.resolve().then(invokePutFinallyCallback);
};
function keepChildPredicate(childName: string, resourceDefinition: ResourceDefinition, dontFilterEmpty: boolean, branch: TreeBranch,
providersFilter: any[]): boolean {
const childDefinition = $scope.resourceDefinitionsCollection.getResourceDefinitionByNameAndUrl(childName,
resourceDefinition.url + "/" + childName);
let keepChild = false;
if (childDefinition && (childDefinition.children || !childDefinition.hasPostAction())) {
if (dontFilterEmpty) {
keepChild = true;
} else {
keepChild = keepChildrenBasedOnExistingResources(branch, childName, providersFilter);
}
}
return keepChild;
}
function getSubscriptionBranch(branch: TreeBranch): TreeBranch {
if (!branch || isItemOf(branch, "subscriptions")) {
return branch;
} else {
return getSubscriptionBranch($scope.treeControl.get_parent_branch(branch));
}
}
async function getProvidersForBranch(branch: TreeBranch): Promise<any[]> {
let providers: any[] = undefined;
const subscriptionBranch = getSubscriptionBranch(branch);
if (subscriptionBranch) {
const repository = new ArmClientRepository($http);
const subscriptionsResponse = await repository.getProvidersForSubscription(subscriptionBranch.value);
providers = subscriptionsResponse.data;
}
return providers;
}
$scope.expandResourceHandler = async (branch: TreeBranch, row: any, event: Event, dontExpandChildren: boolean, dontFilterEmpty: boolean): Promise<any> => {
if (branch.is_leaf) return Promise.resolve();
if (branch.expanded) {
// clear the children array on collapse
branch.children.length = 0;
$timeout(() => { $scope.treeControl.collapse_branch(branch);});
return Promise.resolve();
}
var resourceDefinition = branch.resourceDefinition;
if (!resourceDefinition) return Promise.resolve();
// children are either an array or a string
// if array
// Predefined list of options. Like Providers or (config, appsettings, etc)
// else if string
// this means it's a Url that we need to ge fetch and display.
const children = resourceDefinition.children;
if (typeof children !== "string" && Array.isArray(children)) {
// if we are expanding an element of subscriptions (a subscription),
// then we need to make a request to the server to get a list of available providers in its resourceGroups
// then we can continue with normal expanding of an item
try {
const originalTreeIcon = showExpandingTreeItemIcon(row, branch);
const providersFilter: any[] = await getProvidersForBranch(branch);
const filteredChildren: string[] = children.filter((child: string) => {
return keepChildPredicate(child, resourceDefinition, dontFilterEmpty, branch, providersFilter);
});
const isListFiltered = filteredChildren.length !== children.length;
branch.children = filteredChildren.map((childName: string) => {
const childDefinition = $scope.resourceDefinitionsCollection.getResourceDefinitionByNameAndUrl(
childName,
resourceDefinition.url + "/" + childName);
const newTreeBranch = new TreeBranch(childName);
newTreeBranch.resourceDefinition = childDefinition;
newTreeBranch.is_leaf = (childDefinition.children ? false : true);
newTreeBranch.elementUrl = branch.elementUrl + "/" + childName;
newTreeBranch.sortValue = childName;
newTreeBranch.iconNameOverride = null;
return newTreeBranch;
});
endExpandingTreeItem(branch, originalTreeIcon);
var offset = 0;
if (!dontFilterEmpty && isListFiltered) {
var parent = $scope.treeControl.get_parent_branch(branch);
if (branch.label === "providers" || (parent && parent.currentResourceGroupProviders)) {
const showAllTreeBranch = new TreeBranch("Show all");
showAllTreeBranch.is_instruction = true;
showAllTreeBranch.resourceDefinition = resourceDefinition;
showAllTreeBranch.sortValue = null;
showAllTreeBranch.iconNameOverride = null;
branch.children.unshift(showAllTreeBranch);
offset++;
}
}
$timeout(() => { $scope.treeControl.expand_branch(branch);});
if ((branch.children.length - offset) === 1 && !dontExpandChildren) {
$timeout(() => { $scope.expandResourceHandler($scope.treeControl.get_first_non_instruction_child(branch)); });
}
} catch (error) {
console.log(error);
}
} else if (typeof children === "string") {
var getUrl = branch.elementUrl;
var originalIcon = showExpandingTreeItemIcon(row, branch);
var httpConfig = (getUrl.endsWith("resourceGroups") || getUrl.endsWith("subscriptions") || getUrl.split("/").length === 3)
? {
method: "GET",
url: `api${getUrl.substring(getUrl.indexOf("/subscriptions"))}`
}
: {
method: "POST",
url: "api/operations",
data: {
Url: getUrl,
HttpMethod: "GET",
ApiVersion: resourceDefinition.apiVersion
}
};
try {
const repository = new ArmClientRepository($http);
const httpResponse = await repository.invokeHttp(httpConfig);
const data = httpResponse.data;
var childDefinition = $scope.resourceDefinitionsCollection.getResourceDefinitionByNameAndUrl(children, resourceDefinition.url + "/" + resourceDefinition.children);
// get the projection to use for the current node (i.e. functions to provide label, sort key, ...)
var treeBranchProjection = getTreeBranchProjection(childDefinition);
branch.children = (data.value ? data.value : data).map((d: any) => {
var csmName = getCsmNameFromIdAndName(d.id, d.name);
var label = treeBranchProjection.getLabel(d, csmName);
const treeBranch = new TreeBranch(label);
treeBranch.resourceDefinition = childDefinition;
treeBranch.value = (d.subscriptionId ? d.subscriptionId : csmName);
treeBranch.is_leaf = (childDefinition.children ? false : true);
treeBranch.elementUrl = branch.elementUrl + "/" + (d.subscriptionId ? d.subscriptionId : csmName);
treeBranch.sortValue = treeBranchProjection.getSortKey(d, label);
treeBranch.iconNameOverride = treeBranchProjection.getIconNameOverride(d);
return treeBranch;
}).sort((a: TreeBranch, b: TreeBranch) => {
return a.sortValue.localeCompare(b.sortValue) * treeBranchProjection.sortOrder;
});
} catch (err) {
console.log(err);
} finally {
endExpandingTreeItem(branch, originalIcon);
$timeout(() => { $scope.treeControl.expand_branch(branch);});
if (branch.children && branch.children.length === 1 && !dontExpandChildren) {
$timeout(() => { $scope.expandResourceHandler($scope.treeControl.get_first_child(branch)); });
}
}
}
return Promise.resolve();
};
function keepChildrenBasedOnExistingResources(branch: TreeBranch, childName: string, providersFilter: any[]): boolean {
const parent = $scope.treeControl.get_parent_branch(branch);
let keepChild: boolean = true;
if (branch.label === "providers") {
// filter the providers by providersFilter
if (providersFilter) {
const currentResourceGroup = (parent && isItemOf(parent, "resourceGroups") ? parent.label : undefined);
if (currentResourceGroup) {
const currentResourceGroupProviders: any = providersFilter[currentResourceGroup.toUpperCase()];
if (currentResourceGroupProviders) {
branch.currentResourceGroupProviders = currentResourceGroupProviders;
keepChild = (currentResourceGroupProviders[childName.toUpperCase()] ? true : false);
} else {
keepChild = false;
}
}
}
} else if (parent && parent.currentResourceGroupProviders) {
keepChild = parent.currentResourceGroupProviders[branch.label.toUpperCase()] &&
parent.currentResourceGroupProviders[branch.label.toUpperCase()].some((c: string) => c.toUpperCase() === childName.toUpperCase());
}
return keepChild;
}
$scope.tenantSelect = () => {
window.location.href = "api/tenants/" + $scope.selectedTenant.id;
};
$scope.$createObservableFunction("delayResourceSearch")
.flatMapLatest((event) => {
// set 300 millionseconds gap, since user might still typing,
// we want to trigger search only when user stop typing
return $timeout(() => { return event; }, 300);
}).subscribe((event) => {
if (!event || event.keyCode !== 13 /* enter key will handle by form-submit */) {
$scope.resourceSearcher.resourceSearch();
}
});
$scope.selectResourceSearch = (item) => {
var itemId = item.id;
var currentSelectedBranch = $scope.treeControl.get_selected_branch();
if (currentSelectedBranch) {
const commonAncestor = $scope.treeControl.get_selected_branch().getCommonAncestorBranch(item.id);
while (currentSelectedBranch != null && !currentSelectedBranch.elementUrl.toLowerCase().endsWith(commonAncestor)) {
currentSelectedBranch = $scope.treeControl.get_parent_branch(currentSelectedBranch);
}
if (currentSelectedBranch) {
$scope.treeControl.select_branch(currentSelectedBranch);
const subscriptionTokenIndex = currentSelectedBranch.elementUrl.toLowerCase().indexOf("/subscriptions");
const currentSelectedBranchPath = currentSelectedBranch.elementUrl.substr(subscriptionTokenIndex);
itemId = itemId.substr(currentSelectedBranchPath.length);
} else {
// shouldn`t happen, but if it did happen, we fallback to collapse_all
$scope.treeControl.collapse_all();
}
}
handlePath(itemId.substr(1));
$scope.resourceSearchModel.turnOffSuggestions();
};
$scope.enterCreateMode = () => {
$scope.createMode = true;
$scope.editorCollection.resize(Editor.CreateEditor);
delete $scope.createModel.createdResourceName;
};
$scope.leaveCreateMode = () => {
$scope.createMode = false;
$scope.editorCollection.resize(Editor.ResponseEditor);
$scope.editorCollection.resize(Editor.RequestEditor);
};
$scope.clearCreate = () => {
delete $scope.createModel.createdResourceName;
$scope.editorCollection.setValue(Editor.CreateEditor, StringUtils.stringify($scope.createMetaData));
};
function finalizeCreate() {
const selectedBranch = $scope.treeControl.get_selected_branch();
$timeout(() => { $scope.treeControl.collapse_branch(selectedBranch); });
if (selectedBranch.uid === $scope.treeControl.get_selected_branch().uid) {
$timeout(() => { $scope.selectResourceHandler($scope.treeControl.get_selected_branch(), undefined); });
ExplorerScreen.fadeInAndFadeOutSuccess();
}
$timeout(() => { $scope.expandResourceHandler(selectedBranch); }, 50);
}
function invokeCreateErrorCallback(response: any) {
$timeout(() => { $scope.createError = response.data ? StringUtils.syntaxHighlight(response.data) : StringUtils.syntaxHighlight(response.message) });
ExplorerScreen.fadeInAndFadeOutError();
}
function invokeCreateFinallyCallback() {
$timeout(() => { $scope.invoking = false; $scope.loading = false; });
}
function setStateForInvokeCreate() {
delete $scope.createError;
$scope.invoking = true;
}
async function doInvokeCreate(selectedResource: ISelectedResource, event: Event) {
const resourceName = $scope.createModel.createdResourceName;
if (resourceName) {
setStateForInvokeCreate();
const action = new Action("PUT", "", "");
if ($scope.readOnlyMode) {
if (!action.isGetAction()) {
ExplorerScreen.showReadOnlyConfirmation(event);
}
} else {
const repository = new ArmClientRepository($http);
try {
await repository.invokeCreate(resourceName, selectedResource, action, $scope.editorCollection);
finalizeCreate();
} catch (error) {
invokeCreateErrorCallback(error);
} finally {
invokeCreateFinallyCallback();
}
}
} else {
invokeCreateErrorCallback({ message: "{Resource Name} can't be empty" });
}
return Promise.resolve().then(invokeCreateFinallyCallback);
}
$scope.invokeCreate = (selectedResource: ISelectedResource, event: Event) => {
doInvokeCreate(selectedResource, event);
}
function refreshContent() {
$scope.selectResourceHandler($scope.treeControl.get_selected_branch(), undefined);
};
$scope.enterDataTab = () => {
if ($scope.editorCollection) {
$scope.editorCollection.resize(Editor.ResponseEditor);
$scope.editorCollection.resize(Editor.RequestEditor);
}
};
$scope.hideDocs = () => {
var newWidth = $("#doc").outerWidth(true) + $("#content").outerWidth(true);
$("#content").css({ width: newWidth });
$("#doc").hide();
$("#doc-resizer").hide();
$("#show-doc-btn").show();
}
$scope.showDocs = () => {
$("#doc").show();
$("#doc-resizer").show();
var newWidth = $("#content").outerWidth(true) - $("#doc").outerWidth(true);
$("#content").css({ width: newWidth });
$("#show-doc-btn").hide();
}
$scope.hideConfirm = () => {
$(".confirm-box").fadeOut(300);
$('#dark-blocker').hide();
}
$scope.setReadOnlyMode = (readOnlyMode) => {
$scope.readOnlyMode = readOnlyMode;
$.cookie("readOnlyMode", readOnlyMode, { expires: 10 * 365, path: '/' });
}
$scope.toggleEditMode = () => {
$scope.editMode = !$scope.editMode;
$timeout(() => {
try {
$scope.editorCollection.resize(Editor.ResponseEditor);
$scope.editorCollection.resize(Editor.RequestEditor);
} catch (error) {
console.log(error);
}
});
}
$scope.showHttpVerb = (verb) => {
return ((verb === "GET" || verb === "POST") && !$scope.editMode) || ((verb === "PUT" || verb === "PATCH") && $scope.editMode);
};
$scope.logout = () => {
window.location.href = "/logout";
};
$scope.refresh = () => {
window.location.href = "/";
};
// https://www.reddit.com/r/web_design/comments/33kxgf/javascript_copying_to_clipboard_is_easier_than
$scope.copyResUrlToClipboard = (text: string) => {
// We can only use .select() on a textarea,
// so let's temporarily create one
var textField: HTMLTextAreaElement = document.createElement<"textarea">('textarea');
textField.innerText = text;
document.body.appendChild(textField);
textField.select();
if (document.execCommand('copy')) {
// Cycle resource URL color for visual feedback
$scope.resUrlColor = '#718c00'; // a soft green
$timeout(function () {
$scope.resUrlColor = '#000';
}, 350);
}
else {
console.error("document.execCommand('copy') returned false. " +
"Your browser may not support this feature or clipboard permissions don't allow it. " +
"See http://caniuse.com/#feat=document-execcommand.");
}
textField.remove();
}
// Get resourcesDefinitions
// no await since we don't need this to complete before continuing with rest of init
initResourcesDefinitions();
// Get tenants list
initTenants();
initSettings();
initUser();
initResourceSearch();
function initResourceSearch(): void {
const repository = new ArmClientRepository($http);
$scope.resourceSearchModel = new ResourceSearchDataModel();
$scope.resourceSearcher = new ResourceSearcher($scope.resourceSearchModel, repository);
// hide suggestion list when user click somewhere else
$("body").click(event => {
if (event && event.target
&& event.target.getAttribute("id") !== "resource-search-input"
&& !$.contains($("#resource-search-input")[0], event.target)
&& event.target.getAttribute("id") !== "resource-search-list"
&& !$.contains($("#resource-search-list")[0], event.target)) {
$scope.resourceSearchModel.turnOffSuggestions();
}
});
};
async function initUser() {
let currentUser: any;
try {
const repository = new ArmClientRepository($http);
const userTokenResponse = await repository.getUserToken();
const userToken = userTokenResponse.data;
currentUser = {
name: (userToken.given_name && userToken.family_name ? userToken.given_name + " " + userToken.family_name : undefined) || userToken.name || userToken.email || userToken.unique_name || "User",
imageUrl: "https://secure.gravatar.com/avatar/" + CryptoJS.MD5((userToken.email || userToken.unique_name || userToken.upn || userToken.name || "").toString()) + ".jpg?d=mm",
email: "(" + (userToken.upn ? userToken.upn : userToken.email) + ")"
};
} catch (error) {
currentUser = {
name: "User",
imageUrl: "https://secure.gravatar.com/avatar/.jpg?d=mm"
};
} finally {
$timeout(() => {$scope.user = currentUser});
}
}
function initSettings() {
if ($.cookie("readOnlyMode") !== undefined) {
$scope.setReadOnlyMode($.cookie("readOnlyMode") === "true");
}
}
async function expandChild(child: TreeBranch, rest: string, selectedBranch: TreeBranch) {
if (!child) {
if (selectedBranch) {
const top = document.getElementById("expand-icon-" + selectedBranch.uid).documentOffsetTop() - ((window.innerHeight - 50 /*nav bar height*/) / 2);
$("#sidebar").scrollTop(top);
}
} else {
$scope.treeControl.select_branch(child);
child = $scope.treeControl.get_selected_branch();
let expandPromise: Promise<any>;
if (child && $.isArray(child.children) && child.children.length > 0) {
expandPromise = Promise.resolve();
} else {
expandPromise = $scope.expandResourceHandler(child, undefined, undefined, true);
}
// use .then.catch.then to simulate finally
expandPromise.then().catch().then(() => { $timeout(() => { handlePath(rest); }); });
}
}
async function handlePath(path: string) {
if (path.length > 0) {
let index = path.indexOf("/");
index = (index === -1 ? undefined : index);
var current = path.substring(0, index);
const rest = path.substring(index + 1);
const selectedBranch = $scope.treeControl.get_selected_branch();
let matches: TreeBranch[] = [];
if (selectedBranch) {
if (!selectedBranch.expanded) {
try {
await $scope.expandResourceHandler(selectedBranch, undefined, undefined, true);
} catch (err) {
console.log(err);
}
}
matches = $scope.treeControl.get_children(selectedBranch).filter(e => current.toLocaleUpperCase() === (e.value ? e.value.toLocaleUpperCase() : e.label.toLocaleUpperCase()));
} else {
matches = $scope.treeControl.get_roots().filter(e => e.label.toLocaleUpperCase() === current.toLocaleUpperCase());
}
const child = (matches.length > 0 ? matches[0] : undefined);
expandChild(child, rest, selectedBranch);
}
}
function setStateForClickOnResource() {
delete $scope.putError;
delete $scope.selectedResource;
$scope.invoking = false;
$scope.loading = false;
$scope.creatable = false;
$scope.editMode = false;
}
function setStateForErrorOnResourceClick() {
$scope.invoking = false;
$scope.loading = false;
$scope.editMode = false;
}
function setStateForInvokeAction() {
$scope.loading = true;
delete $scope.actionResponse;
}
function setStateForInvokePut() {
delete $scope.putError;
$scope.invoking = true;
}
function finalizeDelete(action: Action, response: ng.IHttpPromiseCallbackArg<any>) {
const currentBranch = $scope.treeControl.get_selected_branch();
const parent = $scope.treeControl.get_parent_branch(currentBranch);
if (response.data) $scope.actionResponse = StringUtils.syntaxHighlight(response.data);
// async DELETE returns 202. That might fail later. So don't remove from the tree
if (action.isDeleteAction() && response.status === 200 /* OK */) {
if (currentBranch.uid === $scope.treeControl.get_selected_branch().uid) {
$timeout(() => { $scope.treeControl.select_branch(parent); scrollToTop(900);});
}
parent.children = parent.children.filter(branch => branch.uid !== currentBranch.uid);
} else {
$timeout(() => { $scope.selectResourceHandler($scope.treeControl.get_selected_branch(), undefined); });
}
ExplorerScreen.fadeInAndFadeOutSuccess();
}
function invokeActionErrorCallback(response: any) {
$timeout(() => { $scope.actionResponse = response.data ? StringUtils.syntaxHighlight(response.data) : StringUtils.syntaxHighlight(response.message)});
ExplorerScreen.fadeInAndFadeOutError();
}
function invokeActionFinallyCallback() {
$timeout(() => { $scope.loading = false; $scope.invoking = false; });
}
async function doInvokeAction(selectedResource: ISelectedResource, action: Action, event: Event, confirmed?: boolean) {
setStateForInvokeAction();
if ($scope.readOnlyMode) {
if (!action.isGetAction()) {
ExplorerScreen.showReadOnlyConfirmation(event);
// no finally in es6 promise. use a resolved promise with then instead
return Promise.resolve("Write attempted in read only mode").then(invokeActionFinallyCallback);
}
}
else if (action.isDeleteAction() && !confirmed) {
ExplorerScreen.showDeleteConfirmation(event, (deleteConfirmationHandler) => {
deleteConfirmationHandler.stopPropagation();
deleteConfirmationHandler.preventDefault();
$scope.hideConfirm();
doInvokeAction(selectedResource, action, deleteConfirmationHandler, true /*confirmed*/);
});
return Promise.resolve("Delete attempted pre-confirmation").then(invokeActionFinallyCallback);
} else {
const repository = new ArmClientRepository($http);
try {
const invokeResponse = await repository.invokeAction(selectedResource, action, $scope.actionsModel);
finalizeDelete(action, invokeResponse);
} catch (error) {
invokeActionErrorCallback(error);
} finally {
invokeActionFinallyCallback();
}
}
return Promise.resolve("doInvokeAction Complete").then(invokeActionFinallyCallback);
}
function getCsmNameFromIdAndName(id: string, name: string) {
const splited = (id ? decodeURIComponent(id) : name).split("/");
return splited[splited.length - 1];
}
function scrollToTop(delay: number) {
$timeout(() => { $("html, body").scrollTop(0); }, delay);
}
async function initTenants() {
try {
const repository = new ArmClientRepository($http);
const tenantCollection = new TenantCollection(repository);
await tenantCollection.buildTenants();
$timeout(() => { $scope.tenants = tenantCollection.getTenants(); $scope.selectedTenant = tenantCollection.getSelectedTenant();});
}
catch(error) {
console.log(error);
}
}
async function initResourcesDefinitions() {
try {
const repository = new ArmClientRepository($http);
$scope.resourceDefinitionsCollection = new ResourceDefinitionCollection(repository);
await $scope.resourceDefinitionsCollection.buildResourceDefinitions();
// Initializes the root nodes for the tree
// Since resources are updated async let angular known new update should be $digest-ed whenever we get around to updating resources
$timeout(() => { $scope.resources = $scope.resourceDefinitionsCollection.getTreeNodes(); });
} catch (error) {
console.log(error);
} finally {
$timeout(() => { handlePath($location.path().substring(1)) });
}
}
function isItemOf(branch: TreeBranch, elementType: string): boolean {
const parent = $scope.treeControl.get_parent_branch(branch);
return (parent && parent.resourceDefinition.resourceName === elementType);
}
function showExpandingTreeItemIcon(row: any, branch: TreeBranch): string {
const originalTreeIcon = row ? row.tree_icon : "icon-plus glyphicon glyphicon-plus fa fa-plus";
$(document.getElementById(`expand-icon-${branch.uid}`)).removeClass(originalTreeIcon).addClass("fa fa-refresh fa-spin");
return originalTreeIcon;
}
function endExpandingTreeItem(branch: TreeBranch, originalTreeIcon: string) {
$(document.getElementById(`expand-icon-${branch.uid}`)).removeClass("fa fa-spinner fa-spin").addClass(originalTreeIcon);
}
function getTreeBranchProjection(childDefinition: ResourceDefinition): ITreeBranchDataOverrides {
// look up to see whether the current node in the tree has any overrides for the
// display label or sort key/order
const override = ClientConfig.getOverrideFor(childDefinition);
// Apply default behaviors
// - label uses displayname with a fallback to csmName
// - sort is by label
if (override.getLabel == null) {
override.getLabel = (d: any, csmName: string) => (d.displayName ? d.displayName : csmName);
}
if (override.getSortKey == null) {
override.getSortKey = (d: any, label: string) => label;
}
if (override.getIconNameOverride == null) {
override.getIconNameOverride = (d: any) => null;
}
return override;
}
}])
.config(($locationProvider: ng.ILocationProvider) => {
$locationProvider.html5Mode(true);
});
// Global JS fixes
$('label.tree-toggler').click(function () {
$(this).parent().children('ul.tree').toggle(300);
});
$(document).mouseup((e) => {
var container = $(".confirm-box");
if (!container.is(e.target) && container.has(e.target).length === 0) {
container.fadeOut(300);
$('#dark-blocker').hide();
}
});
} | the_stack |
import {html, render} from '../../lit-html.js';
import {ref, createRef, RefOrCallback} from '../../directives/ref.js';
import {assert} from '@esm-bundle/chai';
suite('ref', () => {
let container: HTMLDivElement;
setup(() => {
container = document.createElement('div');
});
test('sets a ref on a Ref object', () => {
const divRef = createRef();
render(html`<div ${ref(divRef)}></div>`, container);
const div = container.firstElementChild;
assert.equal(divRef.value, div);
});
test('calls a ref callback', () => {
let divRef: Element | undefined;
const divCallback = (el: Element | undefined) => (divRef = el);
render(html`<div ${ref(divCallback)}></div>`, container);
const div = container.firstElementChild;
assert.equal(divRef, div);
});
test('sets a ref when Ref object changes', () => {
const divRef1 = createRef();
const divRef2 = createRef();
const go = (r: RefOrCallback) =>
render(html`<div ${ref(r)}></div>`, container);
go(divRef1);
const div1 = container.firstElementChild;
assert.equal(divRef1.value, div1);
go(divRef2);
const div2 = container.firstElementChild;
assert.equal(divRef1.value, undefined);
assert.equal(divRef2.value, div2);
});
test('calls a ref callback when callback changes', () => {
let divRef: Element | undefined;
const divCallback1 = (el: Element | undefined) => (divRef = el);
const divCallback2 = (el: Element | undefined) => (divRef = el);
const go = (r: RefOrCallback) =>
render(html`<div ${ref(r)}></div>`, container);
go(divCallback1);
const div1 = container.firstElementChild;
assert.equal(divRef, div1);
go(divCallback2);
const div2 = container.firstElementChild;
assert.equal(divRef, div2);
});
test('only sets a ref when element changes', () => {
let queriedEl: Element | null;
let callCount = 0;
const elRef = createRef();
// Patch Ref to observe value changes
let value: Element | undefined;
Object.defineProperty(elRef, 'value', {
set(v: Element | undefined) {
value = v;
callCount++;
},
get() {
return value;
},
});
const go = (x: boolean) =>
render(
x ? html`<div ${ref(elRef)}></div>` : html`<span ${ref(elRef)}></span>`,
container
);
go(true);
queriedEl = container.firstElementChild;
assert.equal(queriedEl?.tagName, 'DIV');
assert.equal(elRef.value, queriedEl);
assert.equal(callCount, 1);
go(true);
queriedEl = container.firstElementChild;
assert.equal(queriedEl?.tagName, 'DIV');
assert.equal(elRef.value, queriedEl);
assert.equal(callCount, 1);
go(false);
queriedEl = container.firstElementChild;
assert.equal(queriedEl?.tagName, 'SPAN');
assert.equal(elRef.value, queriedEl);
assert.equal(callCount, 2);
});
test('only calls a ref callback when element changes', () => {
let queriedEl: Element | null;
const calls: Array<string | undefined> = [];
const elCallback = (e: Element | undefined) => {
calls.push(e?.tagName);
};
const go = (x: boolean) =>
render(
x
? html`<div ${ref(elCallback)}></div>`
: html`<span ${ref(elCallback)}></span>`,
container
);
go(true);
queriedEl = container.firstElementChild;
assert.equal(queriedEl?.tagName, 'DIV');
assert.deepEqual(calls, ['DIV']);
go(true);
queriedEl = container.firstElementChild;
assert.equal(queriedEl?.tagName, 'DIV');
assert.deepEqual(calls, ['DIV']);
go(false);
queriedEl = container.firstElementChild;
assert.equal(queriedEl?.tagName, 'SPAN');
assert.deepEqual(calls, ['DIV', undefined, 'SPAN']);
go(true);
queriedEl = container.firstElementChild;
assert.equal(queriedEl?.tagName, 'DIV');
assert.deepEqual(calls, ['DIV', undefined, 'SPAN', undefined, 'DIV']);
});
test('calls callback bound to options.host', () => {
class Host {
bool = false;
calls: Array<string | undefined> = [];
root = document.createElement('div');
elCallback(e: Element | undefined) {
this.calls.push(e?.tagName);
}
render() {
return render(
this.bool
? html`<div ${ref(this.elCallback)}></div>`
: html`<span ${ref(this.elCallback)}></span>`,
this.root,
{host: this}
);
}
}
const testRef = (
host: Host,
initialCalls: Array<string | undefined> = []
) => {
let queriedEl: Element | null;
host.bool = true;
host.render();
queriedEl = host.root.firstElementChild;
assert.equal(queriedEl?.tagName, 'DIV');
assert.deepEqual(host.calls, [...initialCalls, 'DIV']);
host.bool = true;
host.render();
queriedEl = host.root.firstElementChild;
assert.equal(queriedEl?.tagName, 'DIV');
assert.deepEqual(host.calls, [...initialCalls, 'DIV']);
host.bool = false;
host.render();
queriedEl = host.root.firstElementChild;
assert.equal(queriedEl?.tagName, 'SPAN');
assert.deepEqual(host.calls, [...initialCalls, 'DIV', undefined, 'SPAN']);
host.bool = true;
host.render();
queriedEl = host.root.firstElementChild;
assert.equal(queriedEl?.tagName, 'DIV');
assert.deepEqual(host.calls, [
...initialCalls,
'DIV',
undefined,
'SPAN',
undefined,
'DIV',
]);
};
// Test first instance
const host1 = new Host();
testRef(host1);
// Test second instance
const host2 = new Host();
testRef(host2);
// Test on first instance again
// (reset boolean to render SPAN, so we see an initial change
// back to DIV)
host1.bool = false;
host1.render();
// Add in an undefined call for the initial switch from SPAN back to DIV
testRef(host1, [...host1.calls, undefined]);
});
test('two refs', () => {
const divRef1 = createRef();
const divRef2 = createRef();
render(html`<div ${ref(divRef1)} ${ref(divRef2)}></div>`, container);
const div = container.firstElementChild;
assert.equal(divRef1.value, div);
assert.equal(divRef2.value, div);
});
test('two ref callbacks alternating', () => {
let queriedEl: Element | null;
const divCalls: Array<string | undefined> = [];
const divCallback = (e: Element | undefined) => {
divCalls.push(e?.tagName);
};
const spanCalls: Array<string | undefined> = [];
const spanCallback = (e: Element | undefined) => {
spanCalls.push(e?.tagName);
};
const go = (x: boolean) =>
render(
x
? html`<div ${ref(divCallback)}></div>`
: html`<span ${ref(spanCallback)}></span>`,
container
);
go(true);
queriedEl = container.firstElementChild;
assert.equal(queriedEl?.tagName, 'DIV');
assert.deepEqual(divCalls, ['DIV']);
assert.deepEqual(spanCalls, []);
go(true);
queriedEl = container.firstElementChild;
assert.equal(queriedEl?.tagName, 'DIV');
assert.deepEqual(divCalls, ['DIV']);
assert.deepEqual(spanCalls, []);
go(false);
queriedEl = container.firstElementChild;
assert.equal(queriedEl?.tagName, 'SPAN');
assert.deepEqual(divCalls, ['DIV', undefined]);
assert.deepEqual(spanCalls, ['SPAN']);
go(true);
queriedEl = container.firstElementChild;
assert.equal(queriedEl?.tagName, 'DIV');
assert.deepEqual(divCalls, ['DIV', undefined, 'DIV']);
assert.deepEqual(spanCalls, ['SPAN', undefined]);
});
test('refs are always set in tree order', () => {
const elRef = createRef();
const go = () =>
render(
html`
<div id="first" ${ref(elRef)}></div>
<div id="next" ${ref(elRef)}>
${html`<span id="last" ${ref(elRef)}></span>`}
</div>`,
container
);
go();
assert.equal(elRef.value!.id, 'last');
go();
assert.equal(elRef.value!.id, 'last');
});
test('callbacks are always called in tree order', () => {
const calls: Array<string | undefined> = [];
const elCallback = (e: Element | undefined) => {
calls.push(e?.id);
};
const go = () =>
render(
html`
<div id="first" ${ref(elCallback)}></div>
<div id="next" ${ref(elCallback)}>
${html`<span id="last" ${ref(elCallback)}></span>`}
</div>`,
container
);
go();
assert.deepEqual(calls, ['first', undefined, 'next', undefined, 'last']);
calls.length = 0;
go();
assert.deepEqual(calls, [
undefined,
'first',
undefined,
'next',
undefined,
'last',
]);
});
test('Ref passed to ref directive changes', () => {
const aRef = createRef();
const bRef = createRef();
const go = (x: boolean) =>
render(html`<div ${ref(x ? aRef : bRef)}></div>`, container);
go(true);
assert.equal(aRef.value?.tagName, 'DIV');
assert.equal(bRef.value, undefined);
go(false);
assert.equal(aRef.value, undefined);
assert.equal(bRef.value?.tagName, 'DIV');
go(true);
assert.equal(aRef.value?.tagName, 'DIV');
assert.equal(bRef.value, undefined);
});
test('callback passed to ref directive changes', () => {
const aCalls: Array<string | undefined> = [];
const aCallback = (el: Element | undefined) => aCalls.push(el?.tagName);
const bCalls: Array<string | undefined> = [];
const bCallback = (el: Element | undefined) => bCalls.push(el?.tagName);
const go = (x: boolean) =>
render(html`<div ${ref(x ? aCallback : bCallback)}></div>`, container);
go(true);
assert.deepEqual(aCalls, ['DIV']);
assert.deepEqual(bCalls, []);
go(false);
assert.deepEqual(aCalls, ['DIV', undefined]);
assert.deepEqual(bCalls, ['DIV']);
go(true);
assert.deepEqual(aCalls, ['DIV', undefined, 'DIV']);
assert.deepEqual(bCalls, ['DIV', undefined]);
});
test('new callback created each render', () => {
const calls: Array<string | undefined> = [];
const go = () =>
render(
html`<div ${ref((el) => calls.push(el?.tagName))}></div>`,
container
);
go();
assert.deepEqual(calls, ['DIV']);
go();
assert.deepEqual(calls, ['DIV', undefined, 'DIV']);
go();
assert.deepEqual(calls, ['DIV', undefined, 'DIV', undefined, 'DIV']);
});
}); | the_stack |
import { assert } from "chai";
import * as fs from "fs";
import * as path from "path";
import { Guid, Id64Array, Id64String, Logger, OpenMode } from "@itwin/core-bentley";
import {
CodeScopeSpec, CodeSpec, ColorByName, DomainOptions, GeometryStreamBuilder, IModel, RelatedElementProps, RelationshipProps, SubCategoryAppearance,
UpgradeOptions,
} from "@itwin/core-common";
import { LineSegment3d, Point3d, YawPitchRollAngles } from "@itwin/core-geometry";
import { ElementDrivesElementProps, IModelHost, IModelJsFs, PhysicalModel, SpatialCategory, StandaloneDb } from "../../core-backend";
import { IModelTestUtils, TestElementDrivesElement, TestPhysicalObject, TestPhysicalObjectProps } from "../IModelTestUtils";
export function copyFile(newName: string, pathToCopy: string): string {
const newPath = path.join(path.dirname(pathToCopy), newName);
try {
fs.unlinkSync(newPath);
} catch (_err) {
}
fs.copyFileSync(pathToCopy, newPath);
return newPath;
}
function assertRels(list: RelationshipProps[], rels: ElementDrivesElementProps[]) {
assert.equal(list.length, rels.length);
for (let i = 0; i < rels.length; ++i) {
assert.equal(list[i].id, rels[i].id);
}
}
class DependencyCallbackResults {
public beforeOutputs: Id64Array = [];
public allInputsHandled: Id64Array = [];
public rootChanged: RelationshipProps[] = [];
public deletedDependency: RelationshipProps[] = [];
}
interface DbInfo {
seedFileName: string;
codeSpecId: Id64String;
physicalModelId: Id64String;
spatialCategoryId: Id64String;
}
class TestHelper {
public db: StandaloneDb;
public dres = new DependencyCallbackResults();
private removals: VoidFunction[] = [];
private codeSpecId: Id64String = "";
private physicalModelId: Id64String = "";
private spatialCategoryid: Id64String = "";
constructor(testName: string, dbInfo: DbInfo) {
this.codeSpecId = dbInfo.codeSpecId;
this.physicalModelId = dbInfo.physicalModelId;
this.spatialCategoryid = dbInfo.spatialCategoryId;
const writeDbFileName = copyFile(`${testName}.bim`, dbInfo.seedFileName);
this.db = StandaloneDb.openFile(writeDbFileName, OpenMode.ReadWrite);
assert.isTrue(this.db !== undefined);
this.db.nativeDb.enableTxnTesting();
assert.equal(this.db.nativeDb.addChildPropagatesChangesToParentRelationship("TestBim", "ChildPropagatesChangesToParent"), 0);
this.setElementDependencyGraphCallbacks();
}
public terminate() {
this.db.close();
assert.isFalse(this.db.isOpen);
this.removeElementDependencyGraphCallbacks();
}
public makeElement(codeValue: string, parent?: RelatedElementProps): TestPhysicalObjectProps {
const builder = new GeometryStreamBuilder();
builder.appendGeometry(LineSegment3d.create(Point3d.createZero(), Point3d.create(5, 0, 0)));
return {
classFullName: "TestBim:TestPhysicalObject",
model: this.physicalModelId,
category: this.spatialCategoryid,
code: { spec: this.codeSpecId, scope: this.physicalModelId, value: codeValue },
intProperty: 100,
placement: {
origin: new Point3d(0, 0, 0),
angles: new YawPitchRollAngles(),
},
geom: builder.geometryStream,
parent,
};
}
public insertElement(codeValue: string, parent?: RelatedElementProps): Id64String {
return this.db.elements.insertElement(this.makeElement(codeValue, parent));
}
public updateElement(elid: Id64String, newLabel: string) {
const ed2 = this.db.elements.getElement({ id: elid });
ed2.userLabel = newLabel;
this.db.elements.updateElement(ed2.toJSON());
}
public fmtElem(elId: Id64String) { return this.db.elements.getElement(elId).code.value; }
public fmtRel(props: RelationshipProps) { return `${props.classFullName} ${this.fmtElem(props.sourceId)} --> ${this.fmtElem(props.targetId)}`; }
public resetDependencyResults() {
this.dres = new DependencyCallbackResults();
}
public setElementDependencyGraphCallbacks() {
this.removals.push(TestElementDrivesElement.deletedDependency.addListener((evProps) => {
Logger.logTrace("EDGTest", `_onDeletedDependency ${this.fmtRel(evProps)}`);
this.dres.deletedDependency.push(evProps);
}));
this.removals.push(TestElementDrivesElement.rootChanged.addListener((evProps, _im) => {
Logger.logTrace("EDGTest", `_onRootChanged ${this.fmtRel(evProps)}`);
this.dres.rootChanged.push(evProps);
}));
this.removals.push(TestPhysicalObject.beforeOutputsHandled.addListener((elId) => {
Logger.logTrace("EDGTest", `_onBeforeOutputsHandled ${this.fmtElem(elId)}`);
this.dres.beforeOutputs.push(elId);
}));
this.removals.push(TestPhysicalObject.allInputsHandled.addListener((elId) => {
Logger.logTrace("EDGTest", `_onAllInputsHandled ${this.fmtElem(elId)}`);
this.dres.allInputsHandled.push(elId);
}));
}
public removeElementDependencyGraphCallbacks() {
this.removals.forEach((drop) => drop());
}
}
describe("ElementDependencyGraph", () => {
let testFileName: string;
let dbInfo: DbInfo;
const performUpgrade = (pathname: string) => {
const nativeDb = new IModelHost.platform.DgnDb();
const upgradeOptions: UpgradeOptions = {
domain: DomainOptions.Upgrade,
};
nativeDb.openIModel(pathname, OpenMode.ReadWrite, upgradeOptions);
nativeDb.deleteAllTxns();
nativeDb.closeIModel();
};
before(async () => {
IModelTestUtils.registerTestBimSchema();
// make a unique name for the output file so this test can be run in parallel
testFileName = IModelTestUtils.prepareOutputFile("ElementDependencyGraph", `${Guid.createValue()}.bim`);
const seedFileName = IModelTestUtils.resolveAssetFile("test.bim");
const schemaFileName = IModelTestUtils.resolveAssetFile("TestBim.ecschema.xml");
IModelJsFs.copySync(seedFileName, testFileName);
performUpgrade(testFileName);
const imodel = StandaloneDb.openFile(testFileName, OpenMode.ReadWrite);
await imodel.importSchemas([schemaFileName]); // will throw an exception if import fails
const physicalModelId = PhysicalModel.insert(imodel, IModel.rootSubjectId, "EDGTestModel");
const codeSpecId = imodel.codeSpecs.insert(CodeSpec.create(imodel, "EDGTestCodeSpec", CodeScopeSpec.Type.Model));
const spatialCategoryId = SpatialCategory.insert(imodel, IModel.dictionaryId, "EDGTestSpatialCategory", new SubCategoryAppearance({ color: ColorByName.darkRed }));
dbInfo = { physicalModelId, codeSpecId, spatialCategoryId, seedFileName: testFileName };
imodel.saveChanges("");
imodel.nativeDb.deleteAllTxns();
imodel.close();
});
after(() => {
IModelJsFs.removeSync(testFileName);
});
it("should invokeCallbacks EDE only", () => {
const helper = new TestHelper("EDE", dbInfo);
const e1id = helper.insertElement("e1");
const e2id = helper.insertElement("e2");
const e3id = helper.insertElement("e3");
helper.db.saveChanges(); // get the elements into the iModel
const ede_1_2 = TestElementDrivesElement.create<TestElementDrivesElement>(helper.db, e1id, e2id);
const ede_2_3 = TestElementDrivesElement.create<TestElementDrivesElement>(helper.db, e2id, e3id);
for (const ede of [ede_1_2, ede_2_3]) {
ede.insert();
}
// The full graph:
// e1 --> e2 --> e3
helper.resetDependencyResults();
helper.db.saveChanges(); // this will react to EDE inserts only.
assert.deepEqual(helper.dres.beforeOutputs, []); // only roots get this callback, and only if they have been directly changed.
assert.deepEqual(helper.dres.allInputsHandled, []); // No input elements have changed
assertRels(helper.dres.rootChanged, [ede_1_2.toJSON(), ede_2_3.toJSON()]); // we send out this callback even if only the relationship itself is new or changed.
helper.updateElement(e1id, "change e1");
helper.resetDependencyResults();
helper.db.saveChanges();
assert.deepEqual(helper.dres.beforeOutputs, [e1id]); // only called on directly changed root elements.
assert.deepEqual(helper.dres.allInputsHandled, [e2id, e3id]);
assertRels(helper.dres.rootChanged, [ede_1_2.toJSON(), ede_2_3.toJSON()]);
helper.terminate();
});
it("should invokeCallbacks through parents only", () => {
const helper = new TestHelper("Parents", dbInfo);
const p2id = helper.insertElement("p2");
const e1id = helper.insertElement("e1", { id: p2id, relClassName: "TestBim.ChildPropagatesChangesToParent" });
helper.db.saveChanges(); // get the elements into the iModel
// The full graph:
// .-parent-> p2
// /
// e1
//
helper.resetDependencyResults();
helper.db.saveChanges();
assert.deepEqual(helper.dres.beforeOutputs, []); // only roots get this callback, and only if they have been directly changed.
assert.deepEqual(helper.dres.allInputsHandled, []); // No input elements have changed
assertRels(helper.dres.rootChanged, []); // we send out this callback even if only the relationship itself is new or changed.
helper.updateElement(e1id, "change e1");
helper.resetDependencyResults();
helper.db.saveChanges();
assert.deepEqual(helper.dres.beforeOutputs, [e1id]); // only called on directly changed root elements.
assert.deepEqual(helper.dres.allInputsHandled, [p2id]);
assertRels(helper.dres.rootChanged, []);
helper.updateElement(p2id, "change p2");
helper.resetDependencyResults();
helper.db.saveChanges();
assert.deepEqual(helper.dres.beforeOutputs, []); // only called on directly changed root elements
assert.deepEqual(helper.dres.allInputsHandled, []);
assertRels(helper.dres.rootChanged, []);
helper.terminate();
});
it("should invokeCallbacks through EDEs and parents", () => {
const helper = new TestHelper("EDEsAndParents", dbInfo);
const p2id = helper.insertElement("p2");
const p3id = helper.insertElement("p3");
const e1id = helper.insertElement("e1", { id: p2id, relClassName: "TestBim.ChildPropagatesChangesToParent" });
const e2id = helper.insertElement("e2");
const e3id = helper.insertElement("e3");
helper.db.saveChanges(); // get the elements into the iModel
const ede_1_2 = TestElementDrivesElement.create<TestElementDrivesElement>(helper.db, e1id, e2id);
const ede_2_3 = TestElementDrivesElement.create<TestElementDrivesElement>(helper.db, e2id, e3id);
const ede_p2_p3 = TestElementDrivesElement.create<TestElementDrivesElement>(helper.db, p2id, p3id);
for (const ede of [ede_1_2, ede_2_3, ede_p2_p3]) {
ede.insert();
}
// db.nativeDb.writeFullElementDependencyGraphToFile(`${writeDbFileName}.dot`);
// The full graph:
// .-parent-> p2 -EDE-> p3
// /
// e1 -EDE-> e2 -EDE-> e3
//
helper.resetDependencyResults();
helper.db.saveChanges(); // this will react to EDE inserts only.
assert.deepEqual(helper.dres.beforeOutputs, []); // only roots get this callback, and only if they have been directly changed.
assert.deepEqual(helper.dres.allInputsHandled, []); // No input elements have changed
assertRels(helper.dres.rootChanged, [ede_1_2.toJSON(), ede_2_3.toJSON(), ede_p2_p3.toJSON()]); // we send out this callback even if only the relationship itself is new or changed.
helper.updateElement(e1id, "change e1");
helper.resetDependencyResults();
helper.db.saveChanges();
assert.deepEqual(helper.dres.beforeOutputs, [e1id]); // only called on directly changed root elements.
assert.deepEqual(helper.dres.allInputsHandled, [e2id, p2id, e3id, p3id]);
assertRels(helper.dres.rootChanged, [ede_1_2.toJSON(), ede_2_3.toJSON(), ede_p2_p3.toJSON()]);
helper.updateElement(p2id, "change p2");
helper.resetDependencyResults();
helper.db.saveChanges();
assert.deepEqual(helper.dres.beforeOutputs, [p2id]); // only called on directly changed root elements.
assert.deepEqual(helper.dres.allInputsHandled, [p3id]);
assertRels(helper.dres.rootChanged, [ede_p2_p3.toJSON()]);
helper.updateElement(e2id, "change e2");
helper.resetDependencyResults();
helper.db.saveChanges();
assert.deepEqual(helper.dres.beforeOutputs, [e2id]); // only called on directly changed root elements.
assert.deepEqual(helper.dres.allInputsHandled, [e3id]);
assertRels(helper.dres.rootChanged, [ede_2_3.toJSON()]);
helper.terminate();
});
it("should invokeCallbacks through parents - geomodeler schema", () => {
const helper = new TestHelper("GeoModeler", dbInfo);
// The full graph:
// BoreholeSource -EDE-> GroundGeneration
// / parent
// Borehole
// / parent
// Material -EDE-> MaterialDepthRange
const boreholeSource = helper.insertElement("BoreholeSource");
const borehole = helper.insertElement("Borehole", { id: boreholeSource, relClassName: "TestBim.ChildPropagatesChangesToParent" });
const materialDepthRange = helper.insertElement("MaterialDepthRange", { id: borehole, relClassName: "TestBim.ChildPropagatesChangesToParent" });
const material = helper.insertElement("Material");
const groundGeneration = helper.insertElement("GroundGeneration");
helper.db.saveChanges(); // get the elements into the iModel
const ede_material_materialDepthRange = TestElementDrivesElement.create<TestElementDrivesElement>(helper.db, material, materialDepthRange);
const ede_boreholeSource_groundGeneration = TestElementDrivesElement.create<TestElementDrivesElement>(helper.db, boreholeSource, groundGeneration);
for (const ede of [ede_material_materialDepthRange, ede_boreholeSource_groundGeneration]) {
ede.insert();
}
helper.resetDependencyResults();
helper.db.saveChanges();
helper.updateElement(material, "change material");
helper.resetDependencyResults();
helper.db.saveChanges();
assert.deepEqual(helper.dres.beforeOutputs, [material]); // only called on directly changed root elements.
assert.deepEqual(helper.dres.allInputsHandled, [materialDepthRange, borehole, boreholeSource, groundGeneration]);
assertRels(helper.dres.rootChanged, [ede_material_materialDepthRange.toJSON(), ede_boreholeSource_groundGeneration.toJSON()]);
helper.terminate();
});
it("should invokeCallbacks many:1", () => {
const helper = new TestHelper("ManyToOne", dbInfo);
const e1id = helper.insertElement("e1");
const e11id = helper.insertElement("e11");
const e2id = helper.insertElement("e2");
const e21id = helper.insertElement("e21");
const e3id = helper.insertElement("e3");
const e4id = helper.insertElement("e4");
const ede_1_2 = TestElementDrivesElement.create<TestElementDrivesElement>(helper.db, e1id, e2id);
const ede_11_2 = TestElementDrivesElement.create<TestElementDrivesElement>(helper.db, e11id, e2id);
const ede_2_3 = TestElementDrivesElement.create<TestElementDrivesElement>(helper.db, e2id, e3id);
const ede_21_3 = TestElementDrivesElement.create<TestElementDrivesElement>(helper.db, e21id, e3id);
const ede_3_4 = TestElementDrivesElement.create<TestElementDrivesElement>(helper.db, e3id, e4id);
for (const ede of [ede_1_2, ede_11_2, ede_2_3, ede_21_3, ede_3_4]) {
ede.insert();
}
// The full graph:
// e21
// \
// e1 --> e2 --> e3 --> e4
// /
// e11
// On the very first validation, everything is new and is considered directly changed
// resulting graph:
// e21
// \
// e1 --> e2 --> e3 --> e4
// /
// e11
helper.resetDependencyResults();
helper.db.saveChanges();
assert.deepEqual(helper.dres.beforeOutputs, [e1id, e11id, e21id]); // only called on directly changed root elements.
assert.deepEqual(helper.dres.allInputsHandled, [e2id, e3id, e4id]);
assertRels(helper.dres.rootChanged, [ede_1_2.toJSON(), ede_11_2.toJSON(), ede_2_3.toJSON(), ede_21_3.toJSON(), ede_3_4.toJSON()]);
// modify e4 directly. That is a leaf. None of its inputs are changed.
// resulting subgraph:
// *
// e4
//
//
helper.updateElement(e4id, "change e4");
helper.resetDependencyResults();
helper.db.saveChanges();
assert.deepEqual(helper.dres.beforeOutputs, []); // only called on directly changed root elements.
assert.deepEqual(helper.dres.allInputsHandled, []);
assertRels(helper.dres.rootChanged, []);
// modify e3 directly.
// resulting subgraph:
//
//
// *
// e3 --> e4
//
//
helper.updateElement(e3id, "change e3");
helper.resetDependencyResults();
helper.db.saveChanges();
assert.deepEqual(helper.dres.beforeOutputs, [e3id]); // only called on directly changed root elements.
assert.deepEqual(helper.dres.allInputsHandled, [e4id]);
assertRels(helper.dres.rootChanged, [ede_3_4.toJSON()]);
// modify e2 directly. That is a node in middle of the graph. None of its inputs is modified.
// resulting subgraph:
//
// *
// e2 --> e3 --> e4
//
//
//
helper.updateElement(e2id, "change e2");
helper.resetDependencyResults();
helper.db.saveChanges();
assert.deepEqual(helper.dres.beforeOutputs, [e2id]); // only called on directly changed root elements
assert.deepEqual(helper.dres.allInputsHandled, [e3id, e4id],);
assertRels(helper.dres.rootChanged, [ede_2_3.toJSON(), ede_3_4.toJSON()]);
// Modify e1 directly. That should propagate to the rest of the nodes. Each should get an _onAllInputsHandled callback
// resulting graph:
//
// *
// e1 --> e2 --> e3 --> e4
//
helper.updateElement(e1id, "change e1");
helper.resetDependencyResults();
helper.db.saveChanges();
assert.deepEqual(helper.dres.beforeOutputs, [e1id]); // only called on directly changed root elements
assert.deepEqual(helper.dres.allInputsHandled, [e2id, e3id, e4id]);
assertRels(helper.dres.rootChanged, [ede_1_2.toJSON(), ede_2_3.toJSON(), ede_3_4.toJSON()]);
// Modify e11 directly. That should propagate to the rest of the nodes. Each should get an _onAllInputsHandled callback
// resulting graph:
//
// > e2 --> e3 --> e4
// /
// e11
// *
//
// Note that the e1 -> e2 and e21 -> e3 edges are NOT in the sub-graph. These edges should be validated, nevertheless -- TBD
helper.updateElement(e11id, "change e11");
helper.resetDependencyResults();
helper.db.saveChanges();
// assert.deepEqual(helper.dres.directChange, []); // only called on directly changed non-root elements that have no directly changed inputs
assert.deepEqual(helper.dres.beforeOutputs, [e11id]); // only called on directly changed root elements
assert.deepEqual(helper.dres.allInputsHandled, [e2id, e3id, e4id]);
assertRels(helper.dres.rootChanged, [ede_11_2.toJSON(), ede_2_3.toJSON(), ede_3_4.toJSON()]);
// assertRels(helper.dres.validateOutput, [ede_1_2, ede_21_3]); // this callback is made only on rels that not in the graph but share an output with another rel or have an output that was directly changed
helper.terminate();
});
}); | the_stack |
import { Inject, Injectable, Optional } from '@angular/core';
import { Http, Headers, URLSearchParams } from '@angular/http';
import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http';
import { Response, ResponseContentType } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import '../rxjs-operators';
import { Appointment } from '../model/appointment';
import { InlineResponse200 } from '../model/inlineResponse200';
import { InlineResponse2001 } from '../model/inlineResponse2001';
import { InlineResponse2002 } from '../model/inlineResponse2002';
import { Notification } from '../model/notification';
import { Patient } from '../model/patient';
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
/* tslint:disable:no-unused-variable member-ordering */
@Injectable()
export class NotificationService {
protected basePath = 'http://localhost:3000/api';
public defaultHeaders: Headers = new Headers();
public configuration: Configuration = new Configuration();
constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) {
if (basePath) {
this.basePath = basePath;
}
if (configuration) {
this.configuration = configuration;
this.basePath = basePath || configuration.basePath || this.basePath;
}
}
/**
*
* Extends object by coping non-existing properties.
* @param objA object to be extended
* @param objB source object
*/
private extendObj<T1,T2>(objA: T1, objB: T2) {
for(let key in objB){
if(objB.hasOwnProperty(key)){
(objA as any)[key] = (objB as any)[key];
}
}
return <T1&T2>objA;
}
/**
* @param consumes string[] mime-types
* @return true: consumes contains 'multipart/form-data', false: otherwise
*/
private canConsumeForm(consumes: string[]): boolean {
const form = 'multipart/form-data';
for (let consume of consumes) {
if (form === consume) {
return true;
}
}
return false;
}
/**
* Count instances of the model matched by where from the data source.
*
* @param where Criteria to match model instances
*/
public notificationCount(where?: string, extraHttpRequestParams?: any): Observable<InlineResponse200> {
return this.notificationCountWithHttpInfo(where, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Create a new instance of the model and persist it into the data source.
*
* @param data Model instance data
*/
public notificationCreate(data?: Notification, extraHttpRequestParams?: any): Observable<Notification> {
return this.notificationCreateWithHttpInfo(data, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Create a change stream.
*
* @param options
*/
public notificationCreateChangeStreamGetNotificationsChangeStream(options?: string, extraHttpRequestParams?: any): Observable<Blob> {
return this.notificationCreateChangeStreamGetNotificationsChangeStreamWithHttpInfo(options, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.blob();
}
});
}
/**
* Create a change stream.
*
* @param options
*/
public notificationCreateChangeStreamPostNotificationsChangeStream(options?: string, extraHttpRequestParams?: any): Observable<Blob> {
return this.notificationCreateChangeStreamPostNotificationsChangeStreamWithHttpInfo(options, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.blob();
}
});
}
/**
* Delete a model instance by {{id}} from the data source.
*
* @param id Model id
*/
public notificationDeleteById(id: string, extraHttpRequestParams?: any): Observable<any> {
return this.notificationDeleteByIdWithHttpInfo(id, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Check whether a model instance exists in the data source.
*
* @param id Model id
*/
public notificationExistsGetNotificationsidExists(id: string, extraHttpRequestParams?: any): Observable<InlineResponse2001> {
return this.notificationExistsGetNotificationsidExistsWithHttpInfo(id, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Check whether a model instance exists in the data source.
*
* @param id Model id
*/
public notificationExistsHeadNotificationsid(id: string, extraHttpRequestParams?: any): Observable<InlineResponse2001> {
return this.notificationExistsHeadNotificationsidWithHttpInfo(id, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Find all instances of the model matched by filter from the data source.
*
* @param filter Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\"something\":\"value\"})
*/
public notificationFind(filter?: string, extraHttpRequestParams?: any): Observable<Array<Notification>> {
return this.notificationFindWithHttpInfo(filter, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Find a model instance by {{id}} from the data source.
*
* @param id Model id
* @param filter Filter defining fields and include - must be a JSON-encoded string ({\"something\":\"value\"})
*/
public notificationFindById(id: string, filter?: string, extraHttpRequestParams?: any): Observable<Notification> {
return this.notificationFindByIdWithHttpInfo(id, filter, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Find first instance of the model matched by filter from the data source.
*
* @param filter Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\"something\":\"value\"})
*/
public notificationFindOne(filter?: string, extraHttpRequestParams?: any): Observable<Notification> {
return this.notificationFindOneWithHttpInfo(filter, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Patch an existing model instance or insert a new one into the data source.
*
* @param data Model instance data
*/
public notificationPatchOrCreate(data?: Notification, extraHttpRequestParams?: any): Observable<Notification> {
return this.notificationPatchOrCreateWithHttpInfo(data, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Fetches belongsTo relation appointment.
*
* @param id Notification id
* @param refresh
*/
public notificationPrototypeGetAppointment(id: string, refresh?: boolean, extraHttpRequestParams?: any): Observable<Appointment> {
return this.notificationPrototypeGetAppointmentWithHttpInfo(id, refresh, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Fetches belongsTo relation patient.
*
* @param id Notification id
* @param refresh
*/
public notificationPrototypeGetPatient(id: string, refresh?: boolean, extraHttpRequestParams?: any): Observable<Patient> {
return this.notificationPrototypeGetPatientWithHttpInfo(id, refresh, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Patch attributes for a model instance and persist it into the data source.
*
* @param id Notification id
* @param data An object of model property name/value pairs
*/
public notificationPrototypePatchAttributes(id: string, data?: Notification, extraHttpRequestParams?: any): Observable<Notification> {
return this.notificationPrototypePatchAttributesWithHttpInfo(id, data, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Replace attributes for a model instance and persist it into the data source.
*
* @param id Model id
* @param data Model instance data
*/
public notificationReplaceByIdPostNotificationsidReplace(id: string, data?: Notification, extraHttpRequestParams?: any): Observable<Notification> {
return this.notificationReplaceByIdPostNotificationsidReplaceWithHttpInfo(id, data, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Replace attributes for a model instance and persist it into the data source.
*
* @param id Model id
* @param data Model instance data
*/
public notificationReplaceByIdPutNotificationsid(id: string, data?: Notification, extraHttpRequestParams?: any): Observable<Notification> {
return this.notificationReplaceByIdPutNotificationsidWithHttpInfo(id, data, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Replace an existing model instance or insert a new one into the data source.
*
* @param data Model instance data
*/
public notificationReplaceOrCreatePostNotificationsReplaceOrCreate(data?: Notification, extraHttpRequestParams?: any): Observable<Notification> {
return this.notificationReplaceOrCreatePostNotificationsReplaceOrCreateWithHttpInfo(data, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Replace an existing model instance or insert a new one into the data source.
*
* @param data Model instance data
*/
public notificationReplaceOrCreatePutNotifications(data?: Notification, extraHttpRequestParams?: any): Observable<Notification> {
return this.notificationReplaceOrCreatePutNotificationsWithHttpInfo(data, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Update instances of the model matched by {{where}} from the data source.
*
* @param where Criteria to match model instances
* @param data An object of model property name/value pairs
*/
public notificationUpdateAll(where?: string, data?: Notification, extraHttpRequestParams?: any): Observable<InlineResponse2002> {
return this.notificationUpdateAllWithHttpInfo(where, data, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Update an existing model instance or insert a new one into the data source based on the where criteria.
*
* @param where Criteria to match model instances
* @param data An object of model property name/value pairs
*/
public notificationUpsertWithWhere(where?: string, data?: Notification, extraHttpRequestParams?: any): Observable<Notification> {
return this.notificationUpsertWithWhereWithHttpInfo(where, data, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
/**
* Count instances of the model matched by where from the data source.
*
* @param where Criteria to match model instances
*/
public notificationCountWithHttpInfo(where?: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/Notifications/count';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
if (where !== undefined) {
queryParameters.set('where', <any>where);
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Create a new instance of the model and persist it into the data source.
*
* @param data Model instance data
*/
public notificationCreateWithHttpInfo(data?: Notification, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/Notifications';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Create a change stream.
*
* @param options
*/
public notificationCreateChangeStreamGetNotificationsChangeStreamWithHttpInfo(options?: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/Notifications/change-stream';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
if (options !== undefined) {
queryParameters.set('options', <any>options);
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
responseType: ResponseContentType.Blob,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Create a change stream.
*
* @param options
*/
public notificationCreateChangeStreamPostNotificationsChangeStreamWithHttpInfo(options?: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/Notifications/change-stream';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// to determine the Content-Type header
let consumes: string[] = [
'application/json',
'application/x-www-form-urlencoded',
'application/xml',
'text/xml'
];
let canConsumeForm = this.canConsumeForm(consumes);
let useForm = false;
let formParams = new (useForm ? FormData : URLSearchParams as any)() as {
set(param: string, value: any): void;
};
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
if (options !== undefined) {
formParams.set('options', <any>options);
}
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: formParams,
responseType: ResponseContentType.Blob,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Delete a model instance by {{id}} from the data source.
*
* @param id Model id
*/
public notificationDeleteByIdWithHttpInfo(id: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/Notifications/${id}'
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling notificationDeleteById.');
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Delete,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Check whether a model instance exists in the data source.
*
* @param id Model id
*/
public notificationExistsGetNotificationsidExistsWithHttpInfo(id: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/Notifications/${id}/exists'
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling notificationExistsGetNotificationsidExists.');
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Check whether a model instance exists in the data source.
*
* @param id Model id
*/
public notificationExistsHeadNotificationsidWithHttpInfo(id: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/Notifications/${id}'
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling notificationExistsHeadNotificationsid.');
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Head,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Find all instances of the model matched by filter from the data source.
*
* @param filter Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\"something\":\"value\"})
*/
public notificationFindWithHttpInfo(filter?: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/Notifications';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
if (filter !== undefined) {
queryParameters.set('filter', <any>filter);
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Find a model instance by {{id}} from the data source.
*
* @param id Model id
* @param filter Filter defining fields and include - must be a JSON-encoded string ({\"something\":\"value\"})
*/
public notificationFindByIdWithHttpInfo(id: string, filter?: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/Notifications/${id}'
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling notificationFindById.');
}
if (filter !== undefined) {
queryParameters.set('filter', <any>filter);
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Find first instance of the model matched by filter from the data source.
*
* @param filter Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\"something\":\"value\"})
*/
public notificationFindOneWithHttpInfo(filter?: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/Notifications/findOne';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
if (filter !== undefined) {
queryParameters.set('filter', <any>filter);
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Patch an existing model instance or insert a new one into the data source.
*
* @param data Model instance data
*/
public notificationPatchOrCreateWithHttpInfo(data?: Notification, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/Notifications';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Patch,
headers: headers,
body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Fetches belongsTo relation appointment.
*
* @param id Notification id
* @param refresh
*/
public notificationPrototypeGetAppointmentWithHttpInfo(id: string, refresh?: boolean, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/Notifications/${id}/appointment'
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling notificationPrototypeGetAppointment.');
}
if (refresh !== undefined) {
queryParameters.set('refresh', <any>refresh);
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Fetches belongsTo relation patient.
*
* @param id Notification id
* @param refresh
*/
public notificationPrototypeGetPatientWithHttpInfo(id: string, refresh?: boolean, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/Notifications/${id}/patient'
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling notificationPrototypeGetPatient.');
}
if (refresh !== undefined) {
queryParameters.set('refresh', <any>refresh);
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Patch attributes for a model instance and persist it into the data source.
*
* @param id Notification id
* @param data An object of model property name/value pairs
*/
public notificationPrototypePatchAttributesWithHttpInfo(id: string, data?: Notification, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/Notifications/${id}'
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling notificationPrototypePatchAttributes.');
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Patch,
headers: headers,
body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Replace attributes for a model instance and persist it into the data source.
*
* @param id Model id
* @param data Model instance data
*/
public notificationReplaceByIdPostNotificationsidReplaceWithHttpInfo(id: string, data?: Notification, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/Notifications/${id}/replace'
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling notificationReplaceByIdPostNotificationsidReplace.');
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Replace attributes for a model instance and persist it into the data source.
*
* @param id Model id
* @param data Model instance data
*/
public notificationReplaceByIdPutNotificationsidWithHttpInfo(id: string, data?: Notification, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/Notifications/${id}'
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling notificationReplaceByIdPutNotificationsid.');
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Put,
headers: headers,
body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Replace an existing model instance or insert a new one into the data source.
*
* @param data Model instance data
*/
public notificationReplaceOrCreatePostNotificationsReplaceOrCreateWithHttpInfo(data?: Notification, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/Notifications/replaceOrCreate';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Replace an existing model instance or insert a new one into the data source.
*
* @param data Model instance data
*/
public notificationReplaceOrCreatePutNotificationsWithHttpInfo(data?: Notification, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/Notifications';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Put,
headers: headers,
body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Update instances of the model matched by {{where}} from the data source.
*
* @param where Criteria to match model instances
* @param data An object of model property name/value pairs
*/
public notificationUpdateAllWithHttpInfo(where?: string, data?: Notification, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/Notifications/update';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
if (where !== undefined) {
queryParameters.set('where', <any>where);
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
* Update an existing model instance or insert a new one into the data source based on the where criteria.
*
* @param where Criteria to match model instances
* @param data An object of model property name/value pairs
*/
public notificationUpsertWithWhereWithHttpInfo(where?: string, data?: Notification, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/Notifications/upsertWithWhere';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
if (where !== undefined) {
queryParameters.set('where', <any>where);
}
// to determine the Accept header
let produces: string[] = [
'application/json',
'application/xml',
'text/xml',
'application/javascript',
'text/javascript'
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
} | the_stack |
import CustomError = require("./Error");
import utils = require("./utils");
import Internal = require("./Internal");
import {Document, DocumentObjectFromSchemaSettings} from "./Document";
import {Model, ModelIndexes} from "./Model";
import {DynamoDB} from "aws-sdk";
import {ModelType, ObjectType} from "./General";
// TODO: the interfaces below are so similar, we should consider combining them into one. We also do a lot of `DynamoDBTypeResult | DynamoDBSetTypeResult` in the code base.
export interface DynamoDBSetTypeResult {
name: string;
dynamicName?: (() => string);
dynamodbType: string; // TODO: This should probably be an enum
isOfType: (value: ValueType, type?: "toDynamo" | "fromDynamo", settings?: Partial<DocumentObjectFromSchemaSettings>) => boolean;
isSet: true;
customType?: any;
typeSettings?: AttributeDefinitionTypeSettings;
toDynamo: (val: GeneralValueType[]) => SetValueType;
fromDynamo: (val: SetValueType) => Set<ValueType>;
}
export interface DynamoDBTypeResult {
name: string;
dynamicName?: (() => string);
dynamodbType: string | string[]; // TODO: This should probably be an enum
isOfType: (value: ValueType) => {value: ValueType; type: string};
isSet: false;
customType?: any;
typeSettings?: AttributeDefinitionTypeSettings;
nestedType: boolean;
set?: DynamoDBSetTypeResult;
}
interface DynamoDBTypeCreationObject {
name: string;
dynamicName?: ((typeSettings?: AttributeDefinitionTypeSettings) => string);
dynamodbType: string | string[] | DynamoDBType | ((typeSettings: AttributeDefinitionTypeSettings) => string | string[]);
set?: boolean | ((typeSettings?: AttributeDefinitionTypeSettings) => boolean);
jsType: any;
nestedType?: boolean;
customType?: {functions: (typeSettings: AttributeDefinitionTypeSettings) => {toDynamo?: (val: ValueType) => ValueType; fromDynamo?: (val: ValueType) => ValueType; isOfType: (val: ValueType, type: "toDynamo" | "fromDynamo") => boolean}};
customDynamoName?: string | ((typeSettings?: AttributeDefinitionTypeSettings) => string);
}
class DynamoDBType implements DynamoDBTypeCreationObject {
// TODO: since the code below will always be the exact same as DynamoDBTypeCreationObject we should see if there is a way to make it more DRY and not repeat it
name: string;
dynamicName?: ((typeSettings?: AttributeDefinitionTypeSettings) => string);
dynamodbType: string | string[] | DynamoDBType | ((typeSettings: AttributeDefinitionTypeSettings) => string | string[]);
set?: boolean | ((typeSettings?: AttributeDefinitionTypeSettings) => boolean);
jsType: any;
nestedType?: boolean;
customType?: {functions: (typeSettings?: AttributeDefinitionTypeSettings) => {toDynamo: (val: ValueType) => ValueType; fromDynamo: (val: ValueType) => ValueType; isOfType: (val: ValueType, type: "toDynamo" | "fromDynamo") => boolean}};
customDynamoName?: string | ((typeSettings?: AttributeDefinitionTypeSettings) => string);
constructor (obj: DynamoDBTypeCreationObject) {
Object.keys(obj).forEach((key) => {
this[key] = obj[key];
});
}
result (typeSettings?: AttributeDefinitionTypeSettings): DynamoDBTypeResult {
// Can't use variable below to check type, see TypeScript issue link below for more information
// https://github.com/microsoft/TypeScript/issues/37855
// const isSubType = this.dynamodbType instanceof DynamoDBType; // Represents underlying DynamoDB type for custom types
const type = this.dynamodbType instanceof DynamoDBType ? this.dynamodbType : this;
const dynamodbType: string | string[] = ((): string | string[] => {
if (this.dynamodbType instanceof DynamoDBType) {
return this.dynamodbType.dynamodbType as string;
} else if (typeof this.dynamodbType === "function") {
return this.dynamodbType(typeSettings);
} else {
return this.dynamodbType;
}
})();
const result: DynamoDBTypeResult = {
"name": this.name,
dynamodbType,
"nestedType": this.nestedType,
"isOfType": this.jsType.func ? (val) => this.jsType.func(val, typeSettings) : (val): {value: ValueType; type: string} => {
return [{"value": this.jsType, "type": "main"}, {"value": this.dynamodbType instanceof DynamoDBType ? type.jsType : null, "type": "underlying"}].filter((a) => Boolean(a.value)).find((jsType) => typeof jsType.value === "string" ? typeof val === jsType.value : val instanceof jsType.value);
},
"isSet": false,
typeSettings
};
if (this.dynamicName) {
result.dynamicName = (): string => this.dynamicName(typeSettings);
}
if (this.customType) {
const functions = this.customType.functions(typeSettings);
result.customType = {
...this.customType,
functions
};
}
const isSetAllowed = typeof type.set === "function" ? type.set(typeSettings) : type.set;
if (isSetAllowed) {
let typeName;
if (type.customDynamoName) {
typeName = typeof type.customDynamoName === "function" ? type.customDynamoName(typeSettings) : type.customDynamoName;
} else {
typeName = type.name;
}
result.set = {
"name": `${this.name} Set`,
"isSet": true,
"dynamodbType": `${dynamodbType}S`,
"isOfType": (val: ValueType, type: "toDynamo" | "fromDynamo", settings: Partial<DocumentObjectFromSchemaSettings> = {}): boolean => {
if (type === "toDynamo") {
return !settings.saveUnknown && Array.isArray(val) && val.every((subValue) => result.isOfType(subValue)) || val instanceof Set && [...val].every((subValue) => result.isOfType(subValue));
} else {
const setVal = val as SetValueType; // TODO: Probably bad practice here, should figure out how to do this better.
return setVal.wrapperName === "Set" && setVal.type === typeName && Array.isArray(setVal.values);
}
},
"toDynamo": (val: GeneralValueType[]): SetValueType => ({"wrapperName": "Set", "type": typeName, "values": [...val]}),
"fromDynamo": (val: SetValueType): Set<ValueType> => new Set(val.values),
typeSettings
};
if (this.dynamicName) {
result.set.dynamicName = (): string => `${this.dynamicName(typeSettings)} Set`;
}
if (this.customType) {
result.set.customType = {
"functions": {
"toDynamo": (val: GeneralValueType[]): ValueType[] => val.map(result.customType.functions.toDynamo),
"fromDynamo": (val: SetValueType): {values: ValueType} => ({...val, "values": val.values.map(result.customType.functions.fromDynamo)}),
"isOfType": (val: ValueType, type: "toDynamo" | "fromDynamo"): boolean => {
if (type === "toDynamo") {
return Array.isArray(val) && val.every((item) => result.customType.functions.isOfType(item, type));
} else {
const setVal = val as SetValueType; // TODO: Probably bad practice here, should figure out how to do this better.
return setVal.wrapperName === "Set" && setVal.type === typeName && Array.isArray(setVal.values);
}
}
}
};
}
}
return result;
}
}
const attributeTypesMain: DynamoDBType[] = ((): DynamoDBType[] => {
const numberType = new DynamoDBType({"name": "Number", "dynamodbType": "N", "set": true, "jsType": "number"});
const stringType = new DynamoDBType({"name": "String", "dynamodbType": "S", "set": true, "jsType": "string"});
const booleanType = new DynamoDBType({"name": "Boolean", "dynamodbType": "BOOL", "jsType": "boolean"});
return [
new DynamoDBType({"name": "Null", "dynamodbType": "NULL", "set": false, "jsType": {"func": (val): boolean => val === null}}),
new DynamoDBType({"name": "Buffer", "dynamodbType": "B", "set": true, "jsType": Buffer, "customDynamoName": "Binary"}),
booleanType,
new DynamoDBType({"name": "Array", "dynamodbType": "L", "jsType": {"func": Array.isArray}, "nestedType": true}),
new DynamoDBType({"name": "Object", "dynamodbType": "M", "jsType": {"func": (val): boolean => Boolean(val) && val.constructor === Object && (val.wrapperName !== "Set" || Object.keys(val).length !== 3 || !val.type || !val.values)}, "nestedType": true}),
numberType,
stringType,
new DynamoDBType({"name": "Date", "dynamodbType": numberType, "customType": {
"functions": (typeSettings: AttributeDefinitionTypeSettings): {toDynamo: (val: Date) => number; fromDynamo: (val: number) => Date; isOfType: (val: Date, type: "toDynamo" | "fromDynamo") => boolean} => ({
"toDynamo": (val: Date): number => {
if (typeSettings.storage === "seconds") {
return Math.round(val.getTime() / 1000);
} else {
return val.getTime();
}
},
"fromDynamo": (val: number): Date => {
if (typeSettings.storage === "seconds") {
return new Date(val * 1000);
} else {
return new Date(val);
}
},
"isOfType": (val: Date, type: "toDynamo" | "fromDynamo"): boolean => {
return type === "toDynamo" ? val instanceof Date : typeof val === "number";
}
})
}, "jsType": Date}),
new DynamoDBType({"name": "Combine", "dynamodbType": stringType, "set": false, "jsType": String}),
new DynamoDBType({"name": "Constant", "dynamicName": (typeSettings?: AttributeDefinitionTypeSettings): string => {
return `constant ${typeof typeSettings.value} (${typeSettings.value})`;
}, "customType": {
"functions": (typeSettings: AttributeDefinitionTypeSettings): {isOfType: (val: string | boolean | number, type: "toDynamo" | "fromDynamo") => boolean} => ({
"isOfType": (val: string | boolean | number): boolean => typeSettings.value === val
})
}, "jsType": {"func": (val, typeSettings): boolean => val === typeSettings.value}, "dynamodbType": (typeSettings?: AttributeDefinitionTypeSettings): string | string[] => {
switch (typeof typeSettings.value) {
case "string":
return stringType.dynamodbType as any;
case "boolean":
return booleanType.dynamodbType as any;
case "number":
return numberType.dynamodbType as any;
}
}}),
new DynamoDBType({"name": "Model", "customDynamoName": (typeSettings?: AttributeDefinitionTypeSettings): string => {
const model = typeSettings.model.Model;
const hashKey = model.getHashKey();
const typeDetails: DynamoDBTypeResult | DynamoDBSetTypeResult = model.schemas[0].getAttributeTypeDetails(hashKey) as DynamoDBTypeResult | DynamoDBSetTypeResult; // This has no potiental of being an array because a hashKey is not allowed to have multiple type options
return typeDetails.name;
}, "dynamicName": (typeSettings?: AttributeDefinitionTypeSettings): string => typeSettings.model.Model.name, "dynamodbType": (typeSettings?: AttributeDefinitionTypeSettings): string | string[] => {
const model = typeSettings.model.Model;
const hashKey = model.getHashKey();
const rangeKey = model.getRangeKey();
return rangeKey ? "M" : model.schemas[0].getAttributeType(hashKey);
}, "set": (typeSettings?: AttributeDefinitionTypeSettings): boolean => {
return !typeSettings.model.Model.getRangeKey();
}, "jsType": {"func": (val): boolean => val.prototype instanceof Document}, "customType": {
"functions": (typeSettings?: AttributeDefinitionTypeSettings): {toDynamo: (val: any) => any; fromDynamo: (val: any) => any; isOfType: (val: any, type: "toDynamo" | "fromDynamo") => boolean} => ({
"toDynamo": (val: any): any => {
const model = typeSettings.model.Model;
const hashKey = model.getHashKey();
const rangeKey = model.getRangeKey();
if (rangeKey) {
return {
[hashKey]: val[hashKey],
[rangeKey]: val[rangeKey]
};
} else {
return val[hashKey] ?? val;
}
},
"fromDynamo": (val: any): any => val,
"isOfType": (val: any, type: "toDynamo" | "fromDynamo"): boolean => {
const model = typeSettings.model.Model;
const hashKey = model.getHashKey();
const rangeKey = model.getRangeKey();
if (rangeKey) {
return typeof val === "object" && val[hashKey] && val[rangeKey];
} else {
return utils.dynamoose.getValueTypeCheckResult(model.schemas[0], val[hashKey] ?? val, hashKey, {type}, {}).isValidType;
}
}
})
}})
];
})();
const attributeTypes: (DynamoDBTypeResult | DynamoDBSetTypeResult)[] = utils.array_flatten(attributeTypesMain.filter((checkType) => !checkType.customType).map((checkType) => checkType.result()).map((a) => [a, a.set])).filter((a) => Boolean(a));
type SetValueType = {wrapperName: "Set"; values: ValueType[]; type: string /* TODO: should probably make this an enum */};
type GeneralValueType = string | boolean | number | Buffer | Date;
export type ValueType = GeneralValueType | {[key: string]: ValueType} | ValueType[] | SetValueType;
type AttributeType = string | StringConstructor | BooleanConstructor | NumberConstructor | typeof Buffer | DateConstructor | ObjectConstructor | ArrayConstructor | SetConstructor | symbol | Schema | ModelType<Document>;
export interface TimestampObject {
createdAt?: string | string[];
updatedAt?: string | string[];
}
interface SchemaSettings {
timestamps?: boolean | TimestampObject;
saveUnknown?: boolean | string[];
}
interface IndexDefinition {
name?: string;
global?: boolean;
rangeKey?: string;
project?: boolean | string[];
throughput?: "ON_DEMAND" | number | {read: number; write: number};
}
interface AttributeDefinitionTypeSettings {
storage?: "miliseconds" | "seconds";
model?: ModelType<Document>;
attributes?: string[];
seperator?: string;
value?: string | boolean | number;
}
interface AttributeDefinition {
type: AttributeType | AttributeType[] | {value: DateConstructor; settings?: AttributeDefinitionTypeSettings} | {value: AttributeType | AttributeType[]}; // TODO add support for this being an object
schema?: AttributeType | AttributeType[] | AttributeDefinition | AttributeDefinition[] | SchemaDefinition | SchemaDefinition[];
default?: ValueType | (() => ValueType);
forceDefault?: boolean;
validate?: ValueType | RegExp | ((value: ValueType) => boolean);
required?: boolean;
enum?: ValueType[];
get?: ((value: ValueType) => ValueType);
set?: ((value: ValueType) => ValueType);
index?: boolean | IndexDefinition | IndexDefinition[];
hashKey?: boolean;
rangeKey?: boolean;
}
export interface SchemaDefinition {
[attribute: string]: AttributeType | AttributeType[] | AttributeDefinition | AttributeDefinition[];
}
interface SchemaGetAttributeTypeSettings {
unknownAttributeAllowed: boolean;
}
interface SchemaGetAttributeSettingValue {
returnFunction: boolean;
typeIndexOptionMap?: any;
}
export class Schema {
settings: SchemaSettings;
schemaObject: SchemaDefinition;
attributes: (object?: ObjectType) => string[];
async getCreateTableAttributeParams (model: Model<Document>): Promise<Pick<DynamoDB.CreateTableInput, "AttributeDefinitions" | "KeySchema" | "GlobalSecondaryIndexes" | "LocalSecondaryIndexes">> {
const hashKey = this.getHashKey();
const AttributeDefinitions = [
{
"AttributeName": hashKey,
"AttributeType": this.getSingleAttributeType(hashKey)
}
];
const AttributeDefinitionsNames = [hashKey];
const KeySchema = [
{
"AttributeName": hashKey,
"KeyType": "HASH"
}
];
const rangeKey = this.getRangeKey();
if (rangeKey) {
AttributeDefinitions.push({
"AttributeName": rangeKey,
"AttributeType": this.getSingleAttributeType(rangeKey)
});
AttributeDefinitionsNames.push(rangeKey);
KeySchema.push({
"AttributeName": rangeKey,
"KeyType": "RANGE"
});
}
utils.array_flatten(await Promise.all([this.getIndexAttributes(), this.getIndexRangeKeyAttributes()])).map((obj) => obj.attribute).forEach((index) => {
if (AttributeDefinitionsNames.includes(index)) {
return;
}
AttributeDefinitionsNames.push(index);
AttributeDefinitions.push({
"AttributeName": index,
"AttributeType": this.getSingleAttributeType(index)
});
});
const response: any = {
AttributeDefinitions,
KeySchema
};
const {GlobalSecondaryIndexes, LocalSecondaryIndexes} = await this.getIndexes(model);
if (GlobalSecondaryIndexes) {
response.GlobalSecondaryIndexes = GlobalSecondaryIndexes;
}
if (LocalSecondaryIndexes) {
response.LocalSecondaryIndexes = LocalSecondaryIndexes;
}
return response;
}
// This function has the same behavior as `getAttributeType` except if the schema has multiple types, it will throw an error. This is useful for attribute definitions and keys for when you are only allowed to have one type for an attribute
private getSingleAttributeType (key: string, value?: ValueType, settings?: SchemaGetAttributeTypeSettings): string {
const attributeType = this.getAttributeType(key, value, settings);
if (Array.isArray(attributeType)) {
throw new CustomError.InvalidParameter(`You can not have multiple types for attribute definition: ${key}.`);
}
return attributeType;
}
getAttributeType (key: string, value?: ValueType, settings?: SchemaGetAttributeTypeSettings): string | string[] {
try {
const typeDetails = this.getAttributeTypeDetails(key);
return Array.isArray(typeDetails) ? (typeDetails as any).map((detail) => detail.dynamodbType) : typeDetails.dynamodbType;
} catch (e) {
if (settings?.unknownAttributeAllowed && e.message === `Invalid Attribute: ${key}` && value) {
return Object.keys((Document as any).objectToDynamo(value, {"type": "value"}))[0];
} else {
throw e;
}
}
}
static attributeTypes = {
"findDynamoDBType": (type): DynamoDBTypeResult | DynamoDBSetTypeResult => attributeTypes.find((checkType) => checkType.dynamodbType === type),
"findTypeForValue": (...args): DynamoDBTypeResult | DynamoDBSetTypeResult => attributeTypes.find((checkType) => (checkType.isOfType as any)(...args))
};
getHashKey: () => string;
getRangeKey: () => string | void;
// This function will take in an attribute and value, and returns the default value if it should be applied.
async defaultCheck (key: string, value: ValueType, settings: any): Promise<ValueType | void> {
const isValueUndefined = typeof value === "undefined" || value === null;
if (settings.defaults && isValueUndefined || settings.forceDefault && await this.getAttributeSettingValue("forceDefault", key)) {
const defaultValueRaw = await this.getAttributeSettingValue("default", key);
let hasMultipleTypes;
try {
hasMultipleTypes = Array.isArray(this.getAttributeType(key));
} catch (e) {
hasMultipleTypes = false;
}
const defaultValue = Array.isArray(defaultValueRaw) && hasMultipleTypes ? defaultValueRaw[0] : defaultValueRaw;
const isDefaultValueUndefined = typeof defaultValue === "undefined" || defaultValue === null;
if (!isDefaultValueUndefined) {
return defaultValue;
}
}
}
requiredCheck: (key: string, value: ValueType) => Promise<void>;
getAttributeSettingValue (setting: string, key: string, settings: SchemaGetAttributeSettingValue = {"returnFunction": false}): any {
function func (attributeValue): any {
const defaultPropertyValue = (attributeValue || {})[setting];
return typeof defaultPropertyValue === "function" && !settings.returnFunction ? defaultPropertyValue() : defaultPropertyValue;
}
const attributeValue = this.getAttributeValue(key, {"typeIndexOptionMap": settings.typeIndexOptionMap});
if (Array.isArray(attributeValue)) {
return attributeValue.map(func);
} else {
return func(attributeValue);
}
}
getTypePaths (object: ObjectType, settings: { type: "toDynamo" | "fromDynamo"; previousKey?: string; includeAllProperties?: boolean } = {"type": "toDynamo"}): ObjectType {
return Object.entries(object).reduce((result, entry) => {
const [key, value] = entry;
const fullKey = [settings.previousKey, key].filter((a) => Boolean(a)).join(".");
let typeCheckResult;
try {
typeCheckResult = utils.dynamoose.getValueTypeCheckResult(this, value, fullKey, settings, {});
} catch (e) {
if (result && settings.includeAllProperties) {
result[fullKey] = {
"index": 0,
"matchCorrectness": 0.5,
"entryCorrectness": [0.5]
};
}
return result;
}
const {typeDetails, matchedTypeDetailsIndex, matchedTypeDetailsIndexes} = typeCheckResult;
const hasMultipleTypes = Array.isArray(typeDetails);
const isObject = typeof value === "object" && !(value instanceof Buffer) && value !== null;
if (hasMultipleTypes) {
if (matchedTypeDetailsIndexes.length > 1 && isObject) {
result[fullKey] = matchedTypeDetailsIndexes.map((index: number) => {
const entryCorrectness = utils.object.entries(value).map((entry) => {
const [subKey, subValue] = entry;
try {
const {isValidType} = utils.dynamoose.getValueTypeCheckResult(this, subValue, `${fullKey}.${subKey}`, settings, {"typeIndexOptionMap": {[fullKey]: index}});
return isValidType ? 1 : 0;
} catch (e) {
return 0.5;
}
});
return {
index,
// 1 = full match
// 0.5 = attributes don't exist
// 0 = types don't match
"matchCorrectness": Math.min(...entryCorrectness),
entryCorrectness
};
}).sort((a, b) => {
if (a.matchCorrectness === b.matchCorrectness) {
return b.entryCorrectness.reduce((a: number, b: number) => a + b, 0) - a.entryCorrectness.reduce((a: number, b: number) => a + b, 0);
} else {
return b.matchCorrectness - a.matchCorrectness;
}
}).map((a) => a.index)[0];
}
if (result[fullKey] === undefined) {
result[fullKey] = matchedTypeDetailsIndex;
}
} else if (settings.includeAllProperties) {
const matchCorrectness: number = typeCheckResult.isValidType ? 1 : 0;
result[fullKey] = {
"index": 0,
matchCorrectness,
"entryCorrectness": [matchCorrectness]
};
}
if (isObject) {
result = {...result, ...this.getTypePaths(value, {...settings, "previousKey": fullKey})};
}
return result;
}, {});
}
getIndexAttributes: () => Promise<{ index: IndexDefinition; attribute: string }[]>;
getSettingValue: (setting: string) => any;
getAttributeTypeDetails: (key: string, settings?: { standardKey?: boolean; typeIndexOptionMap?: {} }) => DynamoDBTypeResult | DynamoDBSetTypeResult | DynamoDBTypeResult[] | DynamoDBSetTypeResult[];
getAttributeValue: (key: string, settings?: { standardKey?: boolean; typeIndexOptionMap?: {} }) => AttributeDefinition;
getIndexes: (model: Model<Document>) => Promise<ModelIndexes>;
getIndexRangeKeyAttributes: () => Promise<{ attribute: string }[]>;
constructor (object: SchemaDefinition, settings: SchemaSettings = {}) {
if (!object || typeof object !== "object" || Array.isArray(object)) {
throw new CustomError.InvalidParameterType("Schema initalization parameter must be an object.");
}
if (Object.keys(object).length === 0) {
throw new CustomError.InvalidParameter("Schema initalization parameter must not be an empty object.");
}
if (settings.timestamps === true) {
settings.timestamps = {
"createdAt": "createdAt",
"updatedAt": "updatedAt"
};
}
if (settings.timestamps) {
const createdAtArray = Array.isArray(settings.timestamps.createdAt) ? settings.timestamps.createdAt : [settings.timestamps.createdAt];
const updatedAtArray = Array.isArray(settings.timestamps.updatedAt) ? settings.timestamps.updatedAt : [settings.timestamps.updatedAt];
[...createdAtArray, ...updatedAtArray].forEach((prop) => {
if (object[prop]) {
throw new CustomError.InvalidParameter("Timestamp attributes must not be defined in schema.");
}
object[prop] = Date;
});
}
let parsedSettings = {...settings};
const parsedObject = {...object};
utils.object.entries(parsedObject).filter((entry) => entry[1] instanceof Schema).forEach((entry) => {
const [key, value] = entry;
let newValue = {
"type": Object,
"schema": (value as any).schemaObject
};
if (key.endsWith(".schema")) {
newValue = (value as any).schemaObject;
}
const subSettings = {...(value as any).settings};
Object.entries(subSettings).forEach((entry) => {
const [settingsKey, settingsValue] = entry;
switch (settingsKey) {
case "saveUnknown":
subSettings[settingsKey] = typeof subSettings[settingsKey] === "boolean" ? [`${key}.**`] : (settingsValue as any).map((val) => `${key}.${val}`);
break;
case "timestamps":
subSettings[settingsKey] = Object.entries(subSettings[settingsKey]).reduce((obj, entity) => {
const [subKey, subValue] = entity;
obj[subKey] = Array.isArray(subValue) ? subValue.map((subValue) => `${key}.${subValue}`) : `${key}.${subValue}`;
return obj;
}, {});
break;
}
});
parsedSettings = utils.merge_objects.main({"combineMethod": "array_merge_new_arrray"})(parsedSettings, subSettings);
utils.object.set(parsedObject, key, newValue);
});
utils.object.entries(parsedObject).forEach((entry) => {
const key = entry[0];
const value = entry[1] as any;
if (!key.endsWith(".type") && !key.endsWith(".0")) {
if (value && value.Model && value.Model instanceof Model) {
utils.object.set(parsedObject, key, {"type": value});
} else if (value && Array.isArray(value)) {
value.forEach((item, index) => {
if (item && item.Model && item.Model instanceof Model) {
utils.object.set(parsedObject, `${key}.${index}`, {"type": item});
}
});
}
}
});
// Anytime `this.schemaObject` is modified, `this[internalCache].attributes` must be set to undefined or null
this.schemaObject = parsedObject;
this.settings = parsedSettings;
const checkAttributeNameDots = (object: SchemaDefinition/*, existingKey = ""*/): void => {
Object.keys(object).forEach((key) => {
if (key.includes(".")) {
throw new CustomError.InvalidParameter("Attributes must not contain dots.");
}
// TODO: lots of `as` statements in the two lines below. We should clean that up.
if (typeof object[key] === "object" && object[key] !== null && (object[key] as AttributeDefinition).schema) {
checkAttributeNameDots((object[key] as AttributeDefinition).schema as SchemaDefinition/*, key*/);
}
});
};
checkAttributeNameDots(this.schemaObject);
const checkMultipleArraySchemaElements = (key: string): void => {
let attributeType: string[] = [];
try {
const tmpAttributeType = this.getAttributeType(key);
attributeType = Array.isArray(tmpAttributeType) ? tmpAttributeType : [tmpAttributeType];
} catch (e) {} // eslint-disable-line no-empty
if (attributeType.some((type) => type === "L") && ((this.getAttributeValue(key).schema || []) as any).length > 1) {
throw new CustomError.InvalidParameter("You must only pass one element into schema array.");
}
};
this.attributes().forEach((key) => checkMultipleArraySchemaElements(key));
const hashrangeKeys = this.attributes().reduce((val, key) => {
const hashKey = this.getAttributeSettingValue("hashKey", key);
const rangeKey = this.getAttributeSettingValue("rangeKey", key);
const isHashKey = Array.isArray(hashKey) ? hashKey.every((item) => Boolean(item)) : hashKey;
const isRangeKey = Array.isArray(rangeKey) ? rangeKey.every((item) => Boolean(item)) : rangeKey;
if (isHashKey) {
val.hashKeys.push(key);
}
if (isRangeKey) {
val.rangeKeys.push(key);
}
if (isHashKey && isRangeKey) {
val.hashAndRangeKeyAttributes.push(key);
}
return val;
}, {"hashKeys": [], "rangeKeys": [], "hashAndRangeKeyAttributes": []});
const keyTypes = ["hashKey", "rangeKey"];
keyTypes.forEach((keyType) => {
if (hashrangeKeys[`${keyType}s`].length > 1) {
throw new CustomError.InvalidParameter(`Only one ${keyType} allowed per schema.`);
}
if (hashrangeKeys[`${keyType}s`].find((key) => key.includes("."))) {
throw new CustomError.InvalidParameter(`${keyType} must be at root object and not nested in object or array.`);
}
});
if (hashrangeKeys.hashAndRangeKeyAttributes.length > 0) {
throw new CustomError.InvalidParameter(`Attribute ${hashrangeKeys.hashAndRangeKeyAttributes[0]} must not be both hashKey and rangeKey`);
}
this.attributes().forEach((key) => {
const attributeSettingValue = this.getAttributeSettingValue("index", key);
if (key.includes(".") && (Array.isArray(attributeSettingValue) ? attributeSettingValue.some((singleValue) => Boolean(singleValue)) : attributeSettingValue)) {
throw new CustomError.InvalidParameter("Index must be at root object and not nested in object or array.");
}
});
}
}
// TODO: in the two functions below I don't think we should be using as. We should try to clean that up.
Schema.prototype.getHashKey = function (this: Schema): string {
return Object.keys(this.schemaObject).find((key) => (this.schemaObject[key] as AttributeDefinition).hashKey) || Object.keys(this.schemaObject)[0];
};
Schema.prototype.getRangeKey = function (this: Schema): string | void {
return Object.keys(this.schemaObject).find((key) => (this.schemaObject[key] as AttributeDefinition).rangeKey);
};
// This function will take in an attribute and value, and throw an error if the property is required and the value is undefined or null.
Schema.prototype.requiredCheck = async function (this: Schema, key: string, value: ValueType): Promise<void> {
const isRequired = await this.getAttributeSettingValue("required", key);
if ((typeof value === "undefined" || value === null) && (Array.isArray(isRequired) ? isRequired.some((val) => Boolean(val)) : isRequired)) {
throw new CustomError.ValidationError(`${key} is a required property but has no value when trying to save document`);
}
};
Schema.prototype.getIndexAttributes = async function (this: Schema): Promise<{index: IndexDefinition; attribute: string}[]> {
return (await Promise.all(this.attributes()
.map(async (attribute: string) => ({
"index": await this.getAttributeSettingValue("index", attribute) as IndexDefinition,
attribute
}))
))
.filter((obj) => Array.isArray(obj.index) ? obj.index.some((index) => Boolean(index)) : obj.index)
.reduce((accumulator, currentValue) => {
if (Array.isArray(currentValue.index)) {
currentValue.index.forEach((currentIndex) => {
accumulator.push({
...currentValue,
"index": currentIndex
});
});
} else {
accumulator.push(currentValue);
}
return accumulator;
}, []);
};
Schema.prototype.getIndexRangeKeyAttributes = async function (this: Schema): Promise<{attribute: string}[]> {
const indexes: ({index: IndexDefinition; attribute: string})[] = await this.getIndexAttributes();
return indexes.map((index) => index.index.rangeKey).filter((a) => Boolean(a)).map((a) => ({"attribute": a}));
};
export interface TableIndex {
KeySchema: ({AttributeName: string; KeyType: "HASH" | "RANGE"})[];
}
export interface IndexItem {
IndexName: string;
KeySchema: ({AttributeName: string; KeyType: "HASH" | "RANGE"})[];
Projection: {ProjectionType: "KEYS_ONLY" | "INCLUDE" | "ALL"; NonKeyAttributes?: string[]};
ProvisionedThroughput?: {"ReadCapacityUnits": number; "WriteCapacityUnits": number}; // TODO: this was copied from get_provisioned_throughput. We should change this to be an actual interface
}
Schema.prototype.getIndexes = async function (this: Schema, model: Model<Document>): Promise<ModelIndexes> {
const indexes: ModelIndexes = (await this.getIndexAttributes()).reduce((accumulator, currentValue) => {
const indexValue = currentValue.index;
const attributeValue = currentValue.attribute;
const dynamoIndexObject: IndexItem = {
"IndexName": indexValue.name || `${attributeValue}${indexValue.global ? "GlobalIndex" : "LocalIndex"}`,
"KeySchema": [],
"Projection": {"ProjectionType": "KEYS_ONLY"}
};
if (indexValue.project || typeof indexValue.project === "undefined" || indexValue.project === null) {
dynamoIndexObject.Projection = Array.isArray(indexValue.project) ? {"ProjectionType": "INCLUDE", "NonKeyAttributes": indexValue.project} : {"ProjectionType": "ALL"};
}
if (indexValue.global) {
dynamoIndexObject.KeySchema.push({"AttributeName": attributeValue, "KeyType": "HASH"});
if (indexValue.rangeKey) {
dynamoIndexObject.KeySchema.push({"AttributeName": indexValue.rangeKey, "KeyType": "RANGE"});
}
const throughputObject = utils.dynamoose.get_provisioned_throughput(indexValue.throughput ? indexValue : model.options.throughput === "ON_DEMAND" ? {} : model.options);
// TODO: fix up the two lines below. Using too many `as` statements.
if ((throughputObject as {"ProvisionedThroughput": {"ReadCapacityUnits": number; "WriteCapacityUnits": number}}).ProvisionedThroughput) {
dynamoIndexObject.ProvisionedThroughput = (throughputObject as {"ProvisionedThroughput": {"ReadCapacityUnits": number; "WriteCapacityUnits": number}}).ProvisionedThroughput;
}
} else {
dynamoIndexObject.KeySchema.push({"AttributeName": this.getHashKey(), "KeyType": "HASH"});
dynamoIndexObject.KeySchema.push({"AttributeName": attributeValue, "KeyType": "RANGE"});
}
const accumulatorKey = indexValue.global ? "GlobalSecondaryIndexes" : "LocalSecondaryIndexes";
if (!accumulator[accumulatorKey]) {
accumulator[accumulatorKey] = [];
}
accumulator[accumulatorKey].push(dynamoIndexObject);
return accumulator;
}, {});
indexes.TableIndex = {"KeySchema": [{"AttributeName": this.getHashKey(), "KeyType": "HASH"}]};
const rangeKey = this.getRangeKey();
if (rangeKey) {
indexes.TableIndex.KeySchema.push({"AttributeName": rangeKey, "KeyType": "RANGE"});
}
return indexes;
};
Schema.prototype.getSettingValue = function (this: Schema, setting: string): any {
return this.settings[setting];
};
function attributesAction (this: Schema, object?: ObjectType): string[] {
const typePaths = object && this.getTypePaths(object);
const main = (object: SchemaDefinition, existingKey = ""): string[] => {
return Object.keys(object).reduce((accumulator: string[], key) => {
const keyWithExisting = `${existingKey ? `${existingKey}.` : ""}${key}`;
accumulator.push(keyWithExisting);
let attributeType: string[];
try {
const tmpAttributeType = this.getAttributeType(keyWithExisting);
attributeType = Array.isArray(tmpAttributeType) ? tmpAttributeType : [tmpAttributeType];
} catch (e) {} // eslint-disable-line no-empty
// TODO: using too many `as` statements in the few lines below. Clean that up.
function recursive (type, arrayTypeIndex): void {
if ((type === "M" || type === "L") && ((object[key][arrayTypeIndex] || object[key]) as AttributeDefinition).schema) {
accumulator.push(...main(((object[key][arrayTypeIndex] || object[key]) as AttributeDefinition).schema as SchemaDefinition, keyWithExisting));
}
}
if (attributeType) {
if (typePaths && typePaths[keyWithExisting] !== undefined) {
const index = typePaths[keyWithExisting];
const type = attributeType[index];
recursive(type, index);
} else {
attributeType.forEach(recursive);
}
}
// ------------------------------
return accumulator;
}, []);
};
return main(this.schemaObject);
}
Schema.prototype.attributes = function (this: Schema, object?: ObjectType): string[] {
return attributesAction.call(this, object);
};
Schema.prototype.getAttributeValue = function (this: Schema, key: string, settings?: {standardKey?: boolean; typeIndexOptionMap?: {}}): AttributeDefinition {
const previousKeyParts = [];
let result = (settings?.standardKey ? key : key.replace(/\.\d+/gu, ".0")).split(".").reduce((result, part) => {
if (Array.isArray(result)) {
const predefinedIndex = settings && settings.typeIndexOptionMap && settings.typeIndexOptionMap[previousKeyParts.join(".")];
if (predefinedIndex !== undefined) {
result = result[predefinedIndex];
} else {
result = result.find((item) => item.schema && item.schema[part]);
}
}
previousKeyParts.push(part);
return utils.object.get(result.schema, part);
}, {"schema": this.schemaObject} as any);
if (Array.isArray(result)) {
const predefinedIndex = settings && settings.typeIndexOptionMap && settings.typeIndexOptionMap[previousKeyParts.join(".")];
if (predefinedIndex !== undefined) {
result = result[predefinedIndex];
}
}
return result;
};
function retrieveTypeInfo (type: string, isSet: boolean, key: string, typeSettings: AttributeDefinitionTypeSettings): DynamoDBTypeResult | DynamoDBSetTypeResult {
const foundType = attributeTypesMain.find((checkType) => checkType.name.toLowerCase() === type.toLowerCase());
if (!foundType) {
throw new CustomError.InvalidType(`${key} contains an invalid type: ${type}`);
}
const parentType = foundType.result(typeSettings);
if (!parentType.set && isSet) {
throw new CustomError.InvalidType(`${key} with type: ${type} is not allowed to be a set`);
}
return isSet ? parentType.set : parentType;
}
// TODO: using too many `as` statements in the function below. We should clean this up.
Schema.prototype.getAttributeTypeDetails = function (this: Schema, key: string, settings: {standardKey?: boolean; typeIndexOptionMap?: {}} = {}): DynamoDBTypeResult | DynamoDBSetTypeResult | DynamoDBTypeResult[] | DynamoDBSetTypeResult[] {
const standardKey = settings.standardKey ? key : key.replace(/\.\d+/gu, ".0");
const val = this.getAttributeValue(standardKey, {...settings, "standardKey": true});
if (typeof val === "undefined") {
throw new CustomError.UnknownAttribute(`Invalid Attribute: ${key}`);
}
let typeVal = typeof val === "object" && !Array.isArray(val) && val.type ? val.type : val;
let typeSettings: AttributeDefinitionTypeSettings = {};
if (typeof typeVal === "object" && !Array.isArray(typeVal)) {
typeSettings = (typeVal as {value: DateConstructor; settings?: AttributeDefinitionTypeSettings}).settings || {};
typeVal = (typeVal as any).value;
}
const getType = (typeVal: AttributeType | AttributeDefinition): string => {
let type: string;
const isThisType = typeVal as any === Internal.Public.this;
const isNullType = typeVal as any === Internal.Public.null;
if (typeof typeVal === "function" || isThisType) {
if ((typeVal as any).prototype instanceof Document || isThisType) {
type = "model";
if (isThisType) {
typeSettings.model = {
"Model": {
"getHashKey": this.getHashKey.bind(this),
"getRangeKey": this.getRangeKey.bind(this),
"schemas": [this]
}
} as any;
} else {
typeSettings.model = typeVal as any;
}
} else {
const regexFuncName = /^Function ([^(]+)\(/iu;
[, type] = typeVal.toString().match(regexFuncName);
}
} else if (isNullType) {
type = "null";
} else {
type = typeVal as string;
}
return type;
};
const result: DynamoDBTypeResult[] | DynamoDBSetTypeResult[] = ((Array.isArray(typeVal) ? typeVal : [typeVal]) as any).map((item, index: number) => {
item = typeof item === "object" && !Array.isArray(item) && item.type ? item.type : item;
if (typeof item === "object" && !Array.isArray(item)) {
typeSettings = (item as {value: DateConstructor; settings?: AttributeDefinitionTypeSettings}).settings || {};
item = item.value;
}
let type = getType(item);
const isSet = type.toLowerCase() === "set";
if (isSet) {
let schemaValue = this.getAttributeSettingValue("schema", key);
if (Array.isArray(schemaValue[index])) {
schemaValue = schemaValue[index];
}
const subValue = schemaValue[0];
type = getType(typeof subValue === "object" && subValue.type ? subValue.type : subValue);
}
const returnObject = retrieveTypeInfo(type, isSet, key, typeSettings);
return returnObject;
});
const returnObject = result.length < 2 ? result[0] : result;
return returnObject;
}; | the_stack |
import { TreeGrid } from '../../src/treegrid/base/treegrid';
import { createGrid, destroy } from '../base/treegridutil.spec';
import { sampleData } from '../base/datasource.spec';
import { Edit } from '../../src/treegrid/actions/edit';
import { Freeze } from '../../src/treegrid/actions/freeze-column';
import { Toolbar } from '../../src/treegrid/actions/toolbar';
import { SaveEventArgs, CellEditArgs } from '@syncfusion/ej2-grids';
import { profile, inMB, getMemoryProfile } from '../common.spec';
import { Sort } from '../../src/treegrid/actions/sort';
import { isNullOrUndefined } from '@syncfusion/ej2-base';
/**
* Grid Cell Edit spec
*/
TreeGrid.Inject(Edit, Toolbar, Sort, Freeze);
describe('Cell Editing with Frozen Columns', () => {
beforeAll(() => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
});
describe('Hirarchy Frozen editing', () => {
let gridObj: TreeGrid;
let actionBegin: () => void;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
editSettings: { allowEditing: true, mode: 'Cell', allowDeleting: true, allowAdding: true, newRowPosition: 'Top' },
frozenColumns: 3,
treeColumnIndex: 1,
toolbar: ['Add', 'Edit', 'Update', 'Delete', 'Cancel', 'ExpandAll', 'CollapseAll'],
columns: [
{
field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right',
validationRules: { required: true, number: true}, width: 90
},
{ field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220 },
{ field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 210 },
{ field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd' },
{ field: 'endDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
{ field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 210 },
{ field: 'priority', headerText: 'Priority', textAlign: 'Left', width: 230 },
{ field: 'approved', headerText: 'Approved', width: 230, textAlign: 'Left' }
]
},
done
);
});
it('record double click', (done: Function) => {
gridObj.cellEdit = (args?: CellEditArgs): void => {
expect(args.columnName).toBe('taskName');
done();
};
let event: MouseEvent = new MouseEvent('dblclick', {
'view': window,
'bubbles': true,
'cancelable': true
});
gridObj.getCellFromIndex(2, 1).dispatchEvent(event);
});
it('save record', (done: Function) => {
gridObj.grid.editModule.formObj.element.getElementsByTagName('input')[0].value = 'test';
gridObj.actionComplete = (args?: any): void => {
expect(gridObj.dataSource[0].subtasks[1].taskName).toBe('test');
done();
};
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Cell Editing with Frozen Columns - cell alone refresh', () => {
let gridObj: TreeGrid;
let actionBegin: () => void;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
editSettings: { allowEditing: true, allowDeleting: true, allowAdding: true, newRowPosition: 'Top' },
frozenColumns: 3,
treeColumnIndex: 1,
toolbar: ['Add', 'Update', 'Delete', 'Cancel'],
columns: [
{
field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right',
validationRules: { required: true, number: true}, width: 90
},
{ field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220 },
{ field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 210 },
{ field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd' },
{ field: 'endDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
{ field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 210 },
{ field: 'priority', headerText: 'Priority', textAlign: 'Left', width: 230 },
{ field: 'approved', headerText: 'Approved', width: 230, textAlign: 'Left' }
]
},
done
);
});
it('cell refresh', (done: Function) => {
let event: MouseEvent = new MouseEvent('dblclick', {
'view': window,
'bubbles': true,
'cancelable': true
});
(gridObj.getCellFromIndex(1, 1) as HTMLElement).style.background = 'red';
gridObj.getCellFromIndex(2, 1).dispatchEvent(event);
gridObj.actionComplete = (args?: SaveEventArgs): void => {
expect(args.target.textContent).toBe('test');
expect((gridObj.getCellFromIndex(1, 1) as HTMLElement).style.background).toBe('red');
done();
};
gridObj.grid.editModule.formObj.element.getElementsByTagName('input')[0].value = 'test';
gridObj.getRows()[0].click();
});
it('cell refresh by toolbar update', (done: Function) => {
let event: MouseEvent = new MouseEvent('dblclick', {
'view': window,
'bubbles': true,
'cancelable': true
});
(gridObj.getCellFromIndex(1, 1) as HTMLElement).style.background = 'blue';
gridObj.getCellFromIndex(2, 1).dispatchEvent(event);
gridObj.actionComplete = (args?: SaveEventArgs): void => {
expect(args.target.textContent).toBe('test2');
expect((gridObj.getCellFromIndex(1, 1) as HTMLElement).style.background).toBe('blue');
done();
};
gridObj.grid.editModule.formObj.element.getElementsByTagName('input')[0].value = 'test2';
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Cell Editing With scroller and with Frozen Columns', () => {
let gridObj: TreeGrid;
let actionBegin: () => void;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
width: 600, height: 400,
childMapping: 'subtasks',
editSettings: { allowEditing: true, allowDeleting: true, allowAdding: true, newRowPosition: 'Top' },
frozenColumns: 3,
treeColumnIndex: 1,
toolbar: ['Add', 'Update', 'Delete', 'Cancel'],
columns: [
{
field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right',
validationRules: { required: true, number: true}, width: 90
},
{ field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220 },
{ field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 210 },
{ field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd' },
{ field: 'endDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
{ field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 210 },
{ field: 'priority', headerText: 'Priority', textAlign: 'Left', width: 230 },
{ field: 'approved', headerText: 'Approved', width: 230, textAlign: 'Left' }
]
},
done
);
});
it('cell edit', () => {
expect((<HTMLElement>gridObj.grid.element).style.width).toBe('600px');
expect((<HTMLElement>gridObj.getContent().firstChild).classList.contains('e-content')).toBeTruthy();
let event: MouseEvent = new MouseEvent('dblclick', {
'view': window,
'bubbles': true,
'cancelable': true
});
let scrollPosition: number = gridObj.getContent().firstElementChild.scrollLeft;
gridObj.getCellFromIndex(2, 1).dispatchEvent(event);
expect(gridObj.getContent().firstElementChild.scrollLeft).toEqual(scrollPosition);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
expect(gridObj.getContent().firstElementChild.scrollLeft).toEqual(scrollPosition);
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Cell edit and cancel when selection mode is set as Cell', () => {
let gridObj: TreeGrid;
let rows: Element[];
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
allowSelection: true,
selectionSettings: {mode: 'Cell'},
treeColumnIndex: 1,
editSettings: {
allowAdding: true,
allowEditing: true,
allowDeleting: true,
mode: 'Cell'
},
frozenColumns: 3,
toolbar: ['Add', 'Delete', 'Update', 'Cancel'],
columns: [
{
field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right',
validationRules: { required: true, number: true}, width: 90
},
{ field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220 },
{ field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 210 },
{ field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd' },
{ field: 'endDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
{ field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 210 },
{ field: 'priority', headerText: 'Priority', textAlign: 'Left', width: 230 },
{ field: 'approved', headerText: 'Approved', width: 230, textAlign: 'Left' }
]
},
done
);
});
it('double click on a record, cell edit and cancel',() => {
let event: MouseEvent = new MouseEvent('dblclick', {
'view': window,
'bubbles': true,
'cancelable': true
});
gridObj.getCellFromIndex(1, 1).dispatchEvent(event);
gridObj.grid.editModule.formObj.element.getElementsByTagName('input')[0].value = 'Planning completed';
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_cancel' } });
expect((gridObj.getRows()[1].getElementsByClassName('e-treecell')[0] as HTMLElement).innerText=="Plan timeline").toBe(true);
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Expand/Collpase icon testing at the time of cell edit cancel with Frozen Columns', () => {
let gridObj: TreeGrid;
let rows: Element[];
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
allowSelection: true,
selectionSettings: {mode: 'Cell'},
treeColumnIndex: 1,
editSettings: {
allowAdding: true,
allowEditing: true,
allowDeleting: true,
mode: 'Cell'
},
frozenColumns: 3,
toolbar: ['Add', 'Delete', 'Update', 'Cancel'],
columns: [
{
field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right',
validationRules: { required: true, number: true}, width: 90
},
{ field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220 },
{ field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 210 },
{ field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd' },
{ field: 'endDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
{ field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 210 },
{ field: 'priority', headerText: 'Priority', textAlign: 'Left', width: 230 },
{ field: 'approved', headerText: 'Approved', width: 230, textAlign: 'Left' }
]
},
done
);
});
it('double click on a record, cell edit and cancel',() => {
let event: MouseEvent = new MouseEvent('dblclick', {
'view': window,
'bubbles': true,
'cancelable': true
});
gridObj.getCellFromIndex(0, 1).dispatchEvent(event);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_cancel' } });
expect(gridObj.getRows()[0].getElementsByClassName('e-treecell').length).toBe(1);
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Edit cell through method with Frozen Columns', () => {
let gridObj: TreeGrid;
let cellEdit: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
editSettings: { allowEditing: true, mode: 'Cell', allowDeleting: true, allowAdding: true,},
treeColumnIndex: 1,
frozenColumns: 3,
toolbar: ['Add', 'Edit', 'Update', 'Delete', 'Cancel', 'ExpandAll', 'CollapseAll'],
columns: [
{
field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right',
validationRules: { required: true, number: true}, width: 90
},
{ field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220 },
{ field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 210 },
{ field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd' },
{ field: 'endDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
{ field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 210 },
{ field: 'priority', headerText: 'Priority', textAlign: 'Left', width: 230 },
{ field: 'approved', headerText: 'Approved', width: 230, textAlign: 'Left' },
]
},
done
);
});
it('Edit Cell', () => {
cellEdit = (args?: any): void => {
setTimeout(() => {
expect(gridObj.grid.editModule.formObj.element.getElementsByTagName('input').length).toBe(1);
}, 0);
}
gridObj.cellEdit = cellEdit;
gridObj.editCell(2,'progress');
});
afterAll(() => {
destroy(gridObj);
});
});
describe('EJ2-22751: Events not triggered with Frozen Columns', () => {
let gridObj: TreeGrid;
let rows: Element[];
let actionBegin: () => void;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
treeColumnIndex: 1,
editSettings: {
allowAdding: true,
allowEditing: true,
allowDeleting: true,
mode: 'Cell'
},
frozenColumns: 3,
toolbar: ['Add', 'Delete', 'Update', 'Cancel'],
columns: [
{
field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right',
validationRules: { required: true, number: true}, width: 90
},
{ field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220 },
{ field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 210 },
{ field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd' },
{ field: 'endDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
{ field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 210 },
{ field: 'priority', headerText: 'Priority', textAlign: 'Left', width: 230 },
{ field: 'approved', headerText: 'Approved', width: 230, textAlign: 'Left' }
]
},
done
);
});
it('Check editing events', (done: Function) => {
let event: MouseEvent = new MouseEvent('dblclick', {
'view': window,
'bubbles': true,
'cancelable': true
});
gridObj.actionBegin = (args?: Object) : void => {
expect(args['columnName'] === 'taskName').toBe(true);
expect(args['type'] === 'edit').toBe(true);
done();
}
/*gridObj.actionComplete = (args?: Object): void => {
expect(args['type'] === 'edit').toBe(true);
done();
}*/
gridObj.getCellFromIndex(2, 1).dispatchEvent(event);
});
it('Check saving events', (done: Function) => {
let event: MouseEvent = new MouseEvent('dblclick', {
'view': window,
'bubbles': true,
'cancelable': true
});
gridObj.actionBegin = (args?: Object) : void => {
expect(args['type'] === 'save').toBe(true);
}
gridObj.actionComplete = (args?: Object) : void => {
expect(args['type'] === 'save').toBe(true);
expect(args['target'].cellIndex === 1).toBe(true);
done();
}
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
});
it('Check editing events again', (done: Function) => {
let event: MouseEvent = new MouseEvent('dblclick', {
'view': window,
'bubbles': true,
'cancelable': true
});
gridObj.actionBegin = (args?: Object) : void => {
expect(args['columnName'] === 'taskName').toBe(true);
expect(args['type'] === 'edit').toBe(true);
done();
}
/*gridObj.actionComplete = (args?: Object): void => {
expect(args['type'] === 'edit').toBe(true);
done();
}*/
gridObj.getCellFromIndex(3, 1).dispatchEvent(event);
});
it('Check cancelling events', (done: Function) => {
gridObj.actionComplete = (args?: Object) : void => {
expect(args['name'] === 'actionComplete').toBe(true);
done();
}
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_cancel' } });
});
afterAll(() => {
destroy(gridObj);
});
});
describe('allowEditOnDblClick - Cell Editing with Frozen Columns', () => {
let gridObj: TreeGrid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
editSettings: { allowEditing: true, allowDeleting: true, allowAdding: true, mode: "Cell", newRowPosition: 'Below', allowEditOnDblClick: false },
frozenColumns: 3,
treeColumnIndex: 1,
toolbar: ['Add', 'Update', 'Delete', 'Cancel'],
columns: [
{
field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right',
validationRules: { required: true, number: true}, width: 90
},
{ field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220 },
{ field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 210 },
{ field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd' },
{ field: 'endDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
{ field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 210 },
{ field: 'priority', headerText: 'Priority', textAlign: 'Left', width: 230 },
{ field: 'approved', headerText: 'Approved', width: 230, textAlign: 'Left' }
]
},
done
);
});
it('allowEditOnDblClick - Cell Editing', () => {
let event: MouseEvent = new MouseEvent('dblclick', {
'view': window,
'bubbles': true,
'cancelable': true
});
gridObj.getCellFromIndex(2, 1).dispatchEvent(event);
expect(isNullOrUndefined(gridObj.grid.editModule.formObj)).toBe(true);
});
afterAll(() => {
destroy(gridObj);
});
});
describe('EJ2-32160 - DataSource not refreshed after cancelling the edit action on cellEditing with Frozen Columns', () => {
let gridObj: TreeGrid;
let cellEdit: () => void;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
editSettings: { allowEditing: true, allowDeleting: true, allowAdding: true, mode: "Cell", newRowPosition: 'Below' },
treeColumnIndex: 1,
frozenColumns: 3,
toolbar: ['Add', 'Update', 'Delete', 'Cancel'],
columns: [
{
field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right',
validationRules: { required: true, number: true}, width: 90
},
{ field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220 },
{ field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 210 },
{ field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd' },
{ field: 'endDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
{ field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 210 },
{ field: 'priority', headerText: 'Priority', textAlign: 'Left', width: 230 },
{ field: 'approved', headerText: 'Approved', width: 230, textAlign: 'Left' }
]
},
done
);
});
it('DataSource not refreshed after cancelling the edit action on cellEditing', () => {
let event: MouseEvent = new MouseEvent('dblclick', {
'view': window,
'bubbles': true,
'cancelable': true
});
cellEdit = (args?: any): void => {
args.cancel = true;
}
actionComplete = (args?: any): void => {
expect(isNullOrUndefined(args.rowData.taskID)).toBe(true);
}
gridObj.cellEdit = cellEdit;
gridObj.actionComplete = actionComplete;
gridObj.getCellFromIndex(2, 1).dispatchEvent(event);
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_add' } });
});
afterAll(() => {
destroy(gridObj);
});
});
describe('EJ2-32869 - Clicking on Expand icon while in edit state with Frozen Columns', () => {
let gridObj: TreeGrid;
let cellEdit: () => void;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
editSettings: { allowEditing: true, allowDeleting: true, allowAdding: true, mode: "Cell", newRowPosition: 'Below' },
treeColumnIndex: 1,
frozenColumns: 3,
toolbar: ['Add', 'Update', 'Delete', 'Cancel'],
columns: [
{
field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right',
validationRules: { required: true, number: true}, width: 90
},
{ field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220 },
{ field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 210 },
{ field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd' },
{ field: 'endDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
{ field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 210 },
{ field: 'priority', headerText: 'Priority', textAlign: 'Left', width: 230 },
{ field: 'approved', headerText: 'Approved', width: 230, textAlign: 'Left' }
]
},
done
);
});
it('Clicking on expand icon in edit state', () => {
let event: MouseEvent = new MouseEvent('dblclick', {
'view': window,
'bubbles': true,
'cancelable': true
});
gridObj.getCellFromIndex(0, 2).dispatchEvent(event);
debugger;
(gridObj.editModule as any).doubleClickTarget.getElementsByTagName("input")[0].value = "20";
(gridObj.getRows()[0].getElementsByClassName('e-treegridexpand')[0] as HTMLElement).click();
let cells: NodeListOf<Element> = gridObj.grid.getRows()[0].querySelectorAll('.e-rowcell');
expect(cells[2].textContent === '20' ).toBeTruthy();
});
afterAll(() => {
destroy(gridObj);
});
});
describe('EJ2-36694 - Cell Update with aggregates with Frozen Columns', () => {
let gridObj: TreeGrid;
let cellEdit: () => void;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
treeColumnIndex: 1,
frozenColumns: 3,
height: 400,
editSettings: {
allowAdding: true,
allowEditing: true,
allowDeleting: true,
mode: 'Cell',
newRowPosition: 'Below'
},
aggregates: [{
showChildSummary: true,
columns: [
{
type: 'Max',
field: 'duration',
columnName: 'duration',
footerTemplate: 'Maximum: ${Max}'
}
]
}],
toolbar: ['Add', 'Delete', 'Update', 'Cancel'],
columns: [
{
field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right',
validationRules: { required: true, number: true}, width: 90
},
{ field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220 },
{ field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 210 },
{ field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit',
format: 'yMd' },
{ field: 'endDate', headerText: 'End Date', width: 230, textAlign: 'Right',
type: 'date', format: { type: 'dateTime', format: 'dd/MM/yyyy' } },
{ field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 210 },
{ field: 'priority', headerText: 'Priority', textAlign: 'Left', width: 230 },
{ field: 'approved', headerText: 'Approved', width: 230, textAlign: 'Left' }
]
},
done
);
});
it('Edit Cell', (done: Function) => {
actionComplete = (args?: any): void => {
if (args.requestType == 'save') {
expect((gridObj.getRows()[7].getElementsByClassName('e-treecell')[0] as HTMLElement).innerText=="test").toBe(true);
}
done();
}
gridObj.actionComplete = actionComplete;
let event: MouseEvent = new MouseEvent('dblclick', {
'view': window,
'bubbles': true,
'cancelable': true
});
gridObj.getCellFromIndex(7, 1).dispatchEvent(event);
gridObj.grid.editModule.formObj.element.getElementsByTagName('input')[0].value = 'test';
(<any>gridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: gridObj.grid.element.id + '_update' } });
});
afterAll(() => {
destroy(gridObj);
});
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
});
}); | the_stack |
import * as path from "path";
import { Event } from "@extraterm/extraterm-extension-api";
import { later } from "extraterm-later";
import { Logger, getLogger, log } from "extraterm-logging";
import { BrowserWindow, screen } from "electron";
import { SingleWindowConfiguration } from "../Config";
import * as ResourceLoader from "../ResourceLoader";
import { MainWindow, OpenWindowOptions } from "./MainWindow";
import { ThemeManager } from "../theme/ThemeManager";
import { bestOverlap } from "./RectangleMatch";
import { EventEmitter } from "../utils/EventEmitter";
import { ConfigDatabase } from "../ConfigDatabase";
const PNG_ICON_PATH = "../../resources/logo/extraterm_small_logo_256x256.png";
const ICO_ICON_PATH = "../../resources/logo/extraterm_small_logo.ico";
const isWindows = process.platform === "win32";
const isLinux = process.platform === "linux";
const isDarwin = process.platform === "darwin";
let SetWindowCompositionAttribute: any = null;
let AccentState: any = null;
if (isWindows) {
SetWindowCompositionAttribute = require("windows-swca").SetWindowCompositionAttribute;
AccentState = require("windows-swca").ACCENT_STATE;
}
/**
* Main process side representation of an Extraterm window.
*/
export class MainWindowImpl implements MainWindow {
private _log: Logger = null;
#id = -1;
#configDatabase: ConfigDatabase = null;
#themeManager: ThemeManager = null;
#configIndex = -1;
#onWindowClosedEventEmitter = new EventEmitter<number>();
onWindowClosed: Event<number>;
#onWindowDimensionChangedEventEmitter = new EventEmitter<void>();
onWindowDimensionChanged: Event<void>;
#onDevToolsOpenedEventEmitter = new EventEmitter<BrowserWindow>();
onDevToolsOpened: Event<BrowserWindow>;
#onDevToolsClosedEventEmitter = new EventEmitter<BrowserWindow>();
onDevToolsClosed: Event<BrowserWindow>;
#isReady = false;
#readyPromise: Promise<void> = null;
#readyResolve: () => void = null;
constructor(configDatabase: ConfigDatabase, themeManager: ThemeManager, configIndex: number) {
this._log = getLogger("MainWindowImpl", this);
this.#configDatabase = configDatabase;
this.#themeManager = themeManager;
this.#configIndex = configIndex;
this.onWindowClosed = this.#onWindowClosedEventEmitter.event;
this.onDevToolsOpened = this.#onDevToolsOpenedEventEmitter.event;
this.onDevToolsClosed = this.#onDevToolsClosedEventEmitter.event;
this.onWindowDimensionChanged = this.#onWindowDimensionChangedEventEmitter.event;
this.#readyPromise = new Promise((resolve, reject) => {
this.#readyResolve = resolve;
});
}
get id(): number {
return this.#id;
}
get browserId(): number {
return this.#id;
}
get configIndex(): number {
return this.#configIndex;
}
open(options: OpenWindowOptions=null): void {
const generalConfig = this.#configDatabase.getGeneralConfig();
const themeInfo = this.#themeManager.getTheme(generalConfig.themeGUI);
// Create the browser window.
const newBrowserWindowOptions = <Electron.BrowserWindowConstructorOptions> {
width: 1200,
height: 600,
webPreferences: {
experimentalFeatures: true,
contextIsolation: false,
nodeIntegration: true,
},
title: "Extraterm",
backgroundColor: "#00000000",
show: false,
};
if (isDarwin) {
if (generalConfig.titleBarStyle === "native") {
newBrowserWindowOptions.frame = true;
} else {
if (generalConfig.titleBarStyle === "theme") {
newBrowserWindowOptions.titleBarStyle = "hidden";
} else {
// Compact
newBrowserWindowOptions.titleBarStyle = "hiddenInset";
}
}
} else {
newBrowserWindowOptions.frame = generalConfig.titleBarStyle === "native";
}
// Restore the window position and size from the last session.
const dimensions = this._getWindowDimensionsFromConfig();
if (dimensions != null) {
newBrowserWindowOptions.x = dimensions.x;
newBrowserWindowOptions.y = dimensions.y;
newBrowserWindowOptions.width = dimensions.width;
newBrowserWindowOptions.height = dimensions.height;
}
if (isWindows) {
newBrowserWindowOptions.icon = path.join(__dirname, ICO_ICON_PATH);
} else if (isLinux) {
newBrowserWindowOptions.icon = path.join(__dirname, PNG_ICON_PATH);
}
const newWindow = new BrowserWindow(newBrowserWindowOptions);
if (options?.openDevTools) {
newWindow.webContents.openDevTools();
}
newWindow.setMenu(null);
// Emitted when the window is closed.
const mainWindowWebContentsId = newWindow.webContents.id;
newWindow.on("closed", () => {
this.#onWindowClosedEventEmitter.fire(mainWindowWebContentsId);
});
const emitDimensionChanged = () => {
this.#onWindowDimensionChangedEventEmitter.fire();
};
newWindow.on("close", emitDimensionChanged);
newWindow.on("resize", emitDimensionChanged);
newWindow.on("maximize", emitDimensionChanged);
newWindow.on("unmaximize", emitDimensionChanged);
this._setupTransparentBackground(newWindow);
this._checkWindowBoundsLater(newWindow, dimensions);
let params = "?loadingBackgroundColor=" + themeInfo.loadingBackgroundColor.replace("#", "") +
"&loadingForegroundColor=" + themeInfo.loadingForegroundColor.replace("#", "");
if (options.bareWindow) {
params += "&bareWindow=true";
}
// and load the index.html of the app.
newWindow.loadURL(ResourceLoader.toUrl("render_process/main.html") + params);
newWindow.webContents.on("devtools-closed", () => {
this.#onDevToolsClosedEventEmitter.fire(newWindow);
});
newWindow.webContents.on("devtools-opened", () => {
this.#onDevToolsOpenedEventEmitter.fire(newWindow);
});
this.#id = newWindow.id;
}
async handleWindowReady(): Promise<void> {
await later();
this.#isReady = true;
this._log.debug(`#readyResolve`);
this.#readyResolve();
this.#readyResolve = null;
}
/**
* Async wait until the window is fully open and finished initialization.
*/
async ready(): Promise<void> {
if (this.#isReady) {
return;
}
await this.#readyPromise;
}
private _getBrowserWindow(): BrowserWindow {
return BrowserWindow.fromId(this.#id);
}
private _checkWindowBoundsLater(window: BrowserWindow, desiredConfig: SingleWindowConfiguration): void {
window.once("ready-to-show", () => {
const windowBounds = window.getNormalBounds();
// Figure out which Screen this window is meant to be on.
const windowDisplay = this._matchWindowToDisplay(window);
const newDimensions: Electron.Rectangle = { ...windowBounds };
let updateNeeded = false;
if (desiredConfig != null && desiredConfig.isMaximized === true) {
if (windowBounds.x !== windowDisplay.workArea.x ||
windowBounds.y !== windowDisplay.workArea.y ||
windowBounds.width !== windowDisplay.workArea.width ||
windowBounds.height !== windowDisplay.workArea.height) {
window.maximize();
}
} else {
if (desiredConfig != null) {
if (newDimensions.width < desiredConfig.width) {
newDimensions.width = desiredConfig.width;
updateNeeded = true;
}
if (newDimensions.height < desiredConfig.height) {
newDimensions.height = desiredConfig.height;
updateNeeded = true;
}
}
// Clamp the width/height to fit on the display.
if (newDimensions.width > windowDisplay.workArea.width) {
newDimensions.width = windowDisplay.workArea.width;
updateNeeded = true;
}
if (newDimensions.height > windowDisplay.workArea.height) {
newDimensions.height = windowDisplay.workArea.height;
updateNeeded = true;
}
// Slide the window to avoid being half off the display.
if (newDimensions.x < windowDisplay.workArea.x) {
newDimensions.x = windowDisplay.workArea.x;
updateNeeded = true;
}
if (newDimensions.y < windowDisplay.workArea.y) {
newDimensions.y = windowDisplay.workArea.y;
updateNeeded = true;
}
const displayRightEdgeX = windowDisplay.workArea.width + windowDisplay.workArea.x;
if (newDimensions.width + newDimensions.x > displayRightEdgeX) {
newDimensions.x = displayRightEdgeX - newDimensions.width;
updateNeeded = true;
}
const displayBottomEdgeY = windowDisplay.workArea.height + windowDisplay.workArea.y;
if (newDimensions.height + newDimensions.y > displayBottomEdgeY) {
newDimensions.y = displayBottomEdgeY - newDimensions.height;
updateNeeded = true;
}
if (updateNeeded) {
// Enforce minimum and sane width/height values.
newDimensions.height = Math.max(100, newDimensions.height);
newDimensions.width = Math.max(100, newDimensions.width);
}
}
if (updateNeeded) {
window.setBounds(newDimensions);
}
});
}
private _matchWindowToDisplay(window: BrowserWindow): Electron.Display {
const displays = screen.getAllDisplays();
const displayAreas = displays.map(d => d.workArea);
const matchIndex = bestOverlap(window.getNormalBounds(), displayAreas);
if (matchIndex === -1) {
return screen.getPrimaryDisplay();
}
return displays[matchIndex];
}
private _getWindowDimensionsFromConfig(): SingleWindowConfiguration {
const generalConfig = this.#configDatabase.getGeneralConfig();
if (generalConfig.windowConfiguration == null) {
return null;
}
const singleWindowConfig = generalConfig.windowConfiguration[this.#configIndex];
if (singleWindowConfig == null) {
return null;
}
return singleWindowConfig;
}
private _setupTransparentBackground(window: BrowserWindow): void {
const setWindowComposition = () => {
const generalConfig = this.#configDatabase.getGeneralConfig();
const isWindowOpaque = generalConfig.windowBackgroundMode === "opaque";
if (isWindows) {
const accent = isWindowOpaque
? AccentState.ACCENT_DISABLED
: AccentState.ACCENT_ENABLE_BLURBEHIND;
SetWindowCompositionAttribute(window.getNativeWindowHandle(), accent, 0);
}
if (isDarwin) {
if ( ! isWindowOpaque) {
window.setVibrancy("dark");
}
}
};
this.#configDatabase.onChange(event => {
if (event.key === "general" &&
event.oldConfig.windowBackgroundMode !== event.newConfig.windowBackgroundMode) {
setWindowComposition();
}
});
window.once("ready-to-show", () => {
setWindowComposition();
window.show();
});
}
async restore(): Promise<void> {
const generalConfig = this.#configDatabase.getGeneralConfig();
const window = this._getBrowserWindow();
const bounds = generalConfig.windowConfiguration[this.#configIndex];
if (isLinux) {
// On Linux, if a window is the width or height of the screen then
// Electron (2.0.13) resizes them (!) to be smaller for some annoying
// reason. This is a hack to make sure that windows are restored with
// the correct dimensions.
if (bounds != null) {
window.setBounds(bounds);
window.setMinimumSize(bounds.width, bounds.height);
}
if (generalConfig.showTrayIcon && generalConfig.minimizeToTray) {
window.show();
}
window.restore();
await later(100);
window.setMinimumSize(10, 10);
} else {
// Windows and macOS
if (generalConfig.showTrayIcon && generalConfig.minimizeToTray) {
if (bounds != null) {
if (bounds.isMaximized === true) {
window.maximize();
}
this._checkWindowBoundsLater(window, bounds);
}
window.show();
}
window.restore();
await later();
window.moveTop();
window.focus();
}
}
getNormalBounds() {
return this._getBrowserWindow().getNormalBounds();
}
isMinimized(): boolean {
return this._getBrowserWindow().isMinimized();
}
isVisible(): boolean {
return this._getBrowserWindow().isVisible();
}
isMaximized(): boolean {
return this._getBrowserWindow().isMaximized();
}
hide(): void {
this._getBrowserWindow().hide();
}
maximize(): void {
this._getBrowserWindow().maximize();
}
minimize(): void {
this._getBrowserWindow().minimize();
}
moveTop(): void {
this._getBrowserWindow().moveTop();
}
show(): void {
this._getBrowserWindow().show();
}
} | the_stack |
import { autoinject, inject, Factory } from 'aurelia-dependency-injection'
import {
createGuid,
PerspectiveFrustum,
Matrix4,
Cartographic
} from './cesium/cesium-imports'
import {
Role,
ContextFrameState,
CanvasViewport,
Viewport,
SerializedSubviewList
} from './common'
import { SessionPort, SessionService } from './session'
import { Event, deprecated, decomposePerspectiveProjectionMatrix } from './utils'
import { ContextService } from './context'
import { FocusServiceProvider } from './focus'
import { VisibilityServiceProvider } from './visibility'
import { RealityViewer } from './reality-viewers/base'
import { EmptyRealityViewer } from './reality-viewers/empty'
import { LiveRealityViewer } from './reality-viewers/live'
import { HostedRealityViewer } from './reality-viewers/hosted'
import {ViewServiceProvider} from './view'
import {DeviceService} from './device'
@inject(Factory.of(EmptyRealityViewer), Factory.of(LiveRealityViewer), Factory.of(HostedRealityViewer))
export abstract class RealityViewerFactory {
constructor(
private _createEmptyReality,
private _createLiveReality,
private _createHostedReality) {
}
createRealityViewer(uri:string) : RealityViewer {
switch (RealityViewer.getType(uri)) {
case RealityViewer.EMPTY:
return this._createEmptyReality(uri);
case RealityViewer.LIVE:
return this._createLiveReality(uri);
case 'hosted':
return this._createHostedReality(uri);
default:
throw new Error('Unsupported Reality Viewer: ' + uri)
}
}
}
/**
* A service which makes requests to manage the reality viewer.
*/
@autoinject()
export class RealityService {
/**
* An event that provides a session for sending / receiving
* commands to / from a reality.
*
* The session passed via this event can represent either endpoint of
* a connection between RealityViewer <--> RealityAugmenter/RealityManager.
*
* If running in a RealityAugmenter, the session
* represents a connection to a RealityViewer.
*
* If running in a RealityViewer, the session
* represents a connection to a RealityAugmenter.
*/
public get connectEvent() { return this._connectEvent };
private _connectEvent = new Event<SessionPort>();
/**
* A collection of connected sessions.
*
* If running in a RealityAugmenter, this collection
* represents connections to any loaded RealityViewers.
*
* If running in a RealityViewer, this collection
* represents connections to any RealityAugmenters.
*/
public get sessions() { return this._sessions };
private _sessions:SessionPort[] = [];
/**
* An event that is raised when the presenting reality viewer is changed.
*/
public get changeEvent() {
return this._changeEvent;
}
private _changeEvent = new Event<{ previous?: string, current: string }>();
/**
* The URI for the currently presenting Reality Viewer.
*/
public get current(): string | undefined {
return this._current;
}
private _current?: string;
/**
* The default Reality Viewer.
*/
public default = RealityViewer.EMPTY;
// private _scratchFrustum = new PerspectiveFrustum();
constructor(
private sessionService: SessionService,
private contextService: ContextService
) {
sessionService.manager.on['ar.reality.connect'] = ({id}: { id: string }) => {
const realityControlSession = this.sessionService.createSessionPort(id);
const messageChannel = this.sessionService.createSynchronousMessageChannel();
const ROUTE_MESSAGE_KEY = 'ar.reality.message.route.' + id;
const SEND_MESSAGE_KEY = 'ar.reality.message.send.' + id;
const CLOSE_SESSION_KEY = 'ar.reality.close.' + id;
messageChannel.port1.onmessage = (msg: MessageEvent) => {
this.sessionService.manager.send(ROUTE_MESSAGE_KEY, msg.data);
}
this.sessionService.manager.on[SEND_MESSAGE_KEY] = (message) => {
messageChannel.port1.postMessage(message);
}
this.sessionService.manager.on[CLOSE_SESSION_KEY] = () => {
realityControlSession.close();
}
realityControlSession.connectEvent.addEventListener(() => {
this.sessions.push(realityControlSession);
this.connectEvent.raiseEvent(realityControlSession);
realityControlSession.closeEvent.addEventListener(()=>{
const idx = this.sessions.indexOf(realityControlSession);
this.sessions.splice(idx,1);
});
})
this.sessionService.manager.closeEvent.addEventListener(() => {
realityControlSession.close();
delete this.sessionService.manager.on[SEND_MESSAGE_KEY];
delete this.sessionService.manager.on[CLOSE_SESSION_KEY];
});
realityControlSession.open(messageChannel.port2, this.sessionService.configuration);
};
// let i = 0;
this.contextService.updateEvent.addEventListener(()=>{
const frameState = this.contextService.serializedFrameState;
if (sessionService.isRealityViewer && sessionService.manager.isConnected) {
// backwards compatability
if (sessionService.manager.isConnected && sessionService.manager.version[0] === 0) {
const eye = frameState['eye'] = frameState['eye'] || {};
eye.pose = frameState.entities['ar.user'];
eye.viewport = Viewport.clone(frameState.subviews[0].viewport, eye.viewport);
delete frameState.entities['ar.user'];
// throttle for 30fps
// i++ % 2 === 0 &&
sessionService.manager.send('ar.reality.frameState', frameState);
frameState.entities['ar.user'] = eye.pose;
} else {
sessionService.manager.send('ar.reality.frameState', frameState);
}
}
const current = frameState.reality!;
const previous = this._current;
if (previous !== current) {
this._current = current;
this.changeEvent.raiseEvent({ previous, current });
}
});
}
/**
* Install the specified reality viewer
*/
public install(uri: string) : Promise<void> {
return this.sessionService.manager.whenConnected().then(()=>{
if (this.sessionService.manager.version[0] >= 1 !== true)
return Promise.reject(new Error('Not supported'))
return this.sessionService.manager.request('ar.reality.install', {uri});
});
}
/**
* Uninstall the specified reality viewer
*/
public uninstall(uri: string): Promise<void> {
return this.sessionService.manager.whenConnected().then(()=>{
if (this.sessionService.manager.version[0] >= 1 !== true)
return Promise.reject(new Error('Not supported'))
return this.sessionService.manager.request('ar.reality.uninstall', {uri});
});
}
/**
* Request a reality viewer to be presented.
* - Pass a url to request a (custum) hosted reality viewer
* - [[RealityViewer.DEFAULT]] to request the system default reality viewer
* - [[RealityViewer.LIVE]] to request a live reality viewer
* - [[RealityViewer.EMPTY]] to request an empty reality viewer
*/
public request(uri:string): Promise<void> {
return this.sessionService.manager.whenConnected().then(()=>{
if (this.sessionService.manager.version[0] >= 1 !== true)
return this.sessionService.manager.request('ar.reality.desired', {reality:{uri}});
return this.sessionService.manager.request('ar.reality.request', {uri});
});
}
/**
* Deprecated. Use [[RealityService#request]]
* @deprecated
*/
@deprecated('request')
public setDesired(reality: {uri:string} | undefined) {
this.request(reality ? reality.uri : RealityViewer.DEFAULT);
}
/**
* Ask a reality to move the stage to the given geolocation
*/
public setStageGeolocation(realitySession:SessionPort, geolocation:Cartographic) : Promise<void> {
if (!realitySession.supportsProtocol('ar.configureStage'))
return Promise.reject('Protocol `ar.configureStage` is not supported');
return realitySession.request('ar.configureStage.setStageGeolocation', {geolocation});
}
/**
* Ask a reality to move the stage to the given geolocation
*/
public resetStageGeolocation(realitySession:SessionPort) : Promise<void> {
if (!realitySession.supportsProtocol('ar.configureStage'))
return Promise.reject('Protocol `ar.configureStage` is not supported');
return realitySession.request('ar.configureStage.resetStageGeolocation');
}
}
@autoinject
export class RealityServiceProvider {
/**
* An event that is raised when a reality viewer is installed.
*/
public installedEvent = new Event<{ viewer:RealityViewer }>();
/**
* An event that is raised when a reality viewer is uninstalled.
*/
public uninstalledEvent = new Event<{ viewer:RealityViewer }>();
public get presentingRealityViewer() { return this._presentingRealityViewer }
private _presentingRealityViewer:RealityViewer|undefined;
private _viewerByURI = new Map<string, RealityViewer>();
private _installersByURI = new Map<string, Set<SessionPort>>();
constructor(
private sessionService:SessionService,
private realityService:RealityService,
private contextService:ContextService,
private deviceService:DeviceService,
private viewServiceProvider:ViewServiceProvider,
private visibilityServiceProvider:VisibilityServiceProvider,
private focusServiceProvider: FocusServiceProvider,
private realityViewerFactory:RealityViewerFactory,
) {
sessionService.ensureIsRealityManager();
sessionService.manager.connectEvent.addEventListener(() => {
setTimeout(() => {
if (!this._presentingRealityViewer && this.realityService.default)
this._handleRequest(this.sessionService.manager, {
uri:this.realityService.default
});
});
});
sessionService.manager.closeEvent.addEventListener(()=>{
this._viewerByURI.forEach((v)=>{
v.destroy();
});
});
sessionService.connectEvent.addEventListener((session) => {
if (!Role.isRealityViewer(session.info.role)) {
session.on['ar.reality.install'] = ({uri}:{uri:string}) => {
return this._handleInstall(session, uri);
};
session.on['ar.reality.uninstall'] = ({uri}:{uri:string}) => {
return this._handleUninstall(session, uri);
};
session.on['ar.reality.request'] = (message:{uri:string}) => {
return this._handleRequest(session, message);
};
// For backwards compatability.
session.on['ar.reality.desired'] = (message:{reality:{uri:string}}) => {
const {reality} = message;
if (reality) {
if (reality['type']) {
const type = reality['type'] as string;
reality.uri = reality.uri || 'reality:' + type;
if (type === 'hosted') reality.uri = reality['url'];
}
}
this._handleRequest(session, {uri:reality.uri});
}
}
});
this.viewServiceProvider.forwardedUIEvent.addEventListener((uievent)=>{
const session = this._presentingRealityViewer && this._presentingRealityViewer.session;
if (session) this.viewServiceProvider.sendUIEventToSession(uievent, session);
});
}
private _scratchFrustum = new PerspectiveFrustum;
private _handleInstall(session:SessionPort, uri:string) {
let installers = this._installersByURI.get(uri);
if (installers) {
installers.add(session);
} else {
const viewer = this.realityViewerFactory.createRealityViewer(uri);
this._viewerByURI.set(uri, viewer);
installers = new Set<SessionPort>();
installers.add(session);
this._installersByURI.set(uri, installers);
viewer.connectEvent.addEventListener((viewerSession)=>{
if (this.sessionService.manager.isClosed) return;
if (!Role.isRealityViewer(viewerSession.info.role)) {
viewerSession.sendError({ message: "Expected a reality viewer" });
viewerSession.close();
throw new Error('The application "' + viewerSession.uri + '" does not support being loaded as a reality viewer');
}
viewerSession.on['ar.reality.frameState'] = (frame: ContextFrameState) => {
if (this._presentingRealityViewer === viewer) {
if (viewerSession.version[0] === 0) { // backwards compatability
const deviceState = this.deviceService.frameState;
if (!deviceState) return;
frame.viewport = CanvasViewport.clone(deviceState.viewport, frame.viewport)!;
frame.subviews = SerializedSubviewList.clone(deviceState.subviews, frame.subviews)!;
const eye = frame['eye'];
const eyePose = eye.pose;
const eyeFov = eye.fov;
frame.entities = frame.entities || {};
frame.entities['ar.user'] = eyePose;
for (const s of frame.subviews) {
const f:PerspectiveFrustum = decomposePerspectiveProjectionMatrix(s.projectionMatrix, s['frustum'] || {});
f.fov = eyeFov;
this._scratchFrustum.clone(f);
s.projectionMatrix = Matrix4.clone(this._scratchFrustum.projectionMatrix, s.projectionMatrix);
}
}
frame.reality = viewer.uri;
this.contextService.submitFrameState(frame);
}
}
if (viewerSession.info['supportsCustomProtocols']) {
this._connectViewerWithSession(viewerSession, this.sessionService.manager);
for (session of this.sessionService.managedSessions) {
this._connectViewerWithSession(viewerSession, session);
}
const remove = this.sessionService.connectEvent.addEventListener((session)=>{
this._connectViewerWithSession(viewerSession, session);
})
viewerSession.closeEvent.addEventListener(()=>remove());
}
const removePresentChangeListener = viewer.presentChangeEvent.addEventListener(()=>{
this.visibilityServiceProvider.set(viewerSession, viewer.isPresenting)
});
this.visibilityServiceProvider.set(viewerSession, viewer.isPresenting);
viewerSession.closeEvent.addEventListener(() => {
removePresentChangeListener();
this.contextService.entities.removeById(viewerSession.uri);
console.log('Reality session closed: ' + uri);
});
});
viewer.load();
this.installedEvent.raiseEvent({viewer});
}
}
private _connectViewerWithSession(viewerSession:SessionPort, session:SessionPort) {
if (Role.isRealityViewer(session.info.role)) return;
const id = createGuid();
const ROUTE_MESSAGE_KEY = 'ar.reality.message.route.' + id;
const SEND_MESSAGE_KEY = 'ar.reality.message.send.' + id;
const CLOSE_SESSION_KEY = 'ar.reality.close.' + id;
viewerSession.on[ROUTE_MESSAGE_KEY] = (message) => {
session.send(SEND_MESSAGE_KEY, message);
}
session.on[ROUTE_MESSAGE_KEY] = (message) => {
viewerSession.send(SEND_MESSAGE_KEY, message);
}
viewerSession.send('ar.reality.connect', { id });
session.send('ar.reality.connect', { id });
viewerSession.closeEvent.addEventListener(() => {
session.send(CLOSE_SESSION_KEY);
});
session.closeEvent.addEventListener(() => {
viewerSession.send(CLOSE_SESSION_KEY);
})
}
protected _handleUninstall(session: SessionPort, uri:string) {
const installers = this._installersByURI.get(uri);
if (installers) {
if (installers.size === 0) {
const viewer = this._viewerByURI.get(uri)!;
this._viewerByURI.delete(uri);
viewer.destroy();
this.uninstalledEvent.raiseEvent({viewer});
}
}
return Promise.reject(new Error("Unable to uninstall a reality viewer which is not installed"));
}
protected _handleRequest(session: SessionPort, options:{uri:string}) : Promise<void> {
if (this.focusServiceProvider.session === session || session === this.sessionService.manager) {
let uri = options && options.uri || RealityViewer.DEFAULT;
switch (uri) {
case RealityViewer.DEFAULT:
uri = this.realityService.default;
}
this._handleInstall(session, uri);
this._setPresentingRealityViewer(this._viewerByURI.get(uri)!);
return Promise.resolve();
}
throw new Error('Request Denied');
}
private _setPresentingRealityViewer(viewer: RealityViewer) {
if (!viewer) throw new Error('Invalid State. Expected a RealityViewer instance');
if (this._presentingRealityViewer === viewer) return;
this._viewerByURI.forEach((v)=>{
v.setPresenting(v === viewer);
});
this._presentingRealityViewer = viewer;
console.log('Presenting reality viewer changed to: ' + viewer.uri);
}
public getViewerByURI(uri: string) {
return this._viewerByURI.get(uri);
}
public removeInstaller(installerSession: SessionPort) {
this._viewerByURI.forEach((viewer, realityUri, map)=>{
const installers = this._installersByURI.get(realityUri);
if (installers && installers.has(installerSession)) {
installers.delete(installerSession);
if (installers.size === 0 && viewer.session) {
this._handleUninstall(viewer.session, realityUri);
this._installersByURI.delete(realityUri);
}
}
});
}
} | the_stack |
import { PresetIcon, IconSet } from './icon';
interface RegisterIcon {
(key: string | string[], icon: PresetIcon): void
}
interface RegisterFileNameIcon {
(fileName: string | string[], extensions: string[], icon: PresetIcon): void
}
export function setExtensions(set: RegisterIcon) {
// XML
set('xml', {
[IconSet.ColorLight]: '#ff6600',
[IconSet.IconIon]: 'ion-code',
[IconSet.IconDev]: 'devicons devicons-code'
});
set(['html', 'htm'], {
[IconSet.ColorLight]: '#e34c26',
[IconSet.IconIon]: 'ion-code',
[IconSet.IconDev]: 'devicons devicons-html5'
});
set('haml', {
[IconSet.ColorLight]: '#0270b9',
[IconSet.IconIon]: 'ion-code',
[IconSet.IconDev]: 'devicons devicons-code'
});
set('hbs', {
[IconSet.ColorLight]: '#f38709',
[IconSet.IconIon]: 'ion-code',
[IconSet.IconDev]: 'devicons devicons-code'
});
// Stylesheets
set('css', {
[IconSet.ColorLight]: '#0270b9',
[IconSet.IconIon]: ['ion-pound', 12],
[IconSet.IconDev]: 'devicons devicons-css3_full'
});
set(['scss', 'sass'], {
[IconSet.ColorLight]: '#cb6899',
[IconSet.IconIon]: ['ion-pound', 12],
[IconSet.IconDev]: 'devicons devicons-sass'
});
set('less', {
[IconSet.ColorLight]: '#2b5086',
[IconSet.IconIon]: ['ion-pound', 12],
[IconSet.IconDev]: 'devicons devicons-less'
});
set('styl', {
[IconSet.ColorLight]: '#b3d107',
[IconSet.IconIon]: ['ion-pound', 12],
[IconSet.IconDev]: 'devicons devicons-stylus'
});
// JavaScript
set('js', {
[IconSet.ColorLight]: '#e5a228',
[IconSet.IconIon]: ['file-icon-c', 13],
[IconSet.IconDev]: 'devicons devicons-javascript'
});
set('jsx', {
[IconSet.ColorLight]: '#f8c63d',
[IconSet.IconIon]: ['file-icon-c', 13],
[IconSet.IconDev]: 'devicons devicons-javascript'
});
set('es6', {
[IconSet.ColorLight]: '#4321a9',
[IconSet.IconIon]: ['file-icon-c', 13],
[IconSet.IconDev]: 'devicons devicons-javascript'
});
set('babel.js', {
[IconSet.ColorLight]: '#f5da55',
[IconSet.IconIon]: ['file-icon-c', 13],
[IconSet.IconDev]: 'devicons devicons-javascript'
});
set('ts', {
[IconSet.ColorLight]: '#0074c1',
[IconSet.IconIon]: ['file-icon-c', 13],
[IconSet.IconDev]: 'devicons devicons-javascript' // TODO: Better icon
});
set('d.ts', {
[IconSet.ColorLight]: '#0b8f9e',
[IconSet.IconIon]: ['file-icon-c', 13],
[IconSet.IconDev]: 'devicons devicons-javascript' // TODO: Better icon
});
set('coffee', {
[IconSet.ColorLight]: '#425d99',
[IconSet.IconIon]: 'ion-coffee',
[IconSet.IconDev]: 'devicons devicons-coffeescript'
});
set('json', {
[IconSet.ColorLight]: '#e5a228',
[IconSet.IconIon]: 'ion-ios-gear',
[IconSet.IconDev]: 'devicons devicons-aptana'
});
set('ls', {
[IconSet.ColorLight]: '#369bd7',
[IconSet.IconIon]: 'ion-beaker',
[IconSet.IconDev]: 'devicons devicons-javascript' // TODO: Better icon
});
// Server side
set('php', {
[IconSet.ColorLight]: '#6976c3',
[IconSet.IconIon]: 'ion-code-working',
[IconSet.IconDev]: 'devicons devicons-php'
});
set('ctp', {
[IconSet.ColorLight]: '#417282',
[IconSet.IconIon]: 'ion-code-working',
[IconSet.IconDev]: 'devicons devicons-php'
});
set('sql', {
[IconSet.ColorLight]: '#c67f07',
[IconSet.IconIon]: 'ion-soup-can-outline',
[IconSet.IconDev]: 'devicons devicons-database'
});
// Java
set(['java', 'class'], {
[IconSet.ColorLight]: '#5382a1',
[IconSet.IconIon]: 'ion-coffee',
[IconSet.IconDev]: 'devicons devicons-java'
});
set('scala', {
[IconSet.ColorLight]: '#72d0eb',
[IconSet.IconIon]: 'ion-navicon-round file-icon-rotated',
[IconSet.IconDev]: 'devicons devicons-scala'
});
set('groovy', {
[IconSet.ColorLight]: '#4298b8',
[IconSet.IconIon]: 'ion-ios-star',
[IconSet.IconDev]: ['devicons devicons-groovy', 18]
});
set('mf', {
[IconSet.ColorLight]: '#2f5796',
[IconSet.IconIon]: 'ion-ios-gear',
[IconSet.IconDev]: 'devicons devicons-aptana' // Looks like a gear
});
// Lua
set('lua', {
[IconSet.ColorLight]: '#00207d',
[IconSet.IconIon]: ['ion-record', 14]
});
// Clojure
set('clj', {
[IconSet.ColorLight]: '#63b132',
[IconSet.IconIon]: 'ion-aperture',
[IconSet.IconDev]: 'devicons devicons-clojure'
});
// Visual Basic
set('vb', {
[IconSet.ColorLight]: '#486dae',
[IconSet.IconIon]: 'ion-ios-infinite',
[IconSet.IconDev]: 'devicons devicons-visualstudio'
});
set('vbs', {
[IconSet.ColorLight]: '#3d047e',
[IconSet.IconIon]: 'ion-ios-infinite',
[IconSet.IconDev]: 'devicons devicons-visualstudio'
});
// C-family
set('hx', {
[IconSet.ColorLight]: '#ea8220',
[IconSet.IconIon]: ['file-icon-c', 13]
});
set('pl', {
[IconSet.ColorLight]: '#a4c5eb',
[IconSet.IconIon]: ['file-icon-c', 13]
});
set('c', {
[IconSet.ColorLight]: '#a8b9cc',
[IconSet.IconIon]: ['file-icon-c', 13]
});
set('cpp', {
[IconSet.ColorLight]: '#ffd232',
[IconSet.IconIon]: ['file-icon-c', 13]
});
set('cs', {
[IconSet.ColorLight]: '#5bb552',
[IconSet.IconIon]: ['file-icon-c', 13],
[IconSet.IconDev]: 'devicons devicons-visualstudio'
});
set('swift', {
[IconSet.ColorLight]: '#f16830',
[IconSet.IconIon]: ['file-icon-c', 13],
[IconSet.IconDev]: 'devicons devicons-swift'
});
set('dart', {
[IconSet.ColorLight]: '#36bfb6',
[IconSet.IconIon]: ['file-icon-c', 13],
[IconSet.IconDev]: 'devicons devicons-dart'
});
// Ruby
set(['rb', 'erb', 'rdoc'], {
[IconSet.ColorLight]: '#9b111e',
[IconSet.IconIon]: 'ion-heart',
[IconSet.IconDev]: ['devicons devicons-ruby', 14]
});
set('feature', {
[IconSet.ColorLight]: '#4e8b39',
[IconSet.IconIon]: 'ion-chatbox-working',
[IconSet.IconDev]: ['devicons devicons-ruby', 14]
});
// Python
set(['py', 'pyw'], {
[IconSet.ColorLight]: '#f8c63d',
[IconSet.IconIon]: 'ion-social-python',
[IconSet.IconDev]: 'devicons devicons-python'
});
// Haskell
set('hs', {
[IconSet.ColorLight]: '#c4451d',
[IconSet.IconIon]: 'ion-android-share-alt file-icon-rotate-90',
[IconSet.IconDev]: 'devicons devicons-haskell'
})
// Qt Quick
set('qml', {
[IconSet.ColorLight]: '#42ed0e',
[IconSet.IconIon]: 'ion-code',
[IconSet.IconDev]: 'devicons devicons-code'
});
// Shell and friends
set('sh', {
[IconSet.ColorLight]: '#008d00',
[IconSet.IconIon]: 'ion-android-list',
[IconSet.IconDev]: 'devicons devicons-terminal'
});
set('bat', {
[IconSet.ColorLight]: '#60c910',
[IconSet.IconIon]: 'ion-android-list',
[IconSet.IconDev]: 'devicons devicons-terminal'
});
// Applications
set('exe', {
[IconSet.ColorLight]: '#57a084',
[IconSet.IconIon]: 'ion-social-windows',
[IconSet.IconDev]: 'devicons devicons-windows'
});
set('dll', {
[IconSet.ColorLight]: '#709ead',
[IconSet.IconIon]: 'ion-social-windows',
[IconSet.IconDev]: 'devicons devicons-windows'
});
// Templating
set(['pug', 'jade'], {
[IconSet.ColorLight]: '#00a57a',
[IconSet.IconIon]: 'ion-egg'
});
// Images
set('png', {
[IconSet.ColorLight]: '#dbb1a9',
[IconSet.IconIon]: 'ion-image',
[IconSet.IconDev]: 'devicons devicons-html5_multimedia'
});
set(['jpeg', 'jpg'], {
[IconSet.ColorLight]: '#dedfa3',
[IconSet.IconIon]: 'ion-image',
[IconSet.IconDev]: 'devicons devicons-html5_multimedia'
});
set('tiff', {
[IconSet.ColorLight]: '#ff4000',
[IconSet.IconIon]: 'ion-image',
[IconSet.IconDev]: 'devicons devicons-html5_multimedia'
});
set('ico', {
[IconSet.ColorLight]: '#b6d2d1',
[IconSet.IconIon]: 'ion-image',
[IconSet.IconDev]: 'devicons devicons-html5_multimedia'
});
set('svg', {
[IconSet.ColorLight]: '#c0c5eb',
[IconSet.IconIon]: 'ion-image',
[IconSet.IconDev]: 'devicons devicons-html5_multimedia'
});
set('gif', {
[IconSet.ColorLight]: '#aaecc0',
[IconSet.IconIon]: 'ion-images',
[IconSet.IconDev]: 'devicons devicons-html5_multimedia'
});
// Videos
set(['mp4', 'webm', 'ogg'], {
[IconSet.ColorLight]: '#008d00',
[IconSet.IconIon]: 'ion-ios-videocam',
[IconSet.IconDev]: 'devicons devicons-html5_multimedia'
});
// Audio
set(['mp3', 'wav'], {
[IconSet.ColorLight]: '#921100',
[IconSet.IconIon]: 'ion-volume-medium',
[IconSet.IconDev]: 'devicons devicons-html5_multimedia'
});
// Fonts
set('ttf', {
[IconSet.ColorLight]: '#b42950',
[IconSet.IconIon]: 'ion-social-tumblr'
});
set('eot', {
[IconSet.ColorLight]: '#b36908',
[IconSet.IconIon]: 'ion-social-tumblr'
});
set(['woff', 'woff2'], {
[IconSet.ColorLight]: '#7f4bb2',
[IconSet.IconIon]: 'ion-social-tumblr'
});
set('otf', {
[IconSet.ColorLight]: '#7f4bb2',
[IconSet.IconIon]: 'ion-social-tumblr'
});
// Readme
set(['md', 'markdown'], {
[IconSet.ColorLight]: '#b94700',
[IconSet.IconIon]: ['ion-social-markdown', 12],
[IconSet.IconDev]: 'devicons devicons-markdown'
});
// Git
set('gitignore', {
[IconSet.ColorLight]: '#cd5439',
[IconSet.IconIon]: ['ion-minus-circled', 14],
[IconSet.IconDev]: 'devicons devicons-git_commit'
});
set('gitmodules', {
[IconSet.ColorLight]: '#f64d27',
[IconSet.IconIon]: ['ion-fork-repo', 17],
[IconSet.IconDev]: 'devicons devicons-git_branch'
});
// Webservers
set('htaccess', {
[IconSet.ColorLight]: '#93a8be',
[IconSet.IconIon]: ['ion-ios-unlocked', 18]
});
set('htpasswd', {
[IconSet.ColorLight]: '#6c369c',
[IconSet.IconIon]: ['ion-ios-locked', 18]
});
set('conf', {
[IconSet.ColorLight]: '#009900',
[IconSet.IconIon]: 'ion-ios-gear',
[IconSet.IconDev]: 'devicons devicons-aptana' // Looks like a gear
});
// Archive
set('zip', {
[IconSet.ColorLight]: '#008858',
[IconSet.IconIon]: 'ion-briefcase',
[IconSet.IconDev]: ['devicons devicons-netbeans', 17]
});
set('rar', {
[IconSet.ColorLight]: '#005888',
[IconSet.IconIon]: 'ion-briefcase',
[IconSet.IconDev]: ['devicons devicons-netbeans', 17]
});
set('7z', {
[IconSet.ColorLight]: '#880058',
[IconSet.IconIon]: 'ion-briefcase',
[IconSet.IconDev]: ['devicons devicons-netbeans', 17]
});
set('tgz', {
[IconSet.ColorLight]: '#7900bc',
[IconSet.IconIon]: 'ion-briefcase',
[IconSet.IconDev]: ['devicons devicons-netbeans', 17]
});
set('tar', {
[IconSet.ColorLight]: '#885800',
[IconSet.IconIon]: 'ion-briefcase',
[IconSet.IconDev]: ['devicons devicons-netbeans', 17]
});
set('gz', {
[IconSet.ColorLight]: '#588800',
[IconSet.IconIon]: 'ion-briefcase',
[IconSet.IconDev]: ['devicons devicons-netbeans', 17]
});
set('bzip', {
[IconSet.ColorLight]: '#884300',
[IconSet.IconIon]: 'ion-briefcase',
[IconSet.IconDev]: ['devicons devicons-netbeans', 17]
});
set('msi', {
[IconSet.ColorLight]: '#6f8696',
[IconSet.IconIon]: 'ion-briefcase',
[IconSet.IconDev]: ['devicons devicons-netbeans', 17]
});
set('dmg', {
[IconSet.ColorLight]: '#6f8696',
[IconSet.IconIon]: 'ion-briefcase',
[IconSet.IconDev]: ['devicons devicons-netbeans', 17]
});
set('xpi', {
[IconSet.ColorLight]: '#5bac0d',
[IconSet.IconIon]: 'ion-briefcase',
[IconSet.IconDev]: ['devicons devicons-netbeans', 17]
});
// Settings
set([
'project',
'jscsrc',
'jshintrc',
'csslintrc',
'htmlhintrc',
'xmlhintrc',
'todo',
'classpath',
'properties',
'bowerrc',
'gruntrc',
'jsrc',
'pro',
'editorconfig',
'iml'
], {
[IconSet.ColorLight]: '#777777',
[IconSet.IconIon]: 'ion-ios-gear',
[IconSet.IconDev]: 'devicons devicons-aptana' // Looks like a gear
});
set('csproj', {
[IconSet.ColorLight]: '#5bb552',
[IconSet.IconIon]: ['ion-ios-paper-outline', 18],
[IconSet.IconDev]: 'devicons devicons-aptana' // Looks like a gear
});
set('vbproj', {
[IconSet.ColorLight]: '#486dae',
[IconSet.IconIon]: ['ion-ios-paper-outline', 18],
[IconSet.IconDev]: 'devicons devicons-aptana' // Looks like a gear
});
set('sln', {
[IconSet.ColorLight]: '#87c5de',
[IconSet.IconIon]: ['ion-ios-paper-outline', 18],
[IconSet.IconDev]: 'devicons devicons-aptana' // Looks like a gear
});
set([
'eslintrc',
'eslintrc.js',
'eslintrc.yaml',
'eslintrc.yml',
'eslintrc.json'
], {
[IconSet.ColorLight]: '#3a33d1',
[IconSet.IconIon]: 'ion-ios-gear',
[IconSet.IconDev]: 'devicons devicons-aptana' // Looks like a gear
});
// Other text files
set('txt', {
[IconSet.ColorLight]: '#4192c1',
[IconSet.IconIon]: 'ion-document-text'
});
set('log', {
[IconSet.ColorLight]: '#225dc9',
[IconSet.IconIon]: 'ion-clipboard'
});
set('npmignore', {
[IconSet.ColorLight]: '#cb3837',
[IconSet.IconIon]: ['ion-minus-circled', 14],
[IconSet.IconDev]: 'devicons devicons-npm'
});
set('slugignore', {
[IconSet.ColorLight]: '#0da064',
[IconSet.IconIon]: ['ion-minus-circled', 14]
});
set('dockerignore', {
[IconSet.ColorLight]: '#0296C9',
[IconSet.IconIon]: ['ion-minus-circled', 14]
});
set('jpmignore', {
[IconSet.ColorLight]: '#5bac0d',
[IconSet.IconIon]: ['ion-minus-circled', 14]
});
set(['yml', 'yaml'], {
[IconSet.ColorLight]: '#008000',
[IconSet.IconIon]: ['ion-navicon', 14]
});
set('sqf', {
[IconSet.ColorLight]: '#b9e11f',
[IconSet.IconIon]: 'ion-wand'
});
set(['csv', 'tsv'], {
[IconSet.ColorLight]: '#217346',
[IconSet.IconIon]: 'ion-grid'
});
// LaTeX
set(['tex', 'bib', 'sty'], {
[IconSet.ColorLight]: '#262686',
[IconSet.IconIon]: 'ion-document-text'
});
//Singular Types
set('applescript', {
[IconSet.ColorLight]: '#afafaf',
[IconSet.IconIon]: 'ion-social-apple',
[IconSet.IconDev]: 'devicons devicons-apple'
});
set('textile', {
[IconSet.ColorLight]: '#6f8696',
[IconSet.IconIon]: 'ion-quote'
});
set('matlab', {
[IconSet.ColorLight]: '#014495',
[IconSet.IconIon]: 'ion-clipboard'
});
set('lisp', {
[IconSet.ColorLight]: '#f8c63d',
[IconSet.IconIon]: 'ion-ios-paperplane'
});
set('xsl', {
[IconSet.ColorLight]: '#68217a',
[IconSet.IconIon]: 'ion-code',
[IconSet.IconDev]: 'devicons devicons-code'
});
set('tcl', {
[IconSet.ColorLight]: '#c3b15f',
[IconSet.IconIon]: 'ion-code',
[IconSet.IconDev]: 'devicons devicons-code'
});
set('rst', {
[IconSet.ColorLight]: '#6f8696',
[IconSet.IconIon]: 'ion-ios-paper',
[IconSet.IconDev]: ['devicons devicons-rust', 18]
});
set('d', {
[IconSet.ColorLight]: '#960000',
[IconSet.IconIon]: 'ion-contrast',
[IconSet.IconDev]: 'devicons devicons-dlang'
});
set('r', {
[IconSet.ColorLight]: '#8495C0',
[IconSet.IconIon]: 'ion-ios-analytics'
});
set('map', {
[IconSet.ColorLight]: '#e0591f',
[IconSet.IconIon]: 'ion-ios-photos-outline'
});
}
export function setPrefixes(set: RegisterIcon) {
set(['spec', 'test'], {
[IconSet.ColorLight]: '#146ae3',
[IconSet.IconIon]: 'ion-android-radio-button-on'
});
set('min', {
[IconSet.ColorLight]: '#f28b1d',
[IconSet.IconIon]: ['ion-minus-circled', 14]
});
}
export function setFullFileNames(set: RegisterIcon) {
set('Dockerfile', {
[IconSet.ColorLight]: '#0296C9',
[IconSet.IconIon]: ['ion-navicon', 14],
[IconSet.IconDev]: ['devicons devicons-docker', 18]
});
}
export function setFileNames(set: RegisterFileNameIcon) {
set('package', ['json'], {
[IconSet.ColorLight]: '#cb3837',
[IconSet.IconIon]: 'ion-briefcase',
[IconSet.IconDev]: 'devicons devicons-npm'
});
set(['.brackets', 'brackets'], ['json'], {
[IconSet.ColorLight]: '#0083e8',
[IconSet.IconDev]: 'devicons devicons-brackets'
});
set('gulpfile', ['js', 'ts', 'coffee', 'babel.js'], {
[IconSet.ColorLight]: '#eb4a4b',
[IconSet.IconIon]: 'ion-hammer',
[IconSet.IconDev]: 'devicons devicons-gulp'
});
set('gruntfile', ['js', 'coffee'], {
[IconSet.ColorLight]: '#fba919',
[IconSet.IconIon]: 'ion-hammer',
[IconSet.IconDev]: 'devicons devicons-grunt'
});
}
export function getDefault(): PresetIcon {
return {
[IconSet.IconIon]: 'ion-document',
[IconSet.IconDev]: 'devicons devicons-code_badge'
};
} | the_stack |
import { RootWidgetModel, WidgetModel, VariableModel, FormControlModel } from "../models/models";
import { WidgetCodeGenerator } from "./widget-generator";
import { getUniqueBy } from "../utils";
export class ClassCodeGenerator {
private readonly widgetGenerator: WidgetCodeGenerator;
constructor(widgetGenerator: WidgetCodeGenerator) {
this.widgetGenerator = widgetGenerator;
}
generate(rootWidget: RootWidgetModel, controllerPath: string): string {
let vars: VariableModel[] = this.getChildrenRecursively<VariableModel>(rootWidget.rootChild, w => w.vars);
vars = getUniqueBy(vars, a => a.name);
let controllers: VariableModel[] = this.getChildrenRecursively<VariableModel>(rootWidget.rootChild, w => w.controllers);
controllers = getUniqueBy(controllers, a => a.name);
let formControls: FormControlModel[] = this.getChildrenRecursively<FormControlModel>(rootWidget.rootChild, w => w.formControls);
formControls = getUniqueBy(formControls, a => a.name);
const mixins: string[] = [...new Set([...rootWidget.mixins, ...this.getChildrenRecursively<string>(rootWidget.rootChild, w => w.mixins as any)])];
const rootChildCode = this.widgetGenerator.generateWidgetCode(rootWidget.rootChild, 0);
const widgetName = rootWidget.type;
const hasController = !!rootWidget.controller;
// todo
const isStateful = true;
// const isStateful = rootWidget.stateful;
// route aware
let routeAwareStateMethods = '';
let routeAwareControllerMethods = '';
const routeAware = rootWidget.routeAware;
if (routeAware && hasController) {
routeAwareStateMethods = `
// Called when the top route has been popped off, and the current route shows up.
void didPopNext() {
ctrl.didPopNext();
}
// Called when the current route has been pushed.
void didPush() {
ctrl.didPush();
}
// Called when the current route has been popped off.
void didPop() {
ctrl.didPop();
}
// Called when a new route has been pushed, and the current route is no longer visible.
void didPushNext() {
ctrl.didPushNext();
}`;
routeAwareControllerMethods = `
void didPopNext() {
}
void didPush() {
}
void didPop() {
}
void didPushNext() {
}`;
}
//
// mixins
//
let mixinsCode = '';
if (mixins && mixins.length) {
mixinsCode = ' with ' + mixins.map(a => a).join(', ');
}
//
// build method
//
let buildMethodContent =
`
@override
Widget build(BuildContext context) {
final _pipeProvider = Provider.of<PipeProvider>(context);
final __widget = ${rootChildCode};
return __widget;
}`;
if (hasController) {
rootWidget.imports.push({ path: `${rootWidget.controllerPath || controllerPath}` });
}
rootWidget.imports.push({ path: `package:flutter/material.dart` });
rootWidget.imports.push({ path: `package:flutter_xmllayout_helpers/flutter_xmllayout_helpers.dart` });
rootWidget.imports.push({ path: `package:provider/provider.dart` });
let code = `${rootWidget.imports.map(a => `import '${a.path}';`).join('\n')}`;
//
// widget state
//
if (isStateful) {
code += this.createStatefulWidget(widgetName, mixinsCode, rootWidget, controllers, routeAware, routeAwareStateMethods, buildMethodContent, hasController, formControls);
}
else {
code += this.createStatelessWidget(rootWidget, widgetName, mixinsCode, buildMethodContent);
}
//
// base controller
//
if (hasController) {
code += this.createControllerBase(rootWidget, controllers, vars, formControls, routeAwareControllerMethods);
}
return code;
}
private createControllerBase(rootWidget: RootWidgetModel, controllers: VariableModel[], vars: VariableModel[], formControls: FormControlModel[], routeAwareControllerMethods: string) {
const varsLines: string[] = [
...controllers.filter(a => !a.isPrivate && !a.skipGenerate).map(a => this.createControllerVar(a)),
...vars.map(a => a.type ? `final ${a.name} = new ${a.type}();` : a.name),
...rootWidget.vars.map(a => this.createControllerVar(a)),
...rootWidget.params.filter(a => !!a.name).map(a => this.createControllerVar(a)),
...rootWidget.providers.map(a => this.createControllerVar(a))
];
const disposeLines = [
...controllers.filter(a => !a.isPrivate && !a.skipGenerate).map(a => a.name),
...vars.filter(a => a.type === 'FormGroup').map(a => a.name)
];
let formCode = '';
if (formControls.length) {
formCode = `
Map<String, dynamic> _attachedControllers = Map();
dynamic _attachController(FormGroup formGroup, String controlName, controllerBuilder) {
if (_attachedControllers.containsKey(controlName)) {
final controller = _attachedControllers[controlName];
return controller;
}
final controller = controllerBuilder();
_attachedControllers[controlName] = controller;
formGroup.get(controlName).attachTextEditingController(controller);
return controller;
}`;
}
return `
class ${rootWidget.controller}Base {
bool _loaded = false;
${varsLines.join('\n ')}${formCode}
void _load(BuildContext context) {
if (!_loaded) {
_loaded = true;
didLoad(context);
}
onBuild(context);
}
void didLoad(BuildContext context) {
}
void onBuild(BuildContext context) {
}
void afterFirstBuild(BuildContext context) {
}
${routeAwareControllerMethods}
@mustCallSuper
void dispose() {
${disposeLines.map(a => `${a}.dispose();`).join('\n ')}
}
}`;
}
private createStatelessWidget(rootWidget: RootWidgetModel, widgetName: string, mixinsCode: string, buildMethodContent: string) {
// todo add variables, formGroups, services, controllers, routeAware events...
return `
class ${widgetName} extends StatelessWidget${mixinsCode} {
${rootWidget.params.filter(a => !!a.name).map(a => `final ${a.type ? a.type + ' ' : ''}${a.name}${a.value !== undefined ? ' = ' + a.value : ''};`).join('\n ')}
${widgetName}(${rootWidget.params.length ? '{': ''}
${rootWidget.params.map(a => `${a.required ? '@required ' : ''}${a.name ? `this.${a.name}` : `${(a.type ? a.type + ' ' : '')}${a.superParamName}`}`).join(',\n ')}
${rootWidget.params.length ? '}': ''});
${buildMethodContent}
}
`;
}
private createStatefulWidget(widgetName: string, mixinsCode: string, rootWidget: RootWidgetModel, controllers: VariableModel[], routeAware: boolean, routeAwareStateMethods: string, buildMethodContent: string, hasController: boolean, formControls: FormControlModel[]) {
const stateVarsDeclaration: string[] = [
...(hasController ? [`${rootWidget.controller} ctrl;`] : []),
...controllers.filter(a => !a.skipGenerate).map(a => a.isPrivate ? `final ${a.name} = new ${a.type}();` : `${a.type} ${a.name};`),
...rootWidget.providers.map(a => `${a.type} ${a.name};`),
...rootWidget.vars.map(a => `${a.type} ${a.name};`),
...(routeAware ? [`RouteObserver<Route> _routeObserver;`] : [])
];
const stateVarsInit: string[] = [
...(hasController ? [`ctrl = new ${rootWidget.controller}();`] : []),
...(hasController ? rootWidget.params.filter(a => !!a.name).map(a => `ctrl._${a.name} = widget.${a.name};`) : []),
...controllers.filter(a => !a.isPrivate && !a.skipGenerate).map(a => `${hasController ? `ctrl._${a.name} = `: ''}${a.name} = ${a.value ? a.value : `new ${a.type}()`};`),
...rootWidget.vars.map(a => `${hasController ? `ctrl._${a.name} = `: ''}${a.name} = ${a.value};`),
...(hasController ? [`WidgetsBinding.instance.addPostFrameCallback((_) => ctrl.afterFirstBuild(context));`] : [])
];
const superParams = rootWidget.params
.filter(a => a.superParamName)
.map(a => `${a.superParamName}: ${a.name || a.superParamName}`)
.join(', ');
const superCtor = superParams ? ` : super(${superParams})` : '';
return `
class ${widgetName} extends StatefulWidget {
${rootWidget.params.filter(a => !!a.name).map(a => `final ${a.type ? a.type + ' ' : ''}${a.name};`).join('\n ')}
${widgetName}(${rootWidget.params.length ? '{': ''}
${rootWidget.params.map(a => `${a.required ? '@required ' : ''}${a.name ? `this.${a.name}` : `${(a.type ? a.type + ' ' : '')}${a.superParamName}`}${a.value !== undefined ? ' = ' + a.value : ''}`).join(',\n ')}
${rootWidget.params.length ? '}': ''})${superCtor};
@override
_${widgetName}State createState() => _${widgetName}State();
}
class _${widgetName}State extends State<${widgetName}>${mixinsCode} {
${stateVarsDeclaration.join('\n ')}
${routeAwareStateMethods}
@override
void initState() {
super.initState();${(stateVarsInit.length > 0 ? '\n ' : '') + stateVarsInit.join(`\n `)}
}
@override
void didChangeDependencies() {
super.didChangeDependencies();${routeAware ? `\n _routeObserver = Provider.of<RouteObserver<Route>>(context)..subscribe(this, ModalRoute.of(context));` : ''
}${(rootWidget.providers.length ? '\n ' : '') + rootWidget.providers.map(a => `${hasController ? `ctrl._${a.name} = `: ''}${a.name} = Provider.of<${a.type}>(context);`).join('\n ')
}${hasController ? `\n ctrl._load(context);` : ''}
}
@override
void dispose() {${hasController ? `\n ctrl.dispose();` : ''
}${routeAware ? `\n _routeObserver.unsubscribe(this);` : ''
}${(controllers.length > 0 ? '\n ' : '') + controllers.filter(a => a.isPrivate).map(a => `${a.name}.dispose();`).join('\n ')}
super.dispose();
}
${buildMethodContent}
}`;
}
private createControllerVar(a: VariableModel): string {
a.type = a.type || 'var';
return `${a.type} _${a.name};\n ${a.type} get ${a.name} => _${a.name};`;
}
generateControllerFile(fileName: string, rootWidget: RootWidgetModel): string {
if (!rootWidget.controller) {
return '';
}
let code = `import 'package:flutter/widgets.dart';
import '${fileName}.xml.dart';
class ${rootWidget.controller} extends ${rootWidget.controller}Base {
@override
void didLoad(BuildContext context) {
}
@override
void onBuild(BuildContext context) {
}
@override
void afterFirstBuild(BuildContext context) {
}
@override
void dispose() {
super.dispose();
}
}`;
return code;
}
private getChildrenRecursively<T>(widget: WidgetModel | null, variableGetter: (widget: WidgetModel) => T[]): T[] {
if (!widget) {
return [];
}
const res = variableGetter(widget as any) || [];
if (widget instanceof Array) {
widget = widget[0] as any;
if (!widget) {
return [];
}
}
widget.properties.forEach(prop => {
let property = prop;
if (prop.dataType === 'propertyElement') {
// unwrap the contained property
property = prop.value as any;
}
if (property.dataType === 'widget') {
res.push(...this.getChildrenRecursively(property.value as WidgetModel, variableGetter));
}
else if (property.dataType === 'widgetList') {
(property.value as WidgetModel[]).forEach(w => {
res.push(...this.getChildrenRecursively(w, variableGetter));
});
}
});
if (widget.wrappedWidgets) {
widget.wrappedWidgets.forEach(w => res.push(...this.getChildrenRecursively(w, variableGetter)));
}
return new Array(...new Set(res));
}
} | the_stack |
import {
createStore,
createEvent,
sample,
combine,
forward,
Event,
Store,
} from 'effector'
import {h, using, list, node, spec, remap} from 'forest'
import prettyHtml from 'effector/fixtures/prettyHtml'
declare const act: (cb?: () => any) => Promise<void>
declare const initBrowser: () => Promise<void>
declare const el: HTMLElement
declare const exec: (cb: () => any) => Promise<string[]>
declare const execFunc: <T>(cb: () => Promise<T>) => Promise<T>
beforeEach(async () => {
await initBrowser()
}, 10e3)
describe('update store from nested block', () => {
describe('by sample', () => {
test('with shared store', async () => {
const [s1, s2, s3] = await exec(async () => {
const title = createStore('clicked:')
const items = createStore(['a', 'b'])
await new Promise((rs: any) => {
using(el, {
fn() {
list(items, ({store}) => {
const click = createEvent<MouseEvent>()
sample({
source: {title, id: store},
clock: click,
fn: ({title, id}) => `${title} ${id}`,
target: title,
})
h('b', {
text: combine(store, title, (id, title) => `${id} ${title}`),
handler: {click},
attr: {id: store},
})
})
},
onComplete: rs,
})
})
await act()
const firstItem = el.querySelector('#a') as HTMLDivElement
const secondItem = el.querySelector('#b') as HTMLDivElement
await act(async () => {
firstItem.click()
})
await act(async () => {
secondItem.click()
})
})
expect(s1).toMatchInlineSnapshot(`
"
<b id='a'>a clicked:</b><b id='b'>b clicked:</b>
"
`)
expect(s2).toMatchInlineSnapshot(`
"
<b id='a'>a clicked: a</b><b id='b'>b clicked:</b>
"
`)
expect(s3).toMatchInlineSnapshot(`
"
<b id='a'>a clicked: a</b><b id='b'>b clicked: b</b>
"
`)
})
test('with templated store', async () => {
const [s1, s2, s3] = await exec(async () => {
const blocks = createStore(['A', 'B'])
const items = createStore(['a', 'b'])
await new Promise((rs: any) => {
using(el, {
fn() {
list(blocks, ({store: block}) => {
const title = createStore('clicked:')
list(items, ({store}) => {
const click = createEvent<MouseEvent>()
sample({
source: {title, id: store, block},
clock: click,
fn: ({title, id, block}) => `${title} ${block}${id}`,
target: title,
})
h('b', {
text: combine(
block,
store,
title,
(block, id, title) => `${block}${id} ${title}`,
),
handler: {click},
attr: {
id: combine(block, store, (block, id) => `${block}${id}`),
},
})
})
})
},
onComplete: rs,
})
})
await act()
const firstItem = el.querySelector('#Aa') as HTMLDivElement
const secondItem = el.querySelector('#Bb') as HTMLDivElement
await act(async () => {
firstItem.click()
})
await act(async () => {
secondItem.click()
})
})
expect(s1).toMatchInlineSnapshot(`
"
<b id='Aa'>Aa clicked:</b><b id='Ab'>Ab clicked:</b
><b id='Ba'>Ba clicked:</b><b id='Bb'>Bb clicked:</b>
"
`)
expect(s2).toMatchInlineSnapshot(`
"
<b id='Aa'>Aa clicked: Aa</b><b id='Ab'>Ab clicked: Aa</b
><b id='Ba'>Ba clicked:</b><b id='Bb'>Bb clicked:</b>
"
`)
expect(s3).toMatchInlineSnapshot(`
"
<b id='Aa'>Aa clicked: Aa</b><b id='Ab'>Ab clicked: Aa</b
><b id='Ba'>Ba clicked: Bb</b><b id='Bb'>Bb clicked: Bb</b>
"
`)
})
})
describe('by on', () => {
test('with shared store', async () => {
const [s1, s2, s3] = await exec(async () => {
const title = createStore('clicked:')
const items = createStore(['a', 'b'])
await new Promise((rs: any) => {
using(el, {
fn() {
list(items, ({store}) => {
const click = createEvent<MouseEvent>()
title.on(sample(store, click), (title, id) => `${title} ${id}`)
h('b', {
text: combine(store, title, (id, title) => `${id} ${title}`),
handler: {click},
attr: {id: store},
})
})
},
onComplete: rs,
})
})
await act()
const firstItem = el.querySelector('#a') as HTMLDivElement
const secondItem = el.querySelector('#b') as HTMLDivElement
await act(async () => {
firstItem.click()
})
await act(async () => {
secondItem.click()
})
})
expect(s1).toMatchInlineSnapshot(`
"
<b id='a'>a clicked:</b><b id='b'>b clicked:</b>
"
`)
expect(s2).toMatchInlineSnapshot(`
"
<b id='a'>a clicked: a</b><b id='b'>b clicked:</b>
"
`)
expect(s3).toMatchInlineSnapshot(`
"
<b id='a'>a clicked: a</b><b id='b'>b clicked: a b</b>
"
`)
})
test('with templated store', async () => {
const [s1, s2, s3] = await exec(async () => {
const blocks = createStore(['A', 'B'])
const items = createStore(['a', 'b'])
await new Promise((rs: any) => {
using(el, {
fn() {
list(blocks, ({store: block}) => {
const title = createStore('clicked:')
list(items, ({store}) => {
const id = combine(
block,
store,
(block, id) => `${block}${id}`,
)
const click = createEvent<MouseEvent>()
title.on(sample(id, click), (title, id) => `${title} ${id}`)
h('b', {
text: combine(
block,
store,
title,
(block, id, title) => `${block}${id} ${title}`,
),
handler: {click},
attr: {id},
})
})
})
},
onComplete: rs,
})
})
await act()
const firstItem = el.querySelector('#Aa') as HTMLDivElement
const secondItem = el.querySelector('#Bb') as HTMLDivElement
await act(async () => {
firstItem.click()
})
await act(async () => {
secondItem.click()
})
})
expect(s1).toMatchInlineSnapshot(`
"
<b id='Aa'>Aa clicked:</b><b id='Ab'>Ab clicked:</b
><b id='Ba'>Ba clicked:</b><b id='Bb'>Bb clicked:</b>
"
`)
expect(s2).toMatchInlineSnapshot(`
"
<b id='Aa'>Aa clicked: Aa</b><b id='Ab'>Ab clicked: Aa</b
><b id='Ba'>Ba clicked:</b><b id='Bb'>Bb clicked:</b>
"
`)
expect(s3).toMatchInlineSnapshot(`
"
<b id='Aa'>Aa clicked: Aa</b><b id='Ab'>Ab clicked: Aa</b
><b id='Ba'>Ba clicked: Bb</b><b id='Bb'>Bb clicked: Bb</b>
"
`)
})
describe('handler + on edge cases', () => {
test('#1', async () => {
const updates = await execFunc(async () => {
const updates = [] as number[]
const count = createStore(0)
count.watch(upd => {
updates.push(upd)
})
await new Promise((rs: any) => {
using(el, {
onComplete: rs,
fn() {
const click = createEvent<any>()
count.on(click, x => x + 1)
h('button', {
text: 'Store',
handler: {click},
attr: {id: 'click'},
})
},
})
})
await act(async () => {
el.querySelector<HTMLButtonElement>('#click')!.click()
})
return updates
})
expect(updates).toEqual([0, 1])
})
describe('#2', () => {
test('units in root', async () => {
const [s1, s2, s3, s4] = await exec(async () => {
const inc = createEvent<any>()
const $counter = createStore(0)
$counter.on(inc, count => count + 1)
await new Promise((rs: any) => {
using(el, {
fn() {
/**
model-bound component
same external $counter
*/
h('p', () => {
h('button', {
handler: {click: inc},
text: $counter,
attr: {id: 'a'},
})
})
h('p', () => {
h('button', {
handler: {click: inc},
text: $counter,
attr: {id: 'b'},
})
})
/**
With internal units bounded to external units
$counter -> $myCount, inc <- u
*/
h('p', () => {
const up = createEvent<any>()
const $myCount = createStore(0)
forward({from: $counter, to: $myCount})
forward({from: up, to: inc})
h('button', {
handler: {click: up},
text: $myCount,
attr: {id: 'c'},
})
})
h('p', () => {
const up = createEvent<any>()
const $myCount = createStore(0)
forward({from: $counter, to: $myCount})
forward({from: up, to: inc})
h('button', {
handler: {click: up},
text: $myCount,
attr: {id: 'd'},
})
})
},
onComplete: rs,
})
})
await act()
await act(async () => {
el.querySelector<HTMLButtonElement>('#a')!.click()
})
await act(async () => {
el.querySelector<HTMLButtonElement>('#c')!.click()
})
await act(async () => {
el.querySelector<HTMLButtonElement>('#b')!.click()
})
})
expect(s1).toMatchInlineSnapshot(`
"
<p><button id='a'>0</button></p>
<p><button id='b'>0</button></p>
<p><button id='c'>0</button></p>
<p><button id='d'>0</button></p>
"
`)
expect(s2).toMatchInlineSnapshot(`
"
<p><button id='a'>1</button></p>
<p><button id='b'>1</button></p>
<p><button id='c'>1</button></p>
<p><button id='d'>1</button></p>
"
`)
expect(s3).toMatchInlineSnapshot(`
"
<p><button id='a'>2</button></p>
<p><button id='b'>2</button></p>
<p><button id='c'>2</button></p>
<p><button id='d'>2</button></p>
"
`)
expect(s4).toMatchInlineSnapshot(`
"
<p><button id='a'>3</button></p>
<p><button id='b'>3</button></p>
<p><button id='c'>3</button></p>
<p><button id='d'>3</button></p>
"
`)
})
test('units in using', async () => {
const [s1, s2, s3, s4] = await exec(async () => {
await new Promise((rs: any) => {
using(el, {
fn() {
const inc = createEvent<any>()
const $counter = createStore(0)
$counter.on(inc, count => count + 1)
/**
model-bound component
same external $counter
*/
h('p', () => {
h('button', {
handler: {click: inc},
text: $counter,
attr: {id: 'a'},
})
})
h('p', () => {
h('button', {
handler: {click: inc},
text: $counter,
attr: {id: 'b'},
})
})
/**
With internal units bounded to external units
$counter -> $myCount, inc <- u
*/
h('p', () => {
const up = createEvent<any>()
const $myCount = createStore(0)
forward({from: $counter, to: $myCount})
forward({from: up, to: inc})
h('button', {
handler: {click: up},
text: $myCount,
attr: {id: 'c'},
})
})
h('p', () => {
const up = createEvent<any>()
const $myCount = createStore(0)
forward({from: $counter, to: $myCount})
forward({from: up, to: inc})
h('button', {
handler: {click: up},
text: $myCount,
attr: {id: 'd'},
})
})
},
onComplete: rs,
})
})
await act()
await act(async () => {
el.querySelector<HTMLButtonElement>('#a')!.click()
})
await act(async () => {
el.querySelector<HTMLButtonElement>('#c')!.click()
})
await act(async () => {
el.querySelector<HTMLButtonElement>('#b')!.click()
})
})
expect(s1).toMatchInlineSnapshot(`
"
<p><button id='a'>0</button></p>
<p><button id='b'>0</button></p>
<p><button id='c'>0</button></p>
<p><button id='d'>0</button></p>
"
`)
expect(s2).toMatchInlineSnapshot(`
"
<p><button id='a'>1</button></p>
<p><button id='b'>1</button></p>
<p><button id='c'>1</button></p>
<p><button id='d'>1</button></p>
"
`)
expect(s3).toMatchInlineSnapshot(`
"
<p><button id='a'>2</button></p>
<p><button id='b'>2</button></p>
<p><button id='c'>2</button></p>
<p><button id='d'>2</button></p>
"
`)
expect(s4).toMatchInlineSnapshot(`
"
<p><button id='a'>3</button></p>
<p><button id='b'>3</button></p>
<p><button id='c'>3</button></p>
<p><button id='d'>3</button></p>
"
`)
})
})
describe('#3', () => {
test('external store and event', async () => {
const [s1, s2, s3] = await exec(async () => {
const enable = createEvent<any>()
const disable = createEvent<any>()
const enabled = createStore(false)
.on(enable, () => true)
.on(disable, () => false)
const disabled = enabled.map(is => !is)
await new Promise((rs: any) => {
using(el, {
fn() {
h('button', {
text: 'Enable',
attr: {disabled: enabled, id: 'a'},
handler: {click: enable},
})
h('button', {
text: 'Disable',
attr: {disabled, id: 'b'},
handler: {click: disable},
})
h('button', {
text: 'Disable',
attr: {disabled, id: 'c'},
handler: {click: disable},
})
},
onComplete: rs,
})
})
await act()
await act(async () => {
el.querySelector<HTMLButtonElement>('#a')!.click()
})
await act(async () => {
el.querySelector<HTMLButtonElement>('#b')!.click()
})
})
expect(s1).toMatchInlineSnapshot(`
"
<button id='a'>Enable</button
><button id='b' disabled='true'>Disable</button
><button id='c' disabled='true'>Disable</button>
"
`)
expect(s2).toMatchInlineSnapshot(`
"
<button id='a' disabled='true'>Enable</button
><button id='b'>Disable</button
><button id='c'>Disable</button>
"
`)
expect(s3).toMatchInlineSnapshot(`
"
<button id='a'>Enable</button
><button id='b' disabled='true'>Disable</button
><button id='c' disabled='true'>Disable</button>
"
`)
})
test('internal store and event', async () => {
const [s1, s2, s3] = await exec(async () => {
await new Promise((rs: any) => {
using(el, {
fn() {
const enable = createEvent<any>()
const disable = createEvent<any>()
const enabled = createStore(false)
.on(enable, () => true)
.on(disable, () => false)
const disabled = enabled.map(is => !is)
h('button', {
text: 'Enable',
attr: {disabled: enabled, id: 'a'},
handler: {click: enable},
})
h('button', {
text: 'Disable',
attr: {disabled, id: 'b'},
handler: {click: disable},
})
h('button', {
text: 'Disable',
attr: {disabled, id: 'c'},
handler: {click: disable},
})
},
onComplete: rs,
})
})
await act()
await act(async () => {
el.querySelector<HTMLButtonElement>('#a')!.click()
})
await act(async () => {
el.querySelector<HTMLButtonElement>('#b')!.click()
})
})
expect(s1).toMatchInlineSnapshot(`
"
<button id='a'>Enable</button
><button id='b' disabled='true'>Disable</button
><button id='c' disabled='true'>Disable</button>
"
`)
expect(s2).toMatchInlineSnapshot(`
"
<button id='a' disabled='true'>Enable</button
><button id='b'>Disable</button
><button id='c'>Disable</button>
"
`)
expect(s3).toMatchInlineSnapshot(`
"
<button id='a'>Enable</button
><button id='b' disabled='true'>Disable</button
><button id='c' disabled='true'>Disable</button>
"
`)
})
})
})
})
})
describe('watchers support', () => {
test('from global store', async () => {
const updates = await execFunc(async () => {
const updates = [] as number[]
const inc = createEvent()
const count = createStore(0).on(inc, x => x + 1)
using(el, {
fn() {
count.watch(e => {
updates.push(e)
})
},
})
await act(async () => {
inc()
})
return updates
})
expect(updates).toEqual([0, 1])
})
})
describe('store and event on a same level', () => {
test('on support', async () => {
const updates = await execFunc(async () => {
const updates = [] as number[]
await new Promise((rs: any) => {
using(el, {
onComplete: rs,
fn() {
const delta = createStore(0)
const gotHeight = createEvent<number>()
delta.on(gotHeight, (_, x) => x)
delta.watch(x => {
updates.push(x)
})
h('div', {
text: '~/ - /~',
fn() {
node(() => {
gotHeight(10)
})
},
})
},
})
})
return updates
})
expect(updates).toMatchInlineSnapshot(`
Array [
0,
10,
]
`)
})
test('forward support', async () => {
const updates = await execFunc(async () => {
const updates = [] as number[]
await new Promise((rs: any) => {
using(el, {
onComplete: rs,
fn() {
const delta = createStore(0)
const gotHeight = createEvent<number>()
forward({
from: gotHeight,
to: delta,
})
delta.watch(x => {
updates.push(x)
})
h('div', {
text: '~/ - /~',
fn() {
node(() => {
gotHeight(10)
})
},
})
},
})
})
return updates
})
expect(updates).toMatchInlineSnapshot(`
Array [
0,
10,
]
`)
})
})
describe('event from root, sample and nested store', () => {
it('works when nested store is used', async () => {
const {itemUpdates} = await execFunc(async () => {
const itemUpdates = [] as string[]
const htmlSnapshots = [] as string[]
const selectItem = createEvent<string>()
const currentFile = createStore('foo').on(selectItem, (_, file) => file)
const openFile = createEvent<any>()
const files = createStore([{id: 'foo'}, {id: 'bar'}, {id: 'baz'}])
selectItem.watch(e => {
itemUpdates.push(e)
})
await new Promise((rs: any) => {
using(el, {
fn() {
h('ul', () => {
list({
source: files,
key: 'id',
fields: ['id'],
fn({fields: [id]}) {
h('li', () => {
spec({text: id})
sample({
source: id,
clock: openFile,
target: selectItem,
})
const selected = combine(
id,
currentFile,
(file, selectedFile) => file === selectedFile,
)
h('button', {
handler: {click: openFile},
attr: {disabled: selected, id},
text: 'open',
})
h('span', {
visible: selected,
text: 'selected',
})
})
},
})
})
},
onComplete: rs,
})
})
await act(async () => {
el.querySelector<HTMLButtonElement>('#baz')!.click()
})
htmlSnapshots.push(el.innerHTML)
await act(async () => {
el.querySelector<HTMLButtonElement>('#baz')!.click()
})
htmlSnapshots.push(el.innerHTML)
return {itemUpdates, htmlSnapshots}
})
expect(itemUpdates).toMatchInlineSnapshot(`
Array [
"foo",
"baz",
"bar",
]
`)
})
it('works when nested store is not used', async () => {
const {itemUpdates, htmlSnapshots} = await execFunc(async () => {
const itemUpdates = [] as string[]
const htmlSnapshots = [] as string[]
const selectItem = createEvent<string>()
const currentFile = createStore('foo').on(selectItem, (_, file) => file)
const openFile = createEvent<any>()
const files = createStore([{id: 'foo'}, {id: 'bar'}, {id: 'baz'}])
selectItem.watch(e => {
itemUpdates.push(e)
})
await new Promise((rs: any) => {
using(el, {
fn() {
h('ul', () => {
list({
source: files,
key: 'id',
fields: ['id'],
fn({fields: [id]}) {
h('li', {
fn() {
spec({text: id})
sample({
source: id,
clock: openFile,
target: selectItem,
})
const selected = combine(
id,
currentFile,
(file, selectedFile) => file === selectedFile,
)
h('button', {
handler: {click: openFile},
attr: {disabled: selected},
text: 'open',
})
h('span', {
visible: selected,
text: [id, ' selected'],
})
},
})
},
})
})
},
onComplete: rs,
})
})
const [, , baz] = [...el.querySelectorAll('button')]
await act(async () => {
baz.click()
})
htmlSnapshots.push(el.innerHTML)
await act(async () => {
baz.click()
})
htmlSnapshots.push(el.innerHTML)
return {itemUpdates, htmlSnapshots}
})
expect(itemUpdates).toMatchInlineSnapshot(`
Array [
"foo",
"baz",
"bar",
]
`)
/**
* TODO improve meaningless html code
*/
expect(prettyHtml(htmlSnapshots[0])).toMatchInlineSnapshot(`
"
<ul>
<li>
foo<button disabled='true'>open</button
><span>foo selected</span>
</li>
<li>
bar<button disabled='true'>open</button
><span>bar selected</span>
</li>
<li>
baz<button disabled='true'>open</button
><span>baz selected</span>
</li>
</ul>
"
`)
})
})
describe('getState support', () => {
test('store from same level', async () => {
expect(
await execFunc(async () => {
const results = [] as string[]
const users = createStore([
{id: 1, name: 'alice'},
{id: 2, name: 'bob'},
{id: 3, name: 'carol'},
])
using(el, () => {
h('ul', () => {
list({
source: users,
key: 'id',
fn({store}) {
h('li', () => {
const name = remap(store, 'name')
spec({text: name})
node(() => {
results.push(name.getState())
})
})
},
})
})
})
await act()
return results
}),
).toMatchInlineSnapshot(`
Array [
"alice",
"bob",
"carol",
]
`)
})
test('store from parent level', async () => {
expect(
await execFunc(async () => {
const results = [] as string[]
const users = createStore([
{id: 1, name: 'alice'},
{id: 2, name: 'bob'},
{id: 3, name: 'carol'},
])
using(el, () => {
h('ul', () => {
list({
source: users,
key: 'id',
fn({store}) {
const name = remap(store, 'name')
h('li', () => {
node(() => {
results.push(name.getState())
})
})
},
})
})
})
await act()
return results
}),
).toMatchInlineSnapshot(`
Array [
"alice",
"bob",
"carol",
]
`)
})
})
describe('imperative calls support', () => {
test('event from same level', async () => {
expect(
await execFunc(async () => {
const results = [] as string[]
const users = createStore([
{id: 1, name: 'alice'},
{id: 2, name: 'bob'},
{id: 3, name: 'carol'},
])
using(el, () => {
h('ul', () => {
list({
source: users,
key: 'id',
fn({store}) {
h('li', () => {
const name = remap(store, 'name')
const trigger = createEvent()
trigger.watch(() => {
results.push(name.getState())
})
node(() => {
trigger()
})
})
},
})
})
})
await act()
return results
}),
).toMatchInlineSnapshot(`
Array [
"alice",
"bob",
"carol",
]
`)
})
test('event from parent level', async () => {
expect(
await execFunc(async () => {
const results = [] as string[]
const users = createStore([
{id: 1, name: 'alice'},
{id: 2, name: 'bob'},
{id: 3, name: 'carol'},
])
using(el, () => {
h('ul', () => {
list({
source: users,
key: 'id',
fn({store}) {
const name = remap(store, 'name')
const trigger = createEvent()
trigger.watch(() => {
results.push(name.getState())
})
h('li', () => {
node(() => {
trigger()
})
})
},
})
})
})
await act()
return results
}),
).toMatchInlineSnapshot(`
Array [
"alice",
"bob",
"carol",
]
`)
})
test('event from parent level watched on single child', async () => {
expect(
await execFunc(async () => {
const results = [] as string[]
const users = createStore([
{id: 1, name: 'alice'},
{id: 2, name: 'bob'},
{id: 3, name: 'carol'},
])
using(el, () => {
h('ul', () => {
list({
source: users,
key: 'id',
fn({store}) {
const name = remap(store, 'name')
const trigger = createEvent()
h('li', () => {
trigger.watch(() => {
results.push(name.getState())
})
node(() => {
trigger()
})
})
},
})
})
})
await act()
return results
}),
).toMatchInlineSnapshot(`
Array [
"alice",
"bob",
"carol",
]
`)
})
test('event from root level', async () => {
expect(
await execFunc(async () => {
const results = [] as string[]
const users = createStore([
{id: 1, name: 'alice'},
{id: 2, name: 'bob'},
{id: 3, name: 'carol'},
])
const trigger = createEvent()
using(el, () => {
h('ul', () => {
list({
source: users,
key: 'id',
fn({store}) {
const name = remap(store, 'name')
trigger.watch(() => {
results.push(name.getState())
})
h('li', () => {
node(() => {
trigger()
})
})
},
})
})
})
await act()
trigger()
return results
}),
).toMatchInlineSnapshot(`
Array [
null,
null,
null,
null,
]
`)
})
}) | the_stack |
import * as Path from "path";
import {Class, Lazy, Dictionary, MutableDictionary} from "@swim/util";
import {OutputSettings, OutputStyle, Unicode} from "@swim/codec";
import {MemberFastenerClass, Service, ComponentSet} from "@swim/component";
import type {WorkspaceObserver} from "./WorkspaceObserver";
import {Scope} from "../"; // forward import
import type {TaskConfig} from "../task/Task";
import {PackageScope} from "../" // forward import
import {LibraryScope} from "../" // forward import
/** @public */
export class Workspace<T extends Scope = Scope> extends Service<T> {
constructor() {
super();
this.packageNameMap = {};
this.unscopedPackageNameMap = {};
this.libraryPathMap = {};
}
override readonly observerType?: Class<WorkspaceObserver<T>>;
@ComponentSet<Workspace, PackageScope>({
// avoid cyclic static reference to type: PackageScope
observes: true,
packageLibraryDidChange(libraryScope: LibraryScope): void {
this.owner.callObservers("workspaceLibraryDidChange", libraryScope, this.owner);
},
packageDidChange(packageScope: PackageScope): void {
this.owner.callObservers("workspacePackageDidChange", packageScope, this.owner);
},
})
readonly packages!: ComponentSet<this, PackageScope>;
static readonly packages: MemberFastenerClass<Workspace, "packages">;
readonly packageNameMap: Dictionary<PackageScope>;
readonly unscopedPackageNameMap: Dictionary<PackageScope>;
readonly libraryPathMap: Dictionary<LibraryScope>;
getLibrary(libraryDir: string): LibraryScope | null {
const libraryScope = this.libraryPathMap[libraryDir];
return libraryScope !== void 0 ? libraryScope : null;
}
protected override onAttachRoot(scope: T): void {
super.onAttachRoot(scope);
if (scope instanceof PackageScope) {
this.attachPackage(scope);
} else if (scope instanceof LibraryScope) {
this.attachLibrary(scope);
}
}
protected override onDetachRoot(scope: T): void {
if (scope instanceof PackageScope) {
this.detachPackage(scope);
} else if (scope instanceof LibraryScope) {
this.detachLibrary(scope);
}
super.onDetachRoot(scope);
}
protected attachPackage(packageScope: PackageScope): void {
const packageNameMap = this.packageNameMap as MutableDictionary<PackageScope>;
const unscopedPackageNameMap = this.unscopedPackageNameMap as MutableDictionary<PackageScope>;
this.callObservers("workspaceWillAttachPackage", packageScope, this);
packageNameMap[packageScope.name] = packageScope;
if (packageScope.unscopedName !== void 0) {
unscopedPackageNameMap[packageScope.unscopedName] = packageScope;
}
this.packages.addComponent(packageScope);
this.callObservers("workspaceDidAttachPackage", packageScope, this);
}
protected detachPackage(packageScope: PackageScope): void {
const packageNameMap = this.packageNameMap as MutableDictionary<PackageScope>;
const unscopedPackageNameMap = this.unscopedPackageNameMap as MutableDictionary<PackageScope>;
if (packageNameMap[packageScope.name] === packageScope) {
this.callObservers("workspaceWillDetachPackage", packageScope, this);
if (packageScope.unscopedName !== void 0 && unscopedPackageNameMap[packageScope.unscopedName] === packageScope) {
delete unscopedPackageNameMap[packageScope.unscopedName];
}
delete packageNameMap[packageScope.name];
this.callObservers("workspaceDidDetachPackage", packageScope, this);
}
}
protected attachLibrary(libraryScope: LibraryScope): void {
const libraries = this.libraryPathMap as MutableDictionary<LibraryScope>;
const libraryDir = libraryScope.baseDir.value;
if (libraryDir !== void 0) {
this.callObservers("workspaceWillAttachLibrary", libraryScope, this);
libraries[libraryDir] = libraryScope;
this.callObservers("workspaceDidAttachLibrary", libraryScope, this);
}
}
protected detachLibrary(libraryScope: LibraryScope): void {
const libraries = this.libraryPathMap as MutableDictionary<LibraryScope>;
const libraryDir = libraryScope.baseDir.value;
if (libraryDir !== void 0 && libraries[libraryDir] === libraryScope) {
this.callObservers("workspaceWillDetachLibrary", libraryScope, this);
delete libraries[libraryDir];
this.callObservers("workspaceDidDetachLibrary", libraryScope, this);
}
}
getDependencies(packageNames: string[] | string | undefined): MutableDictionary<PackageScope>;
/** @internal */
getDependencies(packageNames: string[] | string | undefined, packages: MutableDictionary<PackageScope>): MutableDictionary<PackageScope>;
getDependencies(packageNames: string[] | string | undefined, packages?: MutableDictionary<PackageScope>): MutableDictionary<PackageScope> {
if (packageNames === void 0) {
packageNames = Object.keys(this.packageNameMap);
} else if (typeof packageNames === "string") {
packageNames = packageNames.split(",");
}
if (packages === void 0) {
packages = {};
}
for (let i = 0; i < packageNames.length; i += 1) {
const packageName = packageNames[i]!;
let packageScope = this.packageNameMap[packageName];
if (packageScope === void 0) {
packageScope = this.unscopedPackageNameMap[packageName];
}
if (packageScope !== void 0) {
packages = packageScope.getDependencies(packages);
} else {
let output = Unicode.stringOutput(OutputSettings.styled());
output = OutputStyle.redBold(output);
output = output.write("unknown package");
output = OutputStyle.reset(output);
output = output.write(" ");
output = OutputStyle.bold(output);
output = output.write(packageName!);
output = OutputStyle.reset(output);
console.log(output.bind());
}
}
return packages;
}
getDependents(packageNames: string[] | string | undefined): MutableDictionary<PackageScope>;
/** @internal */
getDependents(packageNames: string[] | string | undefined, packages: MutableDictionary<PackageScope>): MutableDictionary<PackageScope>;
getDependents(packageNames: string[] | string | undefined, packages?: MutableDictionary<PackageScope>): MutableDictionary<PackageScope> {
if (packageNames === void 0) {
packageNames = Object.keys(this.packageNameMap);
} else if (typeof packageNames === "string") {
packageNames = packageNames.split(",");
}
if (packages === void 0) {
packages = {};
}
for (let i = 0; i < packageNames.length; i += 1) {
const packageName = packageNames[i]!;
let packageScope = this.packageNameMap[packageName];
if (packageScope === void 0) {
packageScope = this.unscopedPackageNameMap[packageName];
}
if (packageScope !== void 0) {
packages = packageScope.getDependents(packages);
} else {
let output = Unicode.stringOutput(OutputSettings.styled());
output = OutputStyle.redBold(output);
output = output.write("unknown package");
output = OutputStyle.reset(output);
output = output.write(" ");
output = OutputStyle.bold(output);
output = output.write(packageName!);
output = OutputStyle.reset(output);
console.log(output.bind());
}
}
return packages;
}
async forEachPackage(packageNames: string[] | string | undefined, callback: (packageScope: PackageScope) => Promise<void> | void): Promise<void>;
async forEachPackage<S>(packageNames: string[] | string | undefined, callback: (this: S, packageScope: PackageScope) => Promise<void> | void, thisArg?: S): Promise<void>;
async forEachPackage<S>(packageNames: string[] | string | undefined, callback: (this: S, packageScope: PackageScope) => Promise<void> | void, thisArg?: S): Promise<void> {
if (packageNames === void 0) {
packageNames = Object.keys(this.packageNameMap);
} else if (typeof packageNames === "string") {
packageNames = packageNames.split(",");
}
for (let i = 0; i < packageNames.length; i += 1) {
const packageName = packageNames[i]!;
let packageScope = this.packageNameMap[packageName];
if (packageScope === void 0) {
packageScope = this.unscopedPackageNameMap[packageName];
}
if (packageScope !== void 0) {
const result = callback.call(thisArg as S, packageScope);
if (result !== void 0) {
await result;
}
} else {
let output = Unicode.stringOutput(OutputSettings.styled());
output = OutputStyle.redBold(output);
output = output.write("unknown package");
output = OutputStyle.reset(output);
output = output.write(" ");
output = OutputStyle.bold(output);
output = output.write(packageName!);
output = OutputStyle.reset(output);
console.log(output.bind());
}
}
}
async forEachPackageDependency(packageNames: string[] | string | undefined, callback: (packageScope: PackageScope) => Promise<void> | void): Promise<void>;
async forEachPackageDependency<S>(packageNames: string[] | string | undefined, callback: (this: S, packageScope: PackageScope) => Promise<void> | void, thisArg?: S, packages?: MutableDictionary<PackageScope>): Promise<void>;
async forEachPackageDependency<S>(packageNames: string[] | string | undefined, callback: (this: S, packageScope: PackageScope) => Promise<void> | void, thisArg?: S, packages?: MutableDictionary<PackageScope>): Promise<void> {
if (packageNames === void 0) {
packageNames = Object.keys(this.packageNameMap);
} else if (typeof packageNames === "string") {
packageNames = packageNames.split(",");
}
if (packages === void 0) {
packages = {};
}
for (let i = 0; i < packageNames.length; i += 1) {
const packageName = packageNames[i]!;
let packageScope = this.packageNameMap[packageName];
if (packageScope === void 0) {
packageScope = this.unscopedPackageNameMap[packageName];
}
if (packageScope !== void 0) {
await packageScope.forEachDependency(callback, thisArg, packages);
} else {
let output = Unicode.stringOutput(OutputSettings.styled());
output = OutputStyle.redBold(output);
output = output.write("unknown package");
output = OutputStyle.reset(output);
output = output.write(" ");
output = OutputStyle.bold(output);
output = output.write(packageName!);
output = OutputStyle.reset(output);
console.log(output.bind());
}
}
}
runPackageTasks(taskConfigs: TaskConfig | readonly TaskConfig[], packageNames?: string[] | string): Promise<void> {
return this.forEachPackage(packageNames, function (packageScope: PackageScope): Promise<void> {
return packageScope.runTasks(taskConfigs) as unknown as Promise<void>;
}, this);
}
runPackageDependencyTasks(taskConfigs: TaskConfig | readonly TaskConfig[], packageNames?: string[] | string): Promise<void> {
return this.forEachPackageDependency(packageNames, function (packageScope: PackageScope): Promise<void> {
return packageScope.runTasks(taskConfigs) as unknown as Promise<void>;
}, this);
}
runPackageLibraryTasks(taskConfigs: TaskConfig | readonly TaskConfig[], packageNames?: string[] | string, libraryNames?: string[] | string): Promise<void> {
if (typeof libraryNames === "string") {
libraryNames = libraryNames.split(",");
}
return this.forEachPackage(packageNames, function (packageScope: PackageScope): Promise<void> {
return packageScope.runLibraryTasks(taskConfigs, libraryNames);
}, this);
}
runPackageLibraryDependencyTasks(taskConfigs: TaskConfig | readonly TaskConfig[], packageNames?: string[] | string, libraryNames?: string[] | string): Promise<void> {
if (typeof libraryNames === "string") {
libraryNames = libraryNames.split(",");
}
return this.forEachPackageDependency(packageNames, function (packageScope: PackageScope): Promise<void> {
return packageScope.runLibraryTasks(taskConfigs, libraryNames);
}, this);
}
printPackages(): void {
let output = Unicode.stringOutput(OutputSettings.styled());
output = OutputStyle.cyanBold(output);
output = output.write("packages");
output = OutputStyle.reset(output);
console.log(output.bind());
const packages = this.packageNameMap;
for (const packageName in packages) {
output = Unicode.stringOutput(OutputSettings.styled());
output = output.write(" - ");
output = OutputStyle.yellow(output);
output = output.write(packageName);
output = OutputStyle.reset(output);
console.log(output.bind());
}
}
getPackageVersions(packageNames: string[] | string | undefined, version?: string, tag?: string, snapshot?: string | boolean): MutableDictionary<string>;
/** @internal */
getPackageVersions(packageNames: string[] | string | undefined, version: string | undefined, tag: string | undefined, snapshot: string | boolean): MutableDictionary<string>;
getPackageVersions(packageNames: string[] | string | undefined, version?: string, tag?: string, snapshot?: string | boolean): MutableDictionary<string> {
if (packageNames === void 0) {
packageNames = Object.keys(this.packageNameMap);
} else if (typeof packageNames === "string") {
packageNames = packageNames.split(",");
}
const packages: MutableDictionary<string> = {};
for (let i = 0; i < packageNames.length; i += 1) {
const packageName = packageNames[i]!;
let packageScope = this.packageNameMap[packageName];
if (packageScope === void 0) {
packageScope = this.unscopedPackageNameMap[packageName];
}
if (packageScope !== void 0) {
packages[packageScope.name] = packageScope.getVersion(version, tag, snapshot);
} else {
let output = Unicode.stringOutput(OutputSettings.styled());
output = OutputStyle.redBold(output);
output = output.write("unknown package");
output = OutputStyle.reset(output);
output = output.write(" ");
output = OutputStyle.bold(output);
output = output.write(packageName!);
output = OutputStyle.reset(output);
console.log(output.bind());
}
}
return packages;
}
getPackageDependencyVersions(packageNames: string[] | string | undefined, version?: string, tag?: string, snapshot?: string | boolean): MutableDictionary<string>;
/** @internal */
getPackageDependencyVersions(packageNames: string[] | string | undefined, version: string | undefined, tag: string | undefined, snapshot: string | boolean): MutableDictionary<string>;
getPackageDependencyVersions(packageNames: string[] | string | undefined, version?: string, tag?: string, snapshot?: string | boolean): MutableDictionary<string> {
if (packageNames === void 0) {
packageNames = Object.keys(this.packageNameMap);
} else if (typeof packageNames === "string") {
packageNames = packageNames.split(",");
}
let packageVersions: MutableDictionary<string> = {};
for (let i = 0; i < packageNames.length; i += 1) {
const packageName = packageNames[i]!;
let packageScope = this.packageNameMap[packageName];
if (packageScope === void 0) {
packageScope = this.unscopedPackageNameMap[packageName];
}
if (packageScope !== void 0) {
packageVersions = packageScope.getDependencyVersions(version, tag, snapshot, packageVersions);
} else {
let output = Unicode.stringOutput(OutputSettings.styled());
output = OutputStyle.redBold(output);
output = output.write("unknown package");
output = OutputStyle.reset(output);
output = output.write(" ");
output = OutputStyle.bold(output);
output = output.write(packageName!);
output = OutputStyle.reset(output);
console.log(output.bind());
}
}
return packageVersions;
}
@Lazy
static global<T extends Scope>(): Workspace<T> {
return new Workspace();
}
static async load(path: string): Promise<Workspace | null> {
const baseDir = Path.resolve(process.cwd(), path);
const packageScope = await Scope.load(baseDir);
if (packageScope !== null) {
packageScope.mount();
return packageScope.workspace.service;
}
return null;
}
} | the_stack |
import sort from 'fast-sort';
import FuzzySearch from 'fuzzy-search';
import { Nilable, Nullable } from 'tsdef';
import { createSelector } from '@reduxjs/toolkit';
import { OptionIds } from '../action-definitions/option-ids';
import { FileArray, FileData, FileFilter } from '../types/file.types';
import { RootState } from '../types/redux.types';
import { FileSortKeySelector, SortOrder } from '../types/sort.types';
import { FileHelper } from '../util/file-helper';
// Raw selectors
export const selectInstanceId = (state: RootState) => state.instanceId;
export const selectExternalFileActionHandler = (state: RootState) => state.externalFileActionHandler;
export const selectFileActionMap = (state: RootState) => state.fileActionMap;
export const selectFileActionIds = (state: RootState) => state.fileActionIds;
export const selectFileActionData = (fileActionId: string) => (state: RootState) =>
selectFileActionMap(state)[fileActionId];
export const selectToolbarItems = (state: RootState) => state.toolbarItems;
export const selectContextMenuItems = (state: RootState) => state.contextMenuItems;
export const selectFolderChain = (state: RootState) => state.folderChain;
export const selectCurrentFolder = (state: RootState) => {
const folderChain = selectFolderChain(state);
const currentFolder = folderChain.length > 0 ? folderChain[folderChain.length - 1] : null;
return currentFolder;
};
export const selectParentFolder = (state: RootState) => {
const folderChain = selectFolderChain(state);
const parentFolder = folderChain.length > 1 ? folderChain[folderChain.length - 2] : null;
return parentFolder;
};
export const selectRawFiles = (state: RootState) => state.rawFiles;
export const selectFileMap = (state: RootState) => state.fileMap;
export const selectCleanFileIds = (state: RootState) => state.cleanFileIds;
export const selectFileData = (fileId: Nullable<string>) => (state: RootState) =>
fileId ? selectFileMap(state)[fileId] : null;
export const selectHiddenFileIdMap = (state: RootState) => state.hiddenFileIdMap;
export const selectHiddenFileCount = (state: RootState) => Object.keys(selectHiddenFileIdMap(state)).length;
export const selectFocusSearchInput = (state: RootState) => state.focusSearchInput;
export const selectSearchString = (state: RootState) => state.searchString;
export const selectSelectionMap = (state: RootState) => state.selectionMap;
export const selectSelectedFileIds = (state: RootState) => Object.keys(selectSelectionMap(state));
export const selectSelectionSize = (state: RootState) => selectSelectedFileIds(state).length;
export const selectIsFileSelected = (fileId: Nullable<string>) => (state: RootState) =>
!!fileId && !!selectSelectionMap(state)[fileId];
export const selectSelectedFiles = (state: RootState) => {
const fileMap = selectFileMap(state);
return Object.keys(selectSelectionMap(state)).map(id => fileMap[id]);
};
export const selectSelectedFilesForAction = (fileActionId: string) => (state: RootState) => {
const { fileActionMap } = state;
const action = fileActionMap[fileActionId];
if (!action || !action.requiresSelection) return undefined;
return getSelectedFiles(state, action.fileFilter);
};
export const selectSelectedFilesForActionCount = (fileActionId: string) => (state: RootState) =>
getSelectedFilesForAction(state, fileActionId)?.length;
export const selectDisableSelection = (state: RootState) => state.disableSelection;
export const selectFileViewConfig = (state: RootState) => state.fileViewConfig;
export const selectSortActionId = (state: RootState) => state.sortActionId;
export const selectSortOrder = (state: RootState) => state.sortOrder;
export const selectOptionMap = (state: RootState) => state.optionMap;
export const selectOptionValue = (optionId: string) => (state: RootState) => selectOptionMap(state)[optionId];
export const selectThumbnailGenerator = (state: RootState) => state.thumbnailGenerator;
export const selectDoubleClickDelay = (state: RootState) => state.doubleClickDelay;
export const selectIsDnDDisabled = (state: RootState) => state.disableDragAndDrop;
export const selectClearSelectionOnOutsideClick = (state: RootState) => state.clearSelectionOnOutsideClick;
export const selectContextMenuMounted = (state: RootState) => state.contextMenuMounted;
export const selectContextMenuConfig = (state: RootState) => state.contextMenuConfig;
export const selectContextMenuTriggerFile = (state: RootState) => {
const config = selectContextMenuConfig(state);
if (!config || !config.triggerFileId) return null;
const fileMap = selectFileMap(state);
return fileMap[config.triggerFileId] ?? null;
};
// Raw selectors
const getFileActionMap = (state: RootState) => state.fileActionMap;
const getOptionMap = (state: RootState) => state.optionMap;
const getFileMap = (state: RootState) => state.fileMap;
const getFileIds = (state: RootState) => state.fileIds;
const getCleanFileIds = (state: RootState) => state.cleanFileIds;
const getSortActionId = (state: RootState) => state.sortActionId;
const getSortOrder = (state: RootState) => state.sortOrder;
const getSearchString = (state: RootState) => state.searchString;
const _getLastClick = (state: RootState) => state.lastClick;
// Memoized selectors
const makeGetAction = (fileActionSelector: (state: RootState) => Nullable<string>) =>
createSelector([getFileActionMap, fileActionSelector], (fileActionMap, fileActionId) =>
fileActionId && fileActionMap[fileActionId] ? fileActionMap[fileActionId] : null
);
const makeGetOptionValue = (optionId: string, defaultValue: any = undefined) =>
createSelector([getOptionMap], optionMap => {
const value = optionMap[optionId];
if (value === undefined) {
return defaultValue;
}
return value;
});
const makeGetFiles = (fileIdsSelector: (state: RootState) => Nullable<string>[]) =>
createSelector(
[getFileMap, fileIdsSelector],
(fileMap, fileIds): FileArray => fileIds.map(fileId => (fileId && fileMap[fileId] ? fileMap[fileId] : null))
);
const getSortedFileIds = createSelector(
[
getFileIds,
getSortOrder,
makeGetFiles(getFileIds),
makeGetAction(getSortActionId),
makeGetOptionValue(OptionIds.ShowFoldersFirst, false),
],
(fileIds, sortOrder, files, sortAction, showFolderFirst) => {
if (!sortAction) {
// We allow users to set the sort action ID to `null` if they want to use their
// own sorting mechanisms instead of relying on Chonky built-in sort.
return fileIds;
}
const prepareSortKeySelector = (selector: FileSortKeySelector) => (file: Nullable<FileData>) => selector(file);
const sortFunctions: {
asc?: (file: FileData) => any;
desc?: (file: FileData) => any;
}[] = [];
if (showFolderFirst) {
// If option is undefined (relevant actions is not enabled), we don't show
// folders first.
sortFunctions.push({
desc: prepareSortKeySelector(FileHelper.isDirectory),
});
}
if (sortAction.sortKeySelector) {
const configKeyName = sortOrder === SortOrder.ASC ? 'asc' : 'desc';
sortFunctions.push({
[configKeyName]: prepareSortKeySelector(sortAction.sortKeySelector),
});
}
if (sortFunctions.length === 0) return fileIds;
// We copy the array because `fast-sort` mutates it
const sortedFileIds = sort([...files])
.by(sortFunctions as any)
.map(file => (file ? file.id : null));
return sortedFileIds;
}
);
const getSearcher = createSelector(
[makeGetFiles(getCleanFileIds)],
cleanFiles => new FuzzySearch(cleanFiles as FileData[], ['name'], { caseSensitive: false })
);
const getSearchFilteredFileIds = createSelector(
[getCleanFileIds, getSearchString, getSearcher],
(cleanFileIds, searchString, searcher) =>
searchString ? searcher.search(searchString).map(f => f.id) : cleanFileIds
);
const getHiddenFileIdMap = createSelector(
[getSearchFilteredFileIds, makeGetFiles(getCleanFileIds), makeGetOptionValue(OptionIds.ShowHiddenFiles)],
(searchFilteredFileIds, cleanFiles, showHiddenFiles) => {
const searchFilteredFileIdsSet = new Set(searchFilteredFileIds);
const hiddenFileIdMap: any = {};
cleanFiles.forEach(file => {
if (!file) return;
else if (!searchFilteredFileIdsSet.has(file.id)) {
// Hidden by seach
hiddenFileIdMap[file.id] = true;
} else if (!showHiddenFiles && FileHelper.isHidden(file)) {
// Hidden by options
hiddenFileIdMap[file.id] = true;
}
});
return hiddenFileIdMap;
}
);
const getDisplayFileIds = createSelector(
[getSortedFileIds, getHiddenFileIdMap],
/** Returns files that will actually be shown to the user. */
(sortedFileIds, hiddenFileIdMap) => sortedFileIds.filter(id => !id || !hiddenFileIdMap[id])
);
const getLastClickIndex = createSelector(
[_getLastClick, getSortedFileIds],
/** Returns the last click index after ensuring it is actually still valid. */
(lastClick, displayFileIds) => {
if (
!lastClick ||
lastClick.index > displayFileIds.length - 1 ||
lastClick.fileId != displayFileIds[lastClick.index]
) {
return null;
}
return lastClick.index;
}
);
export const selectors = {
// Raw selectors
getFileActionMap,
getOptionMap,
getFileMap,
getFileIds,
getCleanFileIds,
getSortActionId,
getSortOrder,
getSearchString,
_getLastClick,
// Memoized selectors
getSortedFileIds,
getSearcher,
getSearchFilteredFileIds,
getHiddenFileIdMap,
getDisplayFileIds,
getLastClickIndex,
// Parametrized selectors
makeGetAction,
makeGetOptionValue,
makeGetFiles,
};
// Selectors meant to be used outside of Redux code
export const getFileData = (state: RootState, fileId: Nullable<string>) =>
fileId ? selectFileMap(state)[fileId] : null;
export const getIsFileSelected = (state: RootState, file: FileData) => {
// !!! We deliberately don't use `FileHelper.isSelectable` here as we want to
// reflect the state of Redux store accurately.
return !!selectSelectionMap(state)[file.id];
};
export const getSelectedFiles = (state: RootState, ...filters: Nilable<FileFilter>[]) => {
const { fileMap, selectionMap } = state;
const selectedFiles = Object.keys(selectionMap).map(id => fileMap[id]);
const filteredSelectedFiles = filters.reduce(
(prevFiles, filter) => (filter ? prevFiles.filter(filter) : prevFiles),
selectedFiles
);
return filteredSelectedFiles;
};
export const getSelectedFilesForAction = (state: RootState, fileActionId: string) =>
selectSelectedFilesForAction(fileActionId)(state); | the_stack |
function _getById(id: string): HTMLElement {
const el = document.getElementById(id)
if (!el) {
_error(`could not find element with id '${id}'`)
return null as any
}
return el
}
function ensuredSingleCharacterString(el: HTMLInputElement) {
if (el.value.length > 1) {
//using last char is more user friendly as we can click and press a key to use the new char
el.value = el.value.substring(el.value.length-1)
}
}
/**
* checks if a given cell value is a comment with the given configuration
* @param value
* @param csvReadConfig
*/
function isCommentCell(value: string | null, csvReadConfig: CsvReadOptions) {
if (value === null) return false
if (typeof csvReadConfig.comments === 'string' && csvReadConfig.comments !== '') {
return value.trimLeft().startsWith(csvReadConfig.comments)
}
return false
}
/**
* ensures that all rows inside data have the same length
* @param csvParseResult
* @param csvReadConfig
*/
function _normalizeDataArray(csvParseResult: ExtendedCsvParseResult, csvReadConfig: CsvReadOptions, fillString = '') {
const maxCols = csvParseResult.data.reduce((prev, curr) => curr.length > prev ? curr.length : prev, 0)
let someRowWasExpanded = false
let firstRealRowExpandedWasFound = false
for (let i = 0; i < csvParseResult.data.length; i++) {
const row = csvParseResult.data[i];
//first real row (not a comment)
//we might need to expand the quote information array
//this works always because
//case 1: first real row is the row with max columns --> maxCols === row.length --> we push empty and because of spread operator we don't push anything
//case 2: first real row has less rows --> row.length < maxCols --> we push
if (isCommentCell(row[0], csvReadConfig) === false && firstRealRowExpandedWasFound === false) {
firstRealRowExpandedWasFound = true
//if the first row is expanded we need to expand the quote information
if (row.length < maxCols && csvParseResult.columnIsQuoted !== null) {
csvParseResult.columnIsQuoted.push(...Array.from(Array(maxCols - row.length), (p, index) => newColumnQuoteInformationIsQuoted))
}
}
if (row.length < maxCols) {
row.push(...Array.from(Array(maxCols - row.length), (p, index) => fillString))
//comment rows are also expanded...
//but comment rows only export the first cell so they are not really affect the expanded state
if (row.length > 0 && isCommentCell(row[0], csvReadConfig) === false) {
someRowWasExpanded = true
}
}
//because we mutate the array the csv parse result will be changed...
//papaparse not automatically expands the rows
//trim cell values to normalize
// if(trimWhitespace) {
// for (let j = 0; j < row.length; j++) {
// if (row[j] === null || row[j] === undefined) continue
// row[j] = row[j].trim()
// }
// }
}
if (someRowWasExpanded) {
postSetEditorHasChanges(true)
}
}
// /**
// * if we find a comment row merge the cells into one row (else we would need to display additional columns for them)
// * also for export multiple cells in a comment row is bad because we might need to escape the cells because of spaces... e.g. #" test ", aaa
// * @param data
// * @param csvReadConfig
// */
// function mergeCommentRowsIntoOneCell(data: string[][], csvReadConfig: CsvReadOptions): void {
// for (let i = 0; i < data.length; i++) {
// const row = data[i];
// if (isCommentCell(row[0], csvReadConfig)) {
// data[i] = [row.join(',')]// csv.unparse([row])
// }
// }
// }
/**
* returns the rows starting with a comment string
* if comments are treated as normal rows an empty array is returned
* @param data
* @param csvReadConfig
*/
function _getCommentIndices(data: string[][], csvReadConfig: CsvReadOptions): number[] {
if (typeof csvReadConfig.comments !== "string") return []
let commentIndices: number[] = []
for (let i = 0; i < data.length; i++) {
const row = data[i];
//can be null if we added a new row
if (row.length > 0 && row[0] !== null && isCommentCell(row[0], csvReadConfig)) {
commentIndices.push(i)
}
}
return commentIndices
}
/**
* generates column labels: column 1, column 2, ....
* @param index 0 based (where 0 will generate label 1 because this is probably more desired)
*/
function getSpreadsheetColumnLabel(index: number) {
return `column ${index + 1}`
}
//idea from handsontable
const COLUMN_LABEL_BASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
const COLUMN_LABEL_BASE_LENGTH = COLUMN_LABEL_BASE.length
/**
* generates spreadsheet-like column names: A, B, C, ..., Z, AA, AB
*
* DO NOT CHANGE THIS !!! IF YOU NEED TO TAKE A LOOK AT THE TESTS IN THE PLUGIN
* @param {Number} index Column index (starting with 0)
*/
function spreadsheetColumnLetterLabel(index: number) {
//e.g. we have index
/*
0 --> A
1 --> B
...
25 --> Z
26 --> AA
27 --> AB
...
2*26-1=51 --> AZ
52 --> BA
3*26-1=77 --> BZ
*/
let num = index
let columnLabel = ''
//see https://stackoverflow.com/questions/34813980/getting-an-array-of-column-names-at-sheetjs
while (num >= 0) {
columnLabel = COLUMN_LABEL_BASE[num % 26] + columnLabel //this will cover the last "bit" in range 0-25 so we get the last letter
num = Math.floor(num / 26) - 1 //e.g. 27 would get us 27/26 = 1 but this is actually AB so we do -1
//e.g. 52 -> first (right) letter is A, 52 / 26 = 2 --> 2-1 = 1 = B --> BA
//so this works only because the number is not changed before getting the first letter
}
return columnLabel
}
//this is ~ 2x slower because of parseInt (and maybe a bit more because of String.fromCharCode)
//this is the original from handson table
// function spreadsheetColumnLabel(index: number): string {
// let dividend = index + 1
// let columnLabel = ''
// let modulo
// while (dividend > 0) {
// modulo = (dividend - 1) % COLUMN_LABEL_BASE_LENGTH;
// columnLabel = String.fromCharCode(65 + modulo) + columnLabel;
// dividend = parseInt((dividend - modulo) / COLUMN_LABEL_BASE_LENGTH, 10);
// }
// return columnLabel;
// }
/**
* adds a new column at the end
* @param {boolean} selectNewColumn true: scrolls to the new column
*/
function addColumn(selectNewColumn = true) {
if (!hot) throw new Error('table was null')
const numCols = hot.countCols()
hot.alter('insert_col', numCols) //inserted data contains null but papaparse correctly unparses it as ''
//in hooks we insert a null column in the header
//we could get 0 cols...
checkIfHasHeaderReadOptionIsAvailable(false)
const pos = hot.getSelected() //undefined or [[startRow, startCol, endRow, endCol], ...] (could select not connected cells...)
if (pos && pos.length === 1) { //only 1 row selected
if (selectNewColumn) {
hot.selectCell(pos[0][0], numCols)
}
}
}
/**
* adds a new row at the end
* @param {boolean} selectNewRow true: scrolls to the new row
*/
function addRow(selectNewRow = true) {
if (!hot) throw new Error('table was null')
// const headerCells = hot.getColHeader()
const numRows = hot.countRows()
hot.alter('insert_row', numRows) //inserted data contains null but papaparse correctly unparses it as ''
// hot.populateFromArray(numRows, 0, [headerCells.map(p => '')])
if (selectNewRow) {
hot.selectCell(numRows, 0)
}
checkAutoApplyHasHeader()
}
/**
* returns the visual start row index of the first selection range
* the index is the visual one seen in the ui (e.g. changed when we reorder rows)
*/
function _getSelectedVisualRowIndex(): number | null {
if (!hot) throw new Error('table was null')
const selections = hot.getSelected()
if (!selections?.length) return null
const firstSelection = selections[0]
const rowIndex = firstSelection[0] //start row
return rowIndex
}
/**
* returns the visual start col index of the first selection range
* the index is the visual one seen in the ui (e.g. changed when we reorder rows)
*/
function _getSelectedVisualColIndex(): number | null {
if (!hot) throw new Error('table was null')
const selections = hot.getSelected()
if (!selections?.length) return null
const firstSelection = selections[0]
const rowIndex = firstSelection[1] //start row
return rowIndex
}
/**
* adds a new row above the current row
*/
function insertRowAbove() {
if (isReadonlyMode) return
_insertRowInternal(false)
}
/**
* adds a new row below the current row
*/
function insertRowBelow() {
if (isReadonlyMode) return
_insertRowInternal(true)
}
function _insertRowInternal(belowCurrRow: boolean) {
if (!hot) throw new Error('table was null')
const currRowIndex = _getSelectedVisualRowIndex()
const currColIndex = _getSelectedVisualColIndex()
if (currRowIndex === null || currColIndex === null) return
const targetRowIndex = currRowIndex + (belowCurrRow ? 1 : 0)
// const test = hot.toPhysicalRow(targetRowIndex) //also not working when rows are reordered...
hot.alter('insert_row', targetRowIndex)
//undefined should not happen but just in case
const focusBehavior = initialConfig?.insertRowBehavior ?? 'focusFirstCellNewRow'
switch (focusBehavior) {
case 'focusFirstCellNewRow': {
//new row, first cell
hot.selectCell(targetRowIndex, 0)
break;
}
case 'keepRowKeepColumn': {
//before insert row, same column
hot.selectCell(targetRowIndex + (belowCurrRow ? -1 : 1), currColIndex)
break;
}
default: notExhaustiveSwitch(focusBehavior)
}
checkAutoApplyHasHeader()
}
/**
* adds a new row above the current row
*/
function insertColLeft(selectNewCol = true, preserveSelectedRow = true) {
if (isReadonlyMode) return
_insertColInternal(false)
}
/**
* adds a new col below the current row
*/
function insertColRight(selectNewCol = true, preserveSelectedRow = true) {
if (isReadonlyMode) return
_insertColInternal(true)
}
function _insertColInternal(afterCurrCol: boolean) {
if (!hot) throw new Error('table was null')
const currColIndex = _getSelectedVisualColIndex()
const currRowIndex = _getSelectedVisualRowIndex()
if (currRowIndex === null || currColIndex === null) return
const targetColIndex = currColIndex + (afterCurrCol ? 1 : 0)
// const test = hot.toPhysicalColumn(targetColIndex) //also not working when columns are reordered...
hot.alter('insert_col', targetColIndex)
//undefined should not happen but just in case
const focusBehavior = initialConfig?.insertColBehavior ?? 'keepRowKeepColumn'
switch (focusBehavior) {
case 'keepRowFocusNewColumn': {
//new row, first cell
hot.selectCell(currRowIndex, targetColIndex)
break;
}
case 'keepRowKeepColumn': {
//before insert row, same column
hot.selectCell(currRowIndex, targetColIndex + (afterCurrCol ? -1 : 1))
break;
}
default: notExhaustiveSwitch(focusBehavior)
}
}
/**
* removes a row by index
* @param {number} index 0 based
*/
function removeRow(index: number) {
if (isReadonlyMode) return
if (!hot) throw new Error('table was null')
hot.alter('remove_row', index)
checkIfHasHeaderReadOptionIsAvailable(false)
}
/**
* removes a column by index
* @param {number} index the visual column index
*/
function removeColumn(index: number) {
if (isReadonlyMode) return
if (!hot) throw new Error('table was null')
hot.alter('remove_col', index)
//keep header in sync with the number of columns
//this is done in the hooks
//we could get 0 cols...
checkIfHasHeaderReadOptionIsAvailable(false)
}
/**
* called on every render...
* so we only need to add the css rule and never remove it
* @param instance
* @param td
* @param row
* @param col
* @param prop
* @param value
* @param cellProperties
*/
function commentValueRenderer(instance: Handsontable, td: HTMLTableDataCellElement, row: number, col: number, prop: any, value: string | null, cellProperties: any) {
//@ts-ignore
Handsontable.renderers.TextRenderer.apply(this, arguments);
// console.log(value)
if (value !== null && col === 0 && isCommentCell(value, defaultCsvReadOptions)) {
// td.classList.add('comment-row')
if (td && td.nextSibling) {
(td.nextSibling as HTMLElement).title = warningTooltipTextWhenCommentRowNotFirstCellIsUsed;
}
//make the whole row a comment
if (td && td.parentElement) {
td.parentElement.classList.add('comment-row')
}
}
// if (cellProperties._isComment) {
// td.classList.add('comment-row')
// } else {
// // td.style.backgroundColor = ''
// }
}
(Handsontable.renderers as any).registerRenderer('commentValueRenderer', commentValueRenderer);
// function invisiblesCellValueRenderer(instance: Handsontable, td: HTMLTableDataCellElement, row: number, col: number, prop: any, value: string | null, cellProperties: any) {
// //@ts-ignore
// const val = Handsontable.helper.stringify(value);
// console.log(value)
// td.innerText = val.replace(/\ /g, '·').replace(/\ /g, '⇥')
// return td
// }
// (Handsontable.renderers as any).registerRenderer('invisiblesCellValueRenderer', invisiblesCellValueRenderer);
/**
* overwrites a single option
* warns and returns if the an option name is not found in targetOptions or options
* @param {*} targetOptions the target options obj
* @param {*} options the option to take the value from
* @param {*} optionName the option name
*/
function _setOption<T extends {}>(targetOptions: T, options: T, optionName: keyof T) {
if (options.hasOwnProperty(optionName)) {
if (targetOptions.hasOwnProperty(optionName) === false) {
_error(`target options object has not property '${optionName}'`)
return
}
targetOptions[optionName] = options[optionName]
} else {
_error(`options object has not property '${optionName}'`)
}
}
/**
* overwrites the current read options with the given options
* also updates the ui to display the new options
* @param {*} options
*/
function setCsvReadOptionsInitial(options: CsvReadOptions) {
const keys = Object.keys(defaultCsvReadOptions)
for (const key of keys) {
_setOption(defaultCsvReadOptions, options, key as keyof CsvReadOptions)
}
//set ui from (maybe updated) options
const el1 = _getById('delimiter-string') as HTMLInputElement
el1.value = defaultCsvReadOptions.delimiter
//disabled
// const el2 = _getById('skip-empty-lines')
// if (el2) {
// //currently disabled...
// el2.checked = csvReadOptions.skipEmptyLines
// }
const el3 = _getById('has-header') as HTMLInputElement
el3.checked = defaultCsvReadOptions._hasHeader
const el4 = _getById('comment-string') as HTMLInputElement
el4.value = defaultCsvReadOptions.comments === false ? '' : defaultCsvReadOptions.comments
const el5 = _getById('quote-char-string') as HTMLInputElement
el5.value = defaultCsvReadOptions.quoteChar
const el6 = _getById('escape-char-string') as HTMLInputElement
el6.value = defaultCsvReadOptions.escapeChar
}
/**
* overwrites the current write options with the given options
* also updates the ui to display the new options
* @param {*} options
*/
function setCsvWriteOptionsInitial(options: CsvWriteOptions) {
const keys = Object.keys(defaultCsvWriteOptions)
for (const key of keys) {
_setOption(defaultCsvWriteOptions, options, key as keyof CsvWriteOptions)
}
//set ui from (maybe updated) options
const el1 = _getById('has-header-write') as HTMLInputElement
el1.checked = defaultCsvWriteOptions.header
const el2 = _getById('delimiter-string-write') as HTMLInputElement
el2.value = defaultCsvWriteOptions.delimiter
const el3 = _getById('comment-string-write') as HTMLInputElement
el3.value = defaultCsvWriteOptions.comments === false ? '' : defaultCsvWriteOptions.comments
const el4 = _getById('quote-char-string-write') as HTMLInputElement
el4.value = defaultCsvWriteOptions.quoteChar
const el5 = _getById('escape-char-string-write') as HTMLInputElement
el5.value = defaultCsvWriteOptions.quoteChar
const el6 = _getById('quote-all-fields-write') as HTMLInputElement
el6.checked = defaultCsvWriteOptions.quoteAllFields
}
/**
* checks if the has header read option must be disabled or not
* and sets the needed state
*
* if has header option is available (when we have enough data rows) we also check
* {@link headerRowWithIndex} if we have only comment rows
*
* see https://forum.handsontable.com/t/table-with-only-header-row/2915 and
* and https://github.com/handsontable/handsontable/issues/735
* seems like with default headers it's not possible to only have headers?
* @returns false: force changes (settings want headers but is not possible with data), true: all ok
*/
function checkIfHasHeaderReadOptionIsAvailable(isInitialRender: boolean): boolean {
const data = getData() //this also includes header rows
const el = hasHeaderReadOptionInput
let canSetOption = false
if (isInitialRender) {
canSetOption = data.length > 1
}
else {
if (defaultCsvReadOptions._hasHeader) {
canSetOption = data.length >= 1 //we already stored the header row so we have data + 1 rows...
} else {
canSetOption = data.length > 1 //no header ... to enable header we need 2 rows
}
}
if (canSetOption) {
//but we could have only comments --> no header available
const firstRow = getFirstRowWithIndex()
if (firstRow === null && !el.checked) { //if el.checked is true then we already have a header row...
canSetOption = false
}
}
if (canSetOption) {
// el.removeAttribute('disabled')
} else {
// el.setAttribute('disabled', '')
defaultCsvReadOptions._hasHeader = false
el.checked = false
return false
}
return true
}
//from https://stackoverflow.com/questions/27078285/simple-throttle-in-js ... from underscore
function throttle(func: Function, wait: number) {
var context: any, args: any, result: any;
var timeout: any = null;
var previous = 0;
var later = function () {
previous = Date.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function (this: any) {
var now = Date.now();
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout) {
timeout = setTimeout(later, remaining);
}
return result
}
}
//from https://davidwalsh.name/javascript-debounce-function
function debounce(func: Function, wait: number, immediate = false) {
var timeout: any;
return function (this: any) {
var context = this, args = arguments;
var later = function () {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
function _error(text: string) {
postVsError(text)
throw new Error(text)
}
/**
* apply the first part of the settings from initialConfig, called before parsing data
* some options have impact e.g. on how to parse the data...
* some options depend on the state after parse ... e.g. has before/after comments?
*/
function setupAndApplyInitialConfigPart1(initialConfig: CsvEditSettings | undefined, initialVars: InitialVars) {
//first apply the initial vars
{
_setIsWatchingSourceFileUiIndicator(initialVars.isWatchingSourceFile)
}
if (initialConfig === undefined) {
//probably in browser here...
toggleOptionsBar(true)
showCommentsBtn.style.display = 'none'
hideCommentsBtn.style.display = 'initial'
return
}
highlightCsvComments = initialConfig.highlightCsvComments
enableWrapping = initialConfig.enableWrapping
initialColumnWidth = initialConfig.initialColumnWidth
newColumnQuoteInformationIsQuoted = initialConfig.newColumnQuoteInformationIsQuoted
fixedRowsTop = Math.max(initialConfig.initiallyFixedRowsTop, 0)
fixedColumnsLeft = Math.max(initialConfig.initiallyFixedColumnsLeft, 0)
disableBorders = initialConfig.disableBorders
if (disableBorders) {
const style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = `.vscode-dark td, th { border: 0px !important; }`;
document.getElementsByTagName('head')[0].appendChild(style);
}
changeFontSizeInPx(initialConfig.fontSizeInPx)
//apply settings from extension
const copyReadOptions = {
...defaultCsvReadOptions
}
let _readOption_hasHeader = initialConfig.readOption_hasHeader === 'true' ? true : false
if (_readOption_hasHeader) {
isFirstHasHeaderChangedEvent = true
} else {
//when this is not initially set then we don't want to clear the undo after we enabled this option
isFirstHasHeaderChangedEvent = false
}
setCsvReadOptionsInitial({
...copyReadOptions,
delimiter: initialConfig.readOption_delimiter,
comments: initialConfig.readOption_comment,
_hasHeader: _readOption_hasHeader,
escapeChar: initialConfig.readOption_escapeChar,
quoteChar: initialConfig.readOption_quoteChar
})
const copyWriteOptions = {
...defaultCsvReadOptions
}
setCsvWriteOptionsInitial({
...copyWriteOptions,
comments: initialConfig.writeOption_comment,
delimiter: initialConfig.writeOption_delimiter,
header: initialConfig.writeOption_hasHeader === 'true' ? true : false,
escapeChar: initialConfig.writeOption_escapeChar,
quoteChar: initialConfig.writeOption_quoteChar,
quoteAllFields: initialConfig.quoteAllFields,
retainQuoteInformation: initialConfig.retainQuoteInformation,
quoteEmptyOrNullFields: initialConfig.quoteEmptyOrNullFields === 'true' ? true : false,
})
switch (initialConfig.optionsBarAppearance) {
case 'expanded': {
toggleOptionsBar(false)
break
}
case 'collapsed': {
toggleOptionsBar(true)
break
}
// case 'remember': {
// toggleOptionsBar(true)
// break
// }
default: {
_error(`unknown optionsBarAppearance: ${initialConfig.optionsBarAppearance}`)
notExhaustiveSwitch(initialConfig.optionsBarAppearance)
break;
}
}
if (initialConfig.initiallyHideComments) {
showCommentsBtn.style.display = 'initial'
hideCommentsBtn.style.display = 'none'
}
else {
showCommentsBtn.style.display = 'none'
hideCommentsBtn.style.display = 'initial'
}
//--- other options
fixedRowsTopInfoSpan.innerText = fixedRowsTop + ''
fixedColumnsTopInfoSpan.innerText = fixedColumnsLeft + ''
isReadonlyMode = initialConfig.initiallyIsInReadonlyMode
_updateToggleReadonlyModeUi()
setNumbersStyleUi(initialConfig.initialNumbersStyle)
}
/* - maybe we get the collapse states and store them across sessions see
CsvEditSettings
.readOptionsAppearance: remember option
.writeOptionsAppearance: remember option
.previewOptionsAppearance: remember option
--- */
function _getVsState(): VsState {
if (!vscode) return _createDefaultVsState()
const state = vscode.getState()
if (!state) return _createDefaultVsState()
return state
}
function _createDefaultVsState(): VsState {
return {
previewIsCollapsed: true,
readOptionIsCollapsed: true,
writeOptionIsCollapsed: true
}
}
function _setReadOptionCollapsedVsState(isCollapsed: boolean) {
if (vscode) {
// const lastState = _getVsState()
// const newState = {
// ...lastState,
// readOptionIsCollapsed: isCollapsed
// }
// console.log(JSON.stringify(newState));
// vscode.setState(newState)
}
}
function _setWriteOptionCollapsedVsState(isCollapsed: boolean) {
if (vscode) {
// const lastState = _getVsState()
// const newState: VsState = {
// ...lastState,
// writeOptionIsCollapsed: isCollapsed
// }
// vscode.setState(newState)
}
}
function _setPreviewCollapsedVsState(isCollapsed: boolean) {
if (vscode) {
// const lastState = _getVsState()
// const newState: VsState = {
// ...lastState,
// previewIsCollapsed: isCollapsed
// }
// vscode.setState(newState)
}
}
/**
* a custom search method for the table
* @param query
* @param value
*/
function customSearchMethod(query: string | undefined | null, value: string | undefined | null): boolean {
if (query === null || query === undefined || value === null || value === undefined) return false
if (query === '') return false
if (!findWidgetInstance.findOptionMatchCaseCache) {
value = value.toLowerCase()
query = query.toLowerCase()
}
if (findWidgetInstance.findOptionTrimCellCache) {
value = value.trim()
}
if (findWidgetInstance.findOptionUseRegexCache) {
if (findWidgetInstance.findWidgetCurrRegex === null) {
throw new Error('should not happen...')
}
//this is needed when we use the global flag and we call exec on the same regex instance
// findWidgetInstance.findWidgetCurrRegex.lastIndex = 0
let result = findWidgetInstance.findWidgetCurrRegex.exec(value)
if (findWidgetInstance.findOptionMatchWholeCellCache) {
if (result !== null && result.length > 0) {
return result[0] === value
}
}
return result !== null
} else {
if (findWidgetInstance.findOptionMatchWholeCellCache) {
return value === query
}
return value.indexOf(query) !== -1
}
}
//taken from https://github.com/MikeMcl/big.js/blob/master/big.js
// const numberRegex = /-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?/
function afterHandsontableCreated(hot: Handsontable) {
/**
* @param row Selection start visual row index.
* @param column Selection start visual column index.
* @param row2 Selection end visual row index.
* @param column2 Selection end visual column index.
*/
const afterSelectionHandler = (row: number, column: number, row2: number, column2: number) => {
if (getIsSidePanelCollapsed()) {
//not update stats (might be costly and we don't display stats anyway)
} else {
calculateStats(row, column, row2, column2)
}
}
hot.addHook('afterSelection', afterSelectionHandler as any)
const afterRowOrColsCountChangeHandler = () => {
statRowsCount.innerText = `${hot.countRows()}`
statColsCount.innerText = `${hot.countCols()}`
}
hot.addHook('afterRemoveRow', afterRowOrColsCountChangeHandler)
hot.addHook('afterCreateRow', afterRowOrColsCountChangeHandler)
hot.addHook('afterCreateCol', afterRowOrColsCountChangeHandler)
hot.addHook('afterRemoveCol', afterRowOrColsCountChangeHandler)
statSelectedRows.innerText = `${0}`
statSelectedCols.innerText = `${0}`
statSelectedNotEmptyCells.innerText = `${0}`
statSumOfNumbers.innerText = `${0}`
statSelectedCellsCount.innerText = `${0}`
statRowsCount.innerText = `${hot.countRows()}`
statColsCount.innerText = `${hot.countCols()}`
}
/**
* recalculates the stats (even if they are not visible)
*/
function recalculateStats() {
const selectedRanges = hot!.getSelected()
if (!selectedRanges) return
const firstRange = selectedRanges[0]
calculateStats(...firstRange)
}
/**
* the stats calculation func
* @param row
* @param column
* @param row2
* @param column2
*/
function _calculateStats(row: number, column: number, row2: number, column2: number) {
let numbersStyleToUse = getNumbersStyleFromUi()
let rowsCount = Math.abs(row2 - row) + 1
let colsCount = Math.abs(column2 - column) + 1
statSelectedRows.innerText = `${rowsCount}`
// statSelectedNotEmptyRows
statSelectedCols.innerText = `${colsCount}`
// statSelectedNotEmptyCols
statSelectedCellsCount.innerText = `${rowsCount * colsCount}`
//could be improved when we iterate over cols when we have less cols than rows??
let notEmptyCount = 0
let numbersSum = Big(0)
let containsInvalidNumbers = false
let minR = Math.min(row, row2)
let maxR = Math.max(row, row2)
for (let index = minR; index <= maxR; index++) {
const data = hot!.getDataAtRow(index)
let minC = Math.min(column, column2)
let maxC = Math.max(column, column2)
for (let i = minC; i <= maxC; i++) {
const el = data[i]
if (el !== '' && el !== null) {
notEmptyCount++
if (!containsInvalidNumbers) {
const firstCanonicalNumberStringInCell = getFirstCanonicalNumberStringInCell(el, numbersStyleToUse)
if (firstCanonicalNumberStringInCell === null) continue
try {
let _num = Big(firstCanonicalNumberStringInCell)
numbersSum = numbersSum.plus(_num)
} catch (error) {
console.warn(`could not create or add number to statSumOfNumbers at row: ${index}, col: ${i}`, error)
containsInvalidNumbers = true
}
}
}
}
}
statSelectedNotEmptyCells.innerText = `${notEmptyCount}`
statSumOfNumbers.innerText = containsInvalidNumbers
? `Some invalid num`
: `${formatBigJsNumber(numbersSum, numbersStyleToUse)}`
}
const calculateStats = throttle(_calculateStats, 300) as typeof _calculateStats
/**
* returns the first number string in the cell value
*/
function getFirstCanonicalNumberStringInCell(cellValue: string, numbersStyle: NumbersStyle): string | null {
// let thousandSeparatorsMatches = numbersStyle.thousandSeparatorReplaceRegex.exec(cellValue)
let cellContent = cellValue
let thousandSeparatorsMatches
while (thousandSeparatorsMatches = numbersStyle.thousandSeparatorReplaceRegex.exec(cellValue)) {
let replaceContent = thousandSeparatorsMatches[0].replace(numbersStyle.thousandSeparator, '')
cellContent = cellContent.replace(thousandSeparatorsMatches[0], replaceContent)
}
let numberRegexRes = numbersStyle.regex.exec(cellContent)
if (!numberRegexRes || numberRegexRes.length === 0) return null
//this not longer has thousand separators...
//big js only accepts numbers in en format (3.14)
return numberRegexRes[0].replace(/\,/gm, '.')
}
const knownNumberStylesMap: KnownNumberStylesMap = {
"en": {
key: 'en',
/**
* this allows:
* 0(000)
* 0(000).0(000)
* .0(000)
* all repeated with - in front (negative numbers)
* all repeated with e0(000) | e+0(000) | e-0(000)
*/
regex: /-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?/,
thousandSeparator: /(\,| )/gm,
thousandSeparatorReplaceRegex: /((\,| )\d{3})+/gm
},
"non-en": {
key: 'non-en',
/**
* this allows:
* 0(000)
* 0(000),0(000)
* ,0(000)
* all repeated with - in front (negative numbers)
* all repeated with e0(000) | e+0(000) | e-0(000)
*/
regex: /-?(\d+(\,\d*)?|\,\d+)(e[+-]?\d+)?/,
thousandSeparator: /(\.| )/gm,
thousandSeparatorReplaceRegex: /((\.| )\d{3})+/gm
}
}
/**
* sets the number style ui from the given nubmer style
*/
function setNumbersStyleUi(numbersStyleToUse: CsvEditSettings["initialNumbersStyle"]) {
numbersStyleEnRadio.checked = false
numbersStyleNonEnRadio.checked = false
switch (numbersStyleToUse) {
case 'en': {
numbersStyleEnRadio.checked = true
break
}
case 'non-en': {
numbersStyleNonEnRadio.checked = true
break
}
default:
notExhaustiveSwitch(numbersStyleToUse)
}
}
/**
* returns the number style from the ui
*/
function getNumbersStyleFromUi(): NumbersStyle {
if (numbersStyleEnRadio.checked) return knownNumberStylesMap['en']
if (numbersStyleNonEnRadio.checked) return knownNumberStylesMap['non-en']
postVsWarning(`Got unknown numbers style from ui, defaulting to 'en'`)
return knownNumberStylesMap['en']
}
//don't know how to type this properly without typeof ...
const b = new Big(1)
function formatBigJsNumber(bigJsNumber: typeof b, numbersStyleToUse: NumbersStyle): string {
switch (numbersStyleToUse.key) {
case 'en': {
//@ts-ignore
bigJsNumber.format = {
decimalSeparator: '.',
groupSeparator: '', //TODO or maybe whitespace?
}
break
}
case 'non-en': {
//@ts-ignore
bigJsNumber.format = {
decimalSeparator: ',',
groupSeparator: '', //TODO or maybe whitespace?
}
break
}
default:
notExhaustiveSwitch(numbersStyleToUse.key)
}
//@ts-ignore
return bigJsNumber.toFormat()
} | the_stack |
export const testData: number[][] = [
[0,0,5,13,9,1,0,0,0,0,13,15,10,15,5,0,0,3,15,2,0,11,8,0,0,4,12,0,0,8,8,0,0,5,8,0,0,9,8,0,0,4,11,0,1,12,7,0,0,2,14,5,10,12,0,0,0,0,6,13,10,0,0,0],
[0,0,0,12,13,5,0,0,0,0,0,11,16,9,0,0,0,0,3,15,16,6,0,0,0,7,15,16,16,2,0,0,0,0,1,16,16,3,0,0,0,0,1,16,16,6,0,0,0,0,1,16,16,6,0,0,0,0,0,11,16,10,0,0],
[0,0,0,4,15,12,0,0,0,0,3,16,15,14,0,0,0,0,8,13,8,16,0,0,0,0,1,6,15,11,0,0,0,1,8,13,15,1,0,0,0,9,16,16,5,0,0,0,0,3,13,16,16,11,5,0,0,0,0,3,11,16,9,0],
[0,0,7,15,13,1,0,0,0,8,13,6,15,4,0,0,0,2,1,13,13,0,0,0,0,0,2,15,11,1,0,0,0,0,0,1,12,12,1,0,0,0,0,0,1,10,8,0,0,0,8,4,5,14,9,0,0,0,7,13,13,9,0,0],
[0,0,0,1,11,0,0,0,0,0,0,7,8,0,0,0,0,0,1,13,6,2,2,0,0,0,7,15,0,9,8,0,0,5,16,10,0,16,6,0,0,4,15,16,13,16,1,0,0,0,0,3,15,10,0,0,0,0,0,2,16,4,0,0],
[0,0,12,10,0,0,0,0,0,0,14,16,16,14,0,0,0,0,13,16,15,10,1,0,0,0,11,16,16,7,0,0,0,0,0,4,7,16,7,0,0,0,0,0,4,16,9,0,0,0,5,4,12,16,4,0,0,0,9,16,16,10,0,0],
[0,0,0,12,13,0,0,0,0,0,5,16,8,0,0,0,0,0,13,16,3,0,0,0,0,0,14,13,0,0,0,0,0,0,15,12,7,2,0,0,0,0,13,16,13,16,3,0,0,0,7,16,11,15,8,0,0,0,1,9,15,11,3,0],
[0,0,7,8,13,16,15,1,0,0,7,7,4,11,12,0,0,0,0,0,8,13,1,0,0,4,8,8,15,15,6,0,0,2,11,15,15,4,0,0,0,0,0,16,5,0,0,0,0,0,9,15,1,0,0,0,0,0,13,5,0,0,0,0],
[0,0,9,14,8,1,0,0,0,0,12,14,14,12,0,0,0,0,9,10,0,15,4,0,0,0,3,16,12,14,2,0,0,0,4,16,16,2,0,0,0,3,16,8,10,13,2,0,0,1,15,1,3,16,8,0,0,0,11,16,15,11,1,0],
[0,0,11,12,0,0,0,0,0,2,16,16,16,13,0,0,0,3,16,12,10,14,0,0,0,1,16,1,12,15,0,0,0,0,13,16,9,15,2,0,0,0,0,3,0,9,11,0,0,0,0,0,9,15,4,0,0,0,9,12,13,3,0,0],
[0,0,1,9,15,11,0,0,0,0,11,16,8,14,6,0,0,2,16,10,0,9,9,0,0,1,16,4,0,8,8,0,0,4,16,4,0,8,8,0,0,1,16,5,1,11,3,0,0,0,12,12,10,10,0,0,0,0,1,10,13,3,0,0],
[0,0,0,0,14,13,1,0,0,0,0,5,16,16,2,0,0,0,0,14,16,12,0,0,0,1,10,16,16,12,0,0,0,3,12,14,16,9,0,0,0,0,0,5,16,15,0,0,0,0,0,4,16,14,0,0,0,0,0,1,13,16,1,0],
[0,0,5,12,1,0,0,0,0,0,15,14,7,0,0,0,0,0,13,1,12,0,0,0,0,2,10,0,14,0,0,0,0,0,2,0,16,1,0,0,0,0,0,6,15,0,0,0,0,0,9,16,15,9,8,2,0,0,3,11,8,13,12,4],
[0,2,9,15,14,9,3,0,0,4,13,8,9,16,8,0,0,0,0,6,14,15,3,0,0,0,0,11,14,2,0,0,0,0,0,2,15,11,0,0,0,0,0,0,2,15,4,0,0,1,5,6,13,16,6,0,0,2,12,12,13,11,0,0],
[0,0,0,8,15,1,0,0,0,0,1,14,13,1,1,0,0,0,10,15,3,15,11,0,0,7,16,7,1,16,8,0,0,9,16,13,14,16,5,0,0,1,10,15,16,14,0,0,0,0,0,1,16,10,0,0,0,0,0,10,15,4,0,0],
[0,5,12,13,16,16,2,0,0,11,16,15,8,4,0,0,0,8,14,11,1,0,0,0,0,8,16,16,14,0,0,0,0,1,6,6,16,0,0,0,0,0,0,5,16,3,0,0,0,1,5,15,13,0,0,0,0,4,15,16,2,0,0,0],
[0,0,0,8,15,1,0,0,0,0,0,12,14,0,0,0,0,0,3,16,7,0,0,0,0,0,6,16,2,0,0,0,0,0,7,16,16,13,5,0,0,0,15,16,9,9,14,0,0,0,3,14,9,2,16,2,0,0,0,7,15,16,11,0],
[0,0,1,8,15,10,0,0,0,3,13,15,14,14,0,0,0,5,10,0,10,12,0,0,0,0,3,5,15,10,2,0,0,0,16,16,16,16,12,0,0,1,8,12,14,8,3,0,0,0,0,10,13,0,0,0,0,0,0,11,9,0,0,0],
[0,0,10,7,13,9,0,0,0,0,9,10,12,15,2,0,0,0,4,11,10,11,0,0,0,0,1,16,10,1,0,0,0,0,12,13,4,0,0,0,0,0,12,1,12,0,0,0,0,1,10,2,14,0,0,0,0,0,11,14,5,0,0,0],
[0,0,6,14,4,0,0,0,0,0,11,16,10,0,0,0,0,0,8,14,16,2,0,0,0,0,1,12,12,11,0,0,0,0,0,0,0,11,3,0,0,0,0,0,0,5,11,0,0,0,1,4,4,7,16,2,0,0,7,16,16,13,11,1],
[0,0,3,13,11,7,0,0,0,0,11,16,16,16,2,0,0,4,16,9,1,14,2,0,0,4,16,0,0,16,2,0,0,0,16,1,0,12,8,0,0,0,15,9,0,13,6,0,0,0,9,14,9,14,1,0,0,0,2,12,13,4,0,0],
[0,0,0,2,16,16,2,0,0,0,0,4,16,16,2,0,0,1,4,12,16,12,0,0,0,7,16,16,16,12,0,0,0,0,3,10,16,14,0,0,0,0,0,8,16,12,0,0,0,0,0,6,16,16,2,0,0,0,0,2,12,15,4,0],
[0,0,8,16,5,0,0,0,0,1,13,11,16,0,0,0,0,0,10,0,13,3,0,0,0,0,3,1,16,1,0,0,0,0,0,9,12,0,0,0,0,0,3,15,5,0,0,0,0,0,14,15,8,8,3,0,0,0,7,12,12,12,13,1],
[0,1,8,12,15,14,4,0,0,3,11,8,8,12,12,0,0,0,0,0,2,13,7,0,0,0,0,2,15,12,1,0,0,0,0,0,13,5,0,0,0,0,0,0,9,13,0,0,0,0,7,8,14,15,0,0,0,0,14,15,11,2,0,0],
[0,0,0,0,12,2,0,0,0,0,0,6,14,1,0,0,0,0,4,16,7,8,0,0,0,0,13,9,0,16,6,0,0,6,16,10,11,16,0,0,0,0,5,10,13,16,0,0,0,0,0,0,6,16,0,0,0,0,0,0,12,8,0,0],
[0,0,12,8,8,7,0,0,0,3,16,16,11,7,0,0,0,2,14,1,0,0,0,0,0,5,14,5,0,0,0,0,0,2,15,16,9,0,0,0,0,0,0,2,16,2,0,0,0,0,4,8,16,4,0,0,0,0,11,14,9,0,0,0],
[0,0,1,13,14,3,0,0,0,0,8,16,13,2,0,0,0,2,16,16,3,0,0,0,0,3,16,12,1,0,0,0,0,5,16,14,5,0,0,0,0,3,16,16,16,16,6,0,0,1,14,16,16,16,12,0,0,0,3,12,15,14,7,0],
[0,0,0,8,14,14,2,0,0,0,0,6,10,15,11,0,0,0,0,0,0,14,10,0,0,2,8,11,12,16,8,0,0,8,16,16,16,16,7,0,0,0,0,0,11,15,1,0,0,0,0,9,16,7,0,0,0,0,0,12,13,1,0,0],
[0,0,10,11,4,0,0,0,0,0,10,15,13,13,1,0,0,0,8,11,0,14,4,0,0,0,0,13,15,13,0,0,0,1,11,16,16,0,0,0,0,1,15,3,9,10,0,0,0,0,14,6,15,10,0,0,0,0,8,14,7,1,0,0],
[0,0,9,13,7,0,0,0,0,0,12,16,16,2,0,0,0,0,12,13,16,6,0,0,0,0,6,16,16,14,0,0,0,0,0,0,2,16,3,0,0,0,0,0,0,9,10,0,0,0,3,7,12,14,16,2,0,0,7,12,12,12,11,0],
[0,0,10,14,11,3,0,0,0,4,16,13,6,14,1,0,0,4,16,2,0,11,7,0,0,8,16,0,0,10,5,0,0,8,16,0,0,14,4,0,0,8,16,0,1,16,1,0,0,4,16,1,11,15,0,0,0,0,11,16,12,3,0,0],
[0,0,2,13,8,0,0,0,0,0,6,16,16,6,0,0,0,0,5,15,13,11,0,0,0,0,0,7,16,15,0,0,0,0,0,0,0,14,3,0,0,0,0,0,0,7,11,0,0,0,0,3,4,4,16,2,0,0,2,15,13,14,13,2],
[0,2,13,16,16,16,11,0,0,5,16,10,5,4,1,0,0,6,16,7,3,0,0,0,0,9,16,16,16,6,0,0,0,3,8,4,11,15,0,0,0,0,0,1,12,15,0,0,0,0,4,13,16,6,0,0,0,2,16,15,8,0,0,0],
[0,6,13,5,8,8,1,0,0,8,16,16,16,16,6,0,0,6,16,9,6,4,0,0,0,6,16,16,15,5,0,0,0,0,4,5,15,12,0,0,0,0,0,3,16,9,0,0,0,1,8,13,15,3,0,0,0,4,16,15,3,0,0,0],
[0,0,0,5,14,2,0,0,0,0,1,13,11,0,0,0,0,0,5,16,2,0,0,0,0,0,6,15,5,0,0,0,0,1,15,16,15,11,1,0,0,2,13,14,1,12,9,0,0,0,4,16,7,13,9,0,0,0,0,5,16,15,3,0],
[0,3,15,8,8,6,0,0,0,4,16,16,16,13,2,0,0,3,16,9,2,0,0,0,0,2,16,16,15,3,0,0,0,0,7,6,12,9,0,0,0,0,0,1,14,10,0,0,0,0,5,14,15,2,0,0,0,1,15,14,1,0,0,0],
[0,0,6,14,10,2,0,0,0,0,15,15,13,15,3,0,0,2,16,10,0,13,9,0,0,1,16,5,0,12,5,0,0,0,16,3,0,13,6,0,0,1,15,5,6,13,1,0,0,0,16,11,14,10,0,0,0,0,7,16,11,1,0,0],
[0,0,13,10,1,0,0,0,0,5,16,14,7,0,0,0,0,4,16,8,14,0,0,0,0,2,14,16,16,6,0,0,0,0,1,4,9,13,1,0,0,0,0,0,0,13,6,0,0,0,5,8,5,9,14,0,0,0,13,13,15,16,13,0],
[0,0,7,7,13,16,4,0,0,0,13,13,6,12,7,0,0,0,10,4,10,11,1,0,0,0,8,16,10,0,0,0,0,3,14,16,0,0,0,0,0,8,8,11,5,0,0,0,0,4,10,9,8,0,0,0,0,1,11,16,6,0,0,0],
[0,1,9,16,13,7,0,0,0,7,14,4,10,12,0,0,0,6,15,9,16,11,0,0,0,0,9,11,7,14,0,0,0,0,0,0,0,15,2,0,0,0,0,0,0,11,6,0,0,3,13,8,5,14,5,0,0,0,9,14,13,10,1,0],
[0,0,11,10,12,4,0,0,0,0,12,13,9,16,1,0,0,0,7,13,11,16,0,0,0,0,1,16,14,4,0,0,0,0,10,16,13,0,0,0,0,0,14,7,12,7,0,0,0,4,14,4,12,13,0,0,0,1,11,14,12,4,0,0],
[0,0,0,9,15,1,0,0,0,0,4,16,12,0,0,0,0,0,15,14,2,11,3,0,0,4,16,9,4,16,10,0,0,9,16,11,13,16,2,0,0,0,9,16,16,14,0,0,0,0,0,8,16,6,0,0,0,0,0,9,16,2,0,0],
[0,0,0,0,12,5,0,0,0,0,0,2,16,12,0,0,0,0,1,12,16,11,0,0,0,2,12,16,16,10,0,0,0,6,11,5,15,6,0,0,0,0,0,1,16,9,0,0,0,0,0,2,16,11,0,0,0,0,0,3,16,8,0,0],
[0,0,0,9,15,12,0,0,0,0,4,7,7,14,0,0,0,0,0,0,0,13,3,0,0,4,9,8,10,13,1,0,0,4,16,15,16,16,6,0,0,0,0,0,14,3,0,0,0,0,0,9,12,0,0,0,0,0,0,11,7,0,0,0],
[0,0,9,16,16,16,5,0,0,1,14,10,8,16,8,0,0,0,0,0,7,16,3,0,0,3,8,11,15,16,11,0,0,8,16,16,15,11,3,0,0,0,2,16,7,0,0,0,0,0,8,16,1,0,0,0,0,0,13,10,0,0,0,0],
[0,0,9,16,13,6,0,0,0,0,6,5,16,16,0,0,0,0,0,8,15,5,0,0,0,0,0,5,14,3,0,0,0,0,0,0,9,15,2,0,0,0,0,0,0,11,12,0,0,0,4,8,11,15,12,0,0,0,11,14,12,8,0,0],
[0,1,15,4,0,0,0,0,0,2,16,16,16,14,2,0,0,6,16,11,8,8,3,0,0,5,16,11,5,0,0,0,0,0,11,14,14,1,0,0,0,0,0,5,16,7,0,0,0,0,6,16,16,4,0,0,0,0,14,14,4,0,0,0],
[0,0,0,1,11,9,0,0,0,0,0,7,16,13,0,0,0,0,4,14,16,9,0,0,0,10,16,11,16,8,0,0,0,0,0,3,16,6,0,0,0,0,0,3,16,8,0,0,0,0,0,5,16,10,0,0,0,0,0,2,14,6,0,0],
[0,0,2,15,13,3,0,0,0,0,10,15,11,15,0,0,0,3,16,6,0,10,0,0,0,4,16,8,0,3,8,0,0,8,14,3,0,4,8,0,0,3,15,1,0,3,7,0,0,0,14,11,6,14,5,0,0,0,4,12,15,6,0,0],
[0,0,1,15,13,1,0,0,0,0,7,16,14,8,0,0,0,8,12,9,2,13,2,0,0,7,9,1,0,6,6,0,0,5,9,0,0,3,9,0,0,0,15,2,0,8,12,0,0,0,9,15,13,16,6,0,0,0,0,13,14,8,0,0],
[0,0,0,5,14,12,2,0,0,0,7,15,8,14,4,0,0,0,6,2,3,13,1,0,0,0,0,1,13,4,0,0,0,0,1,11,9,0,0,0,0,8,16,13,0,0,0,0,0,5,14,16,11,2,0,0,0,0,0,6,12,13,3,0],
[0,0,0,3,15,10,1,0,0,0,0,11,10,16,4,0,0,0,0,12,1,15,6,0,0,0,0,3,4,15,4,0,0,0,0,6,15,6,0,0,0,4,15,16,9,0,0,0,0,0,13,16,15,9,3,0,0,0,0,4,9,14,7,0],
[0,0,3,12,16,16,6,0,0,0,10,11,7,16,11,0,0,0,0,0,2,14,10,0,0,5,11,8,9,16,3,0,0,9,16,16,16,16,9,0,0,1,4,9,16,6,0,0,0,0,0,11,14,0,0,0,0,0,4,16,5,0,0,0],
[0,0,4,8,16,5,0,0,0,0,9,16,8,11,0,0,0,0,5,10,0,13,2,0,0,0,0,13,4,15,2,0,0,0,0,9,16,8,0,0,0,0,8,15,14,5,0,0,0,0,16,5,14,4,0,0,0,0,6,16,12,1,0,0],
[0,0,0,1,14,14,3,0,0,0,0,10,11,13,8,0,0,0,0,7,0,13,8,0,0,0,0,0,7,15,1,0,0,4,8,12,15,4,0,0,0,6,16,16,6,0,0,0,0,0,2,12,12,4,2,0,0,0,0,1,13,16,5,0],
[0,0,2,14,15,5,0,0,0,0,10,16,16,15,1,0,0,3,16,10,10,16,4,0,0,5,16,0,0,14,6,0,0,5,16,6,0,12,7,0,0,1,15,13,4,13,6,0,0,0,11,16,16,15,0,0,0,0,2,11,13,4,0,0],
[0,0,0,0,12,13,1,0,0,0,0,8,16,15,2,0,0,0,10,16,16,12,0,0,0,4,16,16,16,13,0,0,0,4,7,4,16,6,0,0,0,0,0,1,16,8,0,0,0,0,0,1,16,8,0,0,0,0,0,0,12,12,0,0],
[0,0,0,1,9,11,0,0,0,0,0,13,16,16,0,0,0,0,0,12,7,14,0,0,0,0,0,0,14,7,0,0,0,0,5,12,12,0,0,0,0,7,16,16,6,0,0,0,0,4,9,13,16,11,4,0,0,0,0,0,9,13,3,0],
[0,0,0,10,13,1,0,0,0,1,11,12,7,0,0,0,0,2,16,12,0,0,0,0,0,4,16,11,0,0,0,0,0,4,16,15,8,4,0,0,0,4,16,16,13,16,6,0,0,0,7,16,7,13,14,0,0,0,0,7,15,15,5,0],
[0,1,10,15,11,1,0,0,0,3,8,8,11,12,0,0,0,0,0,5,14,15,1,0,0,0,0,11,15,2,0,0,0,0,0,4,15,2,0,0,0,0,0,0,12,10,0,0,0,0,3,4,10,16,1,0,0,0,13,16,15,10,0,0],
[0,0,10,15,14,4,0,0,0,0,4,6,13,16,2,0,0,0,0,3,16,9,0,0,0,0,0,1,16,6,0,0,0,0,0,0,10,12,0,0,0,0,0,0,1,16,4,0,0,1,9,5,6,16,7,0,0,0,14,12,15,11,2,0],
[0,0,6,13,16,6,0,0,0,3,16,14,15,16,1,0,0,0,5,0,8,16,2,0,0,0,0,0,8,16,3,0,0,3,15,16,16,16,9,0,0,5,13,14,16,11,3,0,0,0,0,12,15,1,0,0,0,0,4,16,7,0,0,0],
[0,0,14,16,14,6,0,0,0,0,7,10,16,16,3,0,0,0,0,5,16,16,1,0,0,0,0,2,16,8,0,0,0,0,0,0,12,13,1,0,0,0,0,0,4,16,7,0,0,0,5,9,14,16,7,0,0,0,13,16,16,10,1,0],
[0,3,16,16,14,7,1,0,0,1,9,9,15,16,4,0,0,0,0,7,16,12,1,0,0,0,0,9,16,2,0,0,0,0,0,3,15,7,0,0,0,0,0,0,9,15,0,0,0,1,10,10,16,16,3,0,0,2,13,16,12,5,0,0],
[0,0,0,6,16,4,0,0,0,0,1,13,15,1,0,0,0,1,11,16,5,0,0,0,0,8,16,10,0,10,6,0,0,12,16,8,9,16,12,0,0,2,15,16,16,16,7,0,0,0,0,4,16,11,0,0,0,0,0,7,16,3,0,0],
[0,0,0,9,10,0,0,0,0,0,7,16,7,0,0,0,0,0,13,13,1,0,0,0,0,0,15,7,0,0,0,0,0,4,16,15,12,7,0,0,0,2,16,12,4,11,10,0,0,0,8,14,5,9,14,0,0,0,0,6,12,14,9,0],
[0,0,0,10,11,0,0,0,0,0,9,16,6,0,0,0,0,0,15,13,0,0,0,0,0,0,14,10,0,0,0,0,0,1,15,12,8,2,0,0,0,0,12,16,16,16,10,1,0,0,7,16,12,12,16,4,0,0,0,9,15,12,5,0],
[0,0,5,14,0,0,0,0,0,0,12,9,0,0,0,0,0,0,15,3,0,0,0,0,0,1,16,0,0,0,0,0,0,1,16,2,7,4,0,0,0,3,16,16,16,16,9,0,0,0,15,15,4,10,16,0,0,0,4,14,16,12,7,0],
[0,0,0,9,9,0,0,0,0,0,3,16,9,0,0,0,0,3,14,10,0,2,0,0,0,10,16,5,7,15,1,0,0,2,11,15,16,13,1,0,0,0,0,7,16,3,0,0,0,0,0,6,15,0,0,0,0,0,0,4,16,5,0,0],
[0,0,6,12,13,6,0,0,0,6,16,9,12,16,2,0,0,7,16,9,15,13,0,0,0,0,11,15,16,4,0,0,0,0,0,12,10,0,0,0,0,0,3,16,4,0,0,0,0,0,1,16,2,0,0,0,0,0,6,11,0,0,0,0],
[0,0,0,0,14,7,0,0,0,0,0,13,16,9,0,0,0,0,10,16,16,7,0,0,0,7,16,8,16,2,0,0,0,1,5,6,16,6,0,0,0,0,0,4,16,6,0,0,0,0,0,2,16,6,0,0,0,0,0,0,12,11,0,0],
[0,1,13,15,12,12,5,0,0,4,16,8,8,6,0,0,0,7,13,0,0,0,0,0,0,8,15,13,15,7,0,0,0,1,6,5,8,12,0,0,0,0,0,0,12,11,0,0,0,0,2,13,14,1,0,0,0,3,14,10,1,0,0,0],
[0,0,1,13,10,0,0,0,0,7,16,16,16,7,0,0,0,8,16,13,10,15,0,0,0,8,16,2,2,15,3,0,0,5,15,2,0,12,7,0,0,1,15,6,2,16,3,0,0,0,11,15,13,16,0,0,0,0,1,15,14,8,0,0],
[0,1,12,13,4,0,0,0,0,4,16,16,16,3,0,0,0,4,16,16,16,10,0,0,0,0,6,16,14,16,0,0,0,0,0,0,0,16,4,0,0,0,0,0,0,13,7,0,0,1,2,3,7,14,10,0,0,2,12,16,14,12,3,0],
[0,0,13,13,8,2,0,0,0,5,16,16,16,12,0,0,0,1,15,12,0,0,0,0,0,0,12,13,7,1,0,0,0,0,8,16,16,12,0,0,0,0,0,4,9,16,3,0,0,0,1,5,14,15,1,0,0,0,10,16,16,6,0,0],
[0,0,0,0,9,13,0,0,0,0,0,2,16,16,1,0,0,0,0,5,9,15,0,0,0,0,0,0,5,14,0,0,0,0,0,3,15,7,0,0,0,7,16,16,11,0,0,0,0,0,11,14,16,7,3,0,0,0,0,0,9,15,9,0],
[0,3,5,14,13,6,0,0,0,9,16,12,10,12,0,0,0,6,16,3,12,11,0,0,0,1,13,10,16,6,0,0,0,0,10,16,10,0,0,0,0,1,15,16,10,0,0,0,0,0,16,12,16,0,0,0,0,0,3,15,16,5,0,0],
[0,0,0,0,11,15,4,0,0,0,0,3,16,16,12,0,0,0,0,8,14,16,12,0,0,0,0,5,10,16,6,0,0,1,7,11,16,13,0,0,0,9,16,16,14,1,0,0,0,3,8,14,16,9,0,0,0,0,0,1,11,16,12,0],
[0,0,10,12,10,0,0,0,0,3,16,16,16,4,0,0,0,7,15,3,8,13,0,0,0,8,12,0,0,14,1,0,0,8,12,0,0,7,8,0,0,5,13,0,0,4,8,0,0,0,14,8,0,10,8,0,0,0,7,12,13,12,4,0],
[0,0,4,14,11,0,0,0,0,3,15,15,16,9,0,0,0,8,13,0,3,15,1,0,0,8,12,0,0,8,6,0,0,8,12,0,0,8,8,0,0,5,13,1,0,8,8,0,0,2,15,14,12,15,6,0,0,0,5,16,15,8,0,0],
[0,0,0,1,14,13,1,0,0,0,0,1,16,16,3,0,0,5,11,15,16,16,0,0,0,4,15,16,16,15,0,0,0,0,0,8,16,7,0,0,0,0,0,10,16,3,0,0,0,0,0,8,16,6,0,0,0,0,0,2,13,15,2,0],
[0,0,3,14,16,14,0,0,0,0,13,13,13,16,2,0,0,0,1,0,9,15,0,0,0,0,9,12,15,16,10,0,0,4,16,16,16,11,3,0,0,0,4,9,14,2,0,0,0,0,2,15,9,0,0,0,0,0,4,13,1,0,0,0],
[0,0,0,10,15,3,0,0,0,0,7,16,11,0,0,0,0,0,13,15,1,0,0,0,0,0,15,11,0,0,0,0,0,0,16,13,8,1,0,0,0,0,15,16,16,15,6,0,0,0,10,16,14,16,14,2,0,0,1,9,15,16,11,0],
[0,2,13,15,10,4,0,0,0,0,5,4,13,15,2,0,0,0,0,0,11,16,4,0,0,0,0,0,16,12,0,0,0,0,0,0,13,11,0,0,0,0,0,0,8,13,0,0,0,1,6,8,14,12,0,0,0,2,12,14,11,1,0,0],
[0,1,13,15,2,0,0,0,0,6,15,15,9,0,0,0,0,9,8,10,13,0,0,0,0,5,3,12,12,0,0,0,0,0,3,16,6,0,0,0,0,5,15,15,1,0,0,0,0,6,16,15,12,12,11,0,0,1,11,13,16,16,12,0],
[0,0,0,1,16,5,0,0,0,0,0,5,16,11,0,0,0,0,0,12,16,11,0,0,0,7,12,16,16,7,0,0,0,4,8,12,16,4,0,0,0,0,0,9,16,2,0,0,0,0,0,10,16,2,0,0,0,0,0,3,13,5,0,0],
[0,0,2,7,15,13,1,0,0,0,14,12,9,14,8,0,0,0,2,0,0,12,8,0,0,0,0,0,0,13,6,0,0,5,16,16,16,16,5,0,0,2,5,7,13,14,2,0,0,0,0,1,15,5,0,0,0,0,0,11,9,0,0,0],
[0,0,0,9,16,4,0,0,0,1,9,16,13,2,0,0,0,14,16,14,8,0,0,0,1,15,15,5,16,9,0,0,0,5,16,16,16,8,0,0,0,0,2,13,16,1,0,0,0,0,0,11,13,0,0,0,0,0,0,11,13,0,0,0],
[0,0,0,10,11,0,0,0,0,0,3,16,10,0,0,0,0,0,8,16,0,0,0,0,0,0,12,14,0,0,0,0,0,0,14,16,15,6,0,0,0,0,12,16,12,15,6,0,0,0,7,16,10,13,14,0,0,0,0,9,13,11,6,0],
[0,0,13,16,15,4,0,0,0,0,9,8,13,16,3,0,0,0,0,0,13,16,7,0,0,0,0,1,16,12,0,0,0,0,0,0,15,10,0,0,0,0,0,0,8,15,0,0,0,0,3,6,15,16,7,0,0,0,15,16,16,11,1,0],
[0,0,0,1,12,8,1,0,0,0,0,4,16,16,1,0,0,0,1,13,16,11,0,0,0,1,11,16,16,12,0,0,0,2,12,8,16,10,0,0,0,0,0,0,15,8,0,0,0,0,0,4,16,4,0,0,0,0,0,3,13,4,0,0],
[0,4,14,16,16,12,1,0,0,2,12,7,14,16,6,0,0,0,0,5,16,10,0,0,0,0,0,4,16,7,0,0,0,0,0,4,16,6,0,0,0,0,0,1,15,11,0,0,0,1,8,10,16,10,0,0,0,5,16,16,15,1,0,0],
[0,0,9,13,14,5,0,0,0,4,16,10,13,16,0,0,0,0,13,15,14,16,1,0,0,0,0,3,7,16,3,0,0,0,0,0,4,16,0,0,0,0,0,0,1,16,3,0,0,1,15,5,8,16,2,0,0,0,7,15,16,9,0,0],
[0,0,0,11,16,5,0,0,0,0,0,10,16,5,0,0,0,0,4,16,16,5,0,0,0,11,16,16,16,3,0,0,0,5,8,14,16,2,0,0,0,0,0,14,16,2,0,0,0,0,0,11,16,2,0,0,0,0,0,8,16,8,0,0],
[0,0,3,12,16,10,0,0,0,2,14,12,12,12,0,0,0,5,10,0,10,11,0,0,0,0,0,1,14,9,2,0,0,0,8,16,16,16,10,0,0,0,6,16,13,7,0,0,0,0,0,16,5,0,0,0,0,0,5,13,0,0,0,0],
[0,0,0,11,16,8,0,0,0,0,6,16,13,3,0,0,0,0,8,16,8,0,0,0,0,0,13,16,2,0,0,0,0,0,15,16,5,0,0,0,0,2,16,16,16,5,0,0,0,1,10,16,16,14,0,0,0,0,0,12,16,15,0,0],
[0,1,9,16,15,10,0,0,0,6,16,8,7,16,3,0,0,0,11,14,16,11,1,0,0,1,13,16,6,0,0,0,0,8,15,16,3,0,0,0,0,5,14,10,11,0,0,0,0,0,15,7,16,3,0,0,0,0,11,16,8,0,0,0],
[0,0,0,3,14,1,0,0,0,0,0,13,12,1,0,0,0,0,7,16,5,3,0,0,0,3,15,11,5,16,2,0,0,5,16,11,11,16,6,0,0,0,6,12,16,13,3,0,0,0,0,1,15,7,0,0,0,0,0,2,16,7,0,0],
[0,2,15,16,16,13,2,0,0,1,10,8,14,16,8,0,0,0,0,0,16,15,1,0,0,0,0,0,16,8,0,0,0,0,0,0,14,14,0,0,0,0,0,0,11,16,1,0,0,2,14,13,16,16,3,0,0,2,15,16,14,5,0,0],
[0,0,1,15,13,0,0,0,0,0,1,16,16,5,0,0,0,0,7,16,16,0,0,0,0,0,13,16,13,0,0,0,0,7,16,16,13,0,0,0,0,1,11,16,13,0,0,0,0,0,2,16,16,0,0,0,0,0,1,14,16,3,0,0]
];
export const additionalData = [
[0, 0, 0, 2, 13, 0, 0, 0, 0, 0, 0, 8, 15, 0, 0, 0, 0, 0, 5, 16, 5, 2, 0, 0, 0, 0, 15, 12, 1, 16, 4, 0, 0, 4, 16, 2, 9, 16, 8, 0, 0, 0, 10, 14, 16, 16, 4, 0, 0, 0, 0, 0, 13, 8, 0, 0, 0, 0, 0, 0, 13, 6, 0, 0],
[0, 0, 1, 12, 5, 0, 0, 0, 0, 0, 9, 16, 14, 3, 0, 0, 0, 2, 16, 14, 11, 13, 0, 0, 0, 2, 16, 10, 0, 14, 4, 0, 0, 4, 16, 0, 0, 12, 4, 0, 0, 4, 16, 3, 0, 11, 10, 0, 0, 0, 13, 12, 8, 14, 6, 0, 0, 0, 3, 10, 16, 12, 1, 0],
[0, 0, 12, 16, 16, 8, 0, 0, 0, 3, 16, 13, 8, 5, 0, 0, 0, 2, 16, 3, 0, 0, 0, 0, 0, 0, 16, 13, 9, 0, 0, 0, 0, 0, 10, 16, 16, 7, 0, 0, 0, 0, 0, 1, 10, 13, 0, 0, 0, 0, 2, 11, 16, 10, 0, 0, 0, 0, 11, 16, 12, 0, 0, 0],
];
export const transformResult2d = [-0.11142072379623405, 1.6251469561184166];
export const testLabels = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 9, 5, 5, 6, 5, 0, 9, 8, 9, 8, 4, 1, 7, 7, 3, 5, 1, 0, 0, 2, 2, 7, 8, 2, 0, 1, 2, 6, 3, 3, 7, 3, 3, 4, 6, 6, 6, 4, 9, 1, 5, 0, 9, 5, 2, 8, 2, 0, 0, 1, 7, 6, 3, 2, 1, 7, 4, 6, 3, 1, 3, 9, 1, 7, 6, 8, 4, 3, 1];
export const additionalLabels = [4, 0, 5];
export const testResults2D = [
[-2.904975618700953, 3.683494083841041],
[-0.879124321765863, -0.4426951405143409],
[-5.681244379231256, -0.7285120769550153],
[-10.97656385005008, -1.7526666493055492],
[-0.31624613607402396, 1.1790435717043253],
[-10.335486943961724, -1.7263038658200893],
[1.0183234049896575, 1.5616783163531822],
[-6.670890452694134, -2.599411074380109],
[-7.427928924098714, -1.05418551144876],
[-10.056474336257683, -1.7483236829216935],
[-2.84058073813134, 3.4605708652841742],
[-1.5561486242848588, -0.7689145308285977],
[-9.618253615211268, -0.9363390901794612],
[-10.96225008756357, -2.7757046759437696],
[-0.5471130812484319, 1.0412069799695824],
[-8.468671293896426, -1.9946633211861478],
[1.7476633852483103, 1.7135835405359496],
[-6.060552685379354, -2.5918267819546004],
[-7.612742599715047, -1.5731281884494046],
[-10.686213384810973, -1.2269058958867671],
[-2.8003412175539504, 3.516631590760736],
[-1.7105731474897927, -0.4229854943104262],
[-9.687787910507133, -0.8332650324863461],
[-11.562098613314996, -2.8768460480875233],
[-0.6169436126132575, 0.9271669091731843],
[-8.263457345038251, -1.7749721223830195],
[1.2702831264161745, 1.1345515631395546],
[-5.625939784888585, -2.81705722551124],
[-7.321567272072983, -1.1714267827612699],
[-10.498673585109545, -1.4172021055405306],
[-2.8361027291899963, 3.7566550423427216],
[-10.742499099483476, -1.3312462253382054],
[-8.742331565355999, -1.962339327316867],
[-8.683249673946568, -1.7431070207306547],
[1.519913836537469, 1.5812210418530623],
[-8.639230381438411, -1.83626003754962],
[-3.0714622950362083, 3.360214813815334],
[-10.321920349887177, -1.2166199317699589],
[-7.479960982731633, -2.0085158275034654],
[-10.64339464722167, -1.98466938098528],
[-7.444943872419686, -1.3202152645583067],
[-0.6659047931509448, 1.0689298563354555],
[-1.337476996462183, -0.7062062107669966],
[-5.722954727686442, -2.614991713970329],
[-6.535367593759711, -2.8240481849859242],
[-11.07458350701865, -2.1857932277021],
[-8.465490267069768, -1.5262082312357834],
[-1.4028562692810291, -0.3234834011238395],
[-2.303657152463291, 3.4811020923228124],
[-2.7185070579122725, 3.1727811960040686],
[-5.769483048641313, -0.9860570623329065],
[-5.615815263813969, -0.6062651823744999],
[-5.912314417301917, -2.8274353398822054],
[-6.979235936333255, -1.3486153549845195],
[-5.580947395294925, -0.8487153054662616],
[-2.519127036098348, 3.235839368692096],
[-1.5666266264773967, -0.4084044324487192],
[-5.482920294320904, -0.7132829553293972],
[1.291443869275501, 1.2088921598961009],
[-10.996594305162729, -2.7052817764388934],
[-11.230034148536227, -2.3267787723370223],
[-6.172936702531247, -2.8092873015313207],
[-11.31268843509639, -2.4664461470306835],
[-11.383742431873435, -2.526000902907926],
[-0.5135436868771529, 1.219682963441809],
[1.6600210033832736, 1.2986546898831781],
[1.3440665949247865, 1.6471365427370084],
[1.4289155033476695, 1.3398242847863313],
[-0.749955073590225, 0.5597391612835082],
[-7.196844128522498, -2.2154060964753044],
[-1.287126546227924, -0.1161850904218144],
[-8.736469581347375, -2.133470874953044],
[-2.6244524948342693, 3.2661482243617606],
[-10.488890956441548, -1.518682221199595],
[-9.080187424004665, -1.7921945653042823],
[-5.409549676705336, -0.7562583268806944],
[-7.131907767719736, -1.7819102538183373],
[-5.3945164159653105, -0.6311831012797511],
[-2.4235633967787837, 3.5752787074610253],
[-2.5646735303118913, 3.6545463352449956],
[-1.6293939125209715, -0.3261124147226215],
[-6.174169159339828, -2.816398862346779],
[1.5011647046090915, 1.4604002557978188],
[-11.415289227608609, -2.784266265081746],
[-9.372108978232719, -0.6382375099773951],
[-1.1395765495328711, -0.4341112548365201],
[-5.90712646029175, -2.693143905929763],
[-0.8163580669991641, 0.27205961797264744],
[1.6757381906829827, 1.6959697431903369],
[-11.377447482142799, -2.463933981648078],
[-1.4565032357599115, -0.5951550644235234],
[-11.521681218113521, -2.939480142411405],
[-10.698652055676758, -2.14080724624675],
[-0.8906495642468407, -0.3084980108495706],
[-6.20543225894981, -2.712538184223933],
[1.074802277722911, 1.3366879290550757],
[-7.369542577049855, -1.7665150872563606],
[-0.6479104154512673, 0.8639090216770717],
[-11.63001115748303, -2.7650660117667964],
[-0.6177124196423712, -0.1336295015576095],
];
export const testResults3D = [
[7.689216888038721, 5.889500760682107, -0.9372910704861791],
[1.6289201733408833, 0.09644154452992573, -0.6515193779268037],
[1.8064203152613236, 1.0408971830461913, -3.759296358413371],
[3.719252646835446, 6.2652682378361995, -5.453359288044545],
[2.208579439712507, 1.459095083827724, 0.12000156409675383],
[3.2249615957947833, 5.960024670787041, -4.8481645679297305],
[1.72709168751186, 2.663674819440392, 2.0862843204012536],
[1.4390793446753154, 3.110175910025147, -2.64329402984594],
[2.322369780334226, 3.854174748115889, -4.1940933254107895],
[3.172586988457068, 5.988043163212074, -4.489868026985644],
[7.774232233860294, 5.728604682804332, -0.7492809764488474],
[1.216760464557976, 0.12651789052380594, -1.1160899217216294],
[2.9761272550252342, 5.127354763494007, -3.789929920251627],
[3.623435292999969, 6.467545035827176, -5.742880703018387],
[2.191615075396111, 1.3462025439777128, -0.06012668392608021],
[1.9792286512470967, 5.048455808227712, -4.503864167574659],
[2.289319043749516, 2.479364102096565, 2.06509502307054],
[1.7522008547912962, 3.028100683362274, -1.9757439514197939],
[1.9133011076476316, 3.976012857253692, -3.654786899504835],
[3.126237934842212, 6.121493120485744, -4.9163292854727025],
[7.59812385730979, 5.945122300518597, -0.5466031795420292],
[1.0642820336951215, -0.10032610638546975, -1.272495749311577],
[2.9120539005610295, 4.9615417834931055, -3.6557913237121338],
[3.6667322868678744, 6.432934502429571, -6.475883464450793],
[1.985579003136723, 1.1529793819422138, -0.14330347191913095],
[2.536689758242814, 4.94651699436971, -4.188789564228635],
[1.7588493803085914, 2.820477258013995, 2.356610282996252],
[1.3544004702547257, 2.5228876142069545, -2.0848215214143417],
[2.18648006037277, 3.6254018053870727, -4.0692699701558235],
[3.3080002706216582, 6.170491494769027, -4.909354375701165],
[7.838430931939201, 5.962279999222033, -0.8501265755322832],
[3.146812853890534, 6.420570628535107, -5.128511955440203],
[2.1655492350855243, 5.133684793191488, -4.794337818504037],
[2.156182788918373, 4.779020022109626, -4.458168130007138],
[2.1868295164680163, 2.651935395462085, 1.9402408691766964],
[2.1122898435485626, 5.101805045252335, -4.376461605992093],
[7.759497394541325, 5.99608504530489, -0.5721002846060569],
[3.2698139531816732, 5.945075221007509, -4.716167049727797],
[1.9537425223452107, 3.7990956170037817, -3.1702963336135563],
[3.5638849988193715, 6.286648383473683, -5.057728780776639],
[2.2260271578133892, 3.9062531861533376, -3.7926834207621583],
[2.3487636315682385, 1.2733078093794485, -0.20521957587061831],
[1.4763516191715822, -0.07339630024515807, -1.2568913530002406],
[1.4457541418594435, 2.6678280144185633, -1.968673498837688],
[1.3665146037972555, 3.1104612289267797, -2.3362646187488014],
[3.8775155788281355, 6.65251928161629, -5.665014425209378],
[2.243781465166822, 4.810096665722539, -4.325776535824173],
[1.3113157069794292, -0.3907556024946346, -0.9674678142514966],
[7.4707557181542885, 6.068425618027565, -0.9016754062087259],
[7.719682010298653, 6.293792082295646, -0.6943491194702454],
[1.889160988739313, 1.2825076320476096, -3.8797729494317945],
[1.528848553082611, 1.2588606673105436, -3.8859071748383442],
[1.328663194953698, 2.6696166169691624, -2.2155627880306157],
[2.1544579217204247, 3.4833076529627025, -3.93081895871594],
[1.678647726543417, 1.350749170768083, -3.6472298500923848],
[7.779378974045683, 5.941065599050965, -0.3768179153485322],
[1.090599105664963, -0.21897555239951227, -1.1245858483752145],
[1.9004151266296854, 1.0016306087525904, -3.8240643093652547],
[1.79519610139777, 3.072747351366555, 1.9924133395724823],
[3.385643758056163, 6.481555639718136, -5.946525871558117],
[3.739617985672955, 6.7734869473964165, -5.791002799859846],
[1.68329653285918, 2.9352559918931376, -2.1240958308135625],
[3.8689936660063227, 6.450100300090818, -5.863677747356829],
[3.5227324662391934, 6.304799948350529, -6.015458718806657],
[2.347687118964318, 1.422139375121024, 0.22278213875612188],
[2.2180670708690338, 2.9587217481110355, 1.9577285130476965],
[1.8383459478962132, 2.9516924800936106, 1.951773536386326],
[1.9915163516683876, 3.125657869624825, 1.9360001985910298],
[2.0586128716897076, 0.9319526850785679, -0.363347710318456],
[1.972391691031123, 3.8113757348470148, -3.013137897370146],
[1.379201705857466, -0.31634219940793756, -0.8396233794610332],
[1.9982809296461372, 4.979452278680934, -4.6935290145722695],
[7.572434557728682, 6.103563807021123, -0.45238952042062147],
[3.361781071733503, 6.347807072766981, -4.965261048582085],
[2.4457518923571953, 5.208909777707682, -4.488138746033763],
[1.515371062452698, 1.2451955950131388, -4.004308683680948],
[2.327020894876154, 3.945346529979229, -3.214052790232576],
[1.6340689753522157, 1.1646400128291376, -3.9523159112572697],
[7.3434417124707885, 6.210680610725227, -0.7232208833510627],
[7.487203581595136, 6.091453370170096, -0.814759660914381],
[1.2523055479826777, -0.03355046908458365, -1.1445314775885431],
[1.4031260098000506, 2.9095043917838788, -2.2536281371792706],
[1.920464298567037, 2.8073745017850773, 2.2462294375046903],
[3.8813522730544237, 6.681172127785995, -6.326452335509549],
[2.9558363810192625, 4.788647132234979, -3.4553572807116355],
[1.670714138250657, 0.026486419185176892, -0.991392665968696],
[1.581545066906788, 2.7844989846664046, -1.984244575230313],
[1.875907008651662, 0.6952868053471871, -0.5229128767158864],
[2.084307557879972, 2.646840109884875, 2.056998572415541],
[3.5806516860631024, 6.743248753046012, -6.105297199686208],
[1.462558096710222, -0.10092139207798385, -1.1898581884339972],
[3.654706027150071, 6.390585202444062, -6.357892180833042],
[3.6027095941866247, 6.383704215055882, -5.318204043566554],
[1.7245257657018247, 0.192478655399741, -0.7436440052075087],
[1.683165920875281, 3.243957316304348, -2.3259907808966545],
[1.745611159759802, 2.472672662103672, 1.9155422431593778],
[2.177305599456365, 3.9231388710705675, -3.3039650230819726],
[2.068771729441073, 1.222227121468545, -0.02797486874066797],
[3.773289766268219, 6.534098686594626, -6.250642359343324],
[1.7729320319143027, 0.3201914207876183, -0.40659921859631903],
];
export const treeData = {
"hyperplanes": [
[0,0,0,-3,-1,11,2,0,0,0,7,3,-6,14,4,0,0,0,3,-14,-4,13,1,0,0,0,-6,-15,11,4,0,0,0,0,-6,-5,-7,-13,-5,0,0,8,1,-3,-9,-9,-14,0,0,5,11,2,2,0,-16,-2,0,0,0,-1,-3,-3,-8,0],
[0,-1,-6,12,16,16,5,0,0,-1,-2,-6,-8,2,6,0,0,-6,-16,-11,-1,8,0,0,0,-2,-8,0,10,16,11,0,0,8,5,2,1,10,3,0,0,0,2,11,-9,-7,0,0,0,0,2,0,-15,-4,0,0,0,0,-1,-4,-4,0,0,0],
[0,0,3,7,2,4,4,0,0,0,3,-4,-1,2,7,0,0,0,-6,-2,-1,1,9,0,0,5,11,7,-4,12,3,0,0,9,15,5,7,16,9,0,0,-7,-12,-4,16,6,0,0,0,-5,-14,-5,3,-2,0,0,0,0,4,10,-7,-13,-3,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,10,11,-1,-9,0,0,0,3,16,9,0,-9,0,0,0,7,11,-11,-8,4,0,0,0,-2,-4,-11,-16,6,1,0,0,8,12,-3,-16,1,8,0,0,5,13,-3,-16,-4,8,0,0,0,14,3,-16,0,8,0,0,0,7,10,-1,6,4,0],
[0,0,10,-6,-7,2,0,0,0,3,6,0,-5,-8,-1,0,0,-1,-2,-9,-10,-16,-4,0,0,0,-2,5,0,-14,-6,0,0,-3,-1,10,9,-12,-7,0,0,-1,-15,-11,12,-11,-6,0,0,0,-7,-8,0,-11,0,0,0,0,9,3,-4,-4,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,-2,-13,-15,-5,-7,-11,0,0,-5,-16,-3,11,9,-1,0,0,-6,-12,7,13,9,0,0,0,1,0,-5,0,2,0,0,0,-3,-8,-1,5,-9,0,0,0,0,0,2,4,-7,0,0,0,0,-4,-8,0,4,0,0,0,-2,-16,-13,6,6,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,2,-1,-3,0,0,0,0,-7,0,3,3,0,0,0,-2,-9,0,13,0,0,0,0,-3,-3,4,12,0,0,0,0,2,0,2,8,0,0,0,0,-2,-5,0,-3,-16,-6,0,0,-1,-12,0,0,-16,-12,0,0,0,-2,2,1,-11,-7,0],
[0,0,0,9,1,-6,0,0,0,0,4,3,-4,-9,0,0,0,0,5,-2,-14,4,3,0,0,-3,0,1,-12,14,10,0,0,8,11,5,-3,10,2,0,0,0,9,12,0,8,0,0,0,0,0,6,0,0,0,0,0,0,0,9,4,-9,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,-1,0,-1,0,0,0,0,-5,-2,2,9,14,0,0,0,-4,-3,8,1,10,1,0,0,-2,-3,0,0,1,0,0,0,0,-1,0,-2,3,6,0,0,0,0,0,4,3,3,0,0,0,0,-4,7,7,-10,0,0,0,-4,3,1,-6,-13,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
],
"offsets": [529.5,-244,-709,0,0,-164.5,896.5,0,0,640.5,0,0,381.5,-556,0,0,-263,0,0],
"children": [[1,12],[2,5],[3,4],[-0,-1],[-1,-1],[6,9],[7,8],[-2,-1],[-3,-1],[10,11],[-4,-1],[-5,-1],[13,16],[14,15],[-6,-1],[-7,-1],[17,18],[-8,-1],[-9,-1]],
"indices": [
[7,17,23,27,43,44,52,61,81,83,86,89,94,98,-1],
[2,13,38,50,51,53,54,57,60,75,77,-1,-1,-1,-1],
[22,25,76,84,96,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],
[0,8,9,10,20,30,36,39,48,49,55,72,78,79,92],
[12,18,28,40,47,56,59,62,63,69,80,-1,-1,-1,-1],
[15,32,33,35,46,71,91,-1,-1,-1,-1,-1,-1,-1,-1],
[41,68,87,97,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],
[1,3,11,19,21,31,42,45,70,85,90,93,99,-1,-1],
[4,5,14,24,64,73,74,95,-1,-1,-1,-1,-1,-1,-1],
[6,16,26,29,34,37,58,65,66,67,82,88,-1,-1,-1],
]
}; | the_stack |
jest.mock('simple-peer')
jest.mock('../insertable-streams')
jest.mock('../socket')
jest.mock('../window')
jest.useFakeTimers()
import SimplePeer from 'simple-peer'
import { dial, hangUp } from '../actions/CallActions'
import * as MediaActions from '../actions/MediaActions'
import { StreamTypeCamera, StreamTypeDesktop } from '../actions/StreamActions'
import { DIAL_STATE_DIALLING, DIAL_STATE_HUNG_UP, DIAL_STATE_IN_CALL, HANG_UP, MEDIA_ENUMERATE, MEDIA_STREAM, PEER_ADD, SOCKET_EVENT_HANG_UP } from '../constants'
import socket from '../socket'
import { createStore, Store } from '../store'
import { MediaStream, MediaStreamTrack } from '../window'
import { MediaConstraint } from './media'
describe('media', () => {
const nickname = 'john'
let store: Store
beforeEach(() => {
store = createStore();
(navigator as any).mediaDevices = {}
})
afterEach(() => {
delete (navigator as any).mediaDevices
})
function toJSON(this: MediaDeviceInfo) {
return JSON.stringify(this)
}
describe(MEDIA_ENUMERATE, () => {
beforeEach(() => {
navigator.mediaDevices.enumerateDevices = async () => {
const result: MediaDeviceInfo[] = [{
deviceId: 'abcdef1',
groupId: 'group1',
kind: 'videoinput',
label: 'Video Input',
toJSON,
}, {
deviceId: 'abcdef2',
groupId: 'group1',
kind: 'audioinput',
label: 'Audio Input',
toJSON,
}, {
// duplicate device should be filtered out.
// sometimes cameras have two devices with different label (e.g. IR)
deviceId: 'abcdef2',
groupId: 'group1',
kind: 'audioinput',
label: 'Audio Input',
toJSON,
}, {
deviceId: 'abcdef3',
groupId: 'group2',
kind: 'audiooutput',
label: 'Audio Output',
toJSON,
}]
return result
}
})
it('retrieves a list of audioinput/videoinput devices', async () => {
await store.dispatch(MediaActions.enumerateDevices())
expect(store.getState().media.devices).toEqual({
audio: [{
id: 'abcdef2',
name: 'Audio Input',
type: 'audioinput',
}],
video: [{
id: 'abcdef1',
name: 'Video Input',
type: 'videoinput',
}],
})
})
it('handles errors', async () => {
delete (
navigator.mediaDevices as {enumerateDevices?: unknown}
).enumerateDevices
try {
await store.dispatch(MediaActions.enumerateDevices())
} catch (err) {
// do nothing
}
expect(store.getState().media.devices).toEqual({ audio: [], video: [] })
expect(store.getState().media.error).toBeTruthy()
})
})
describe('media constraints: video', () => {
type Action = MediaActions.MediaDeviceToggleAction |
MediaActions.MediaSizeConstraintAction |
MediaActions.MediaDeviceIdAction
const tests: {
name: string
action: Action
wantState: MediaConstraint
}[] = [
{
name: 'disable video',
action: MediaActions.toggleDevice({ kind: 'video', enabled: false }),
wantState: {
enabled: false,
constraints: { facingMode: 'user' },
},
},
{
name: 'set deviceId',
action: MediaActions.setDeviceId({ kind: 'video', deviceId: 'abcd' }),
wantState: {
enabled: true,
constraints: { deviceId: 'abcd' },
},
},
{
name: 'set size constraint',
action: MediaActions.setSizeConstraint({ width: 640, height: 480 }),
wantState: {
enabled: true,
constraints: { deviceId: 'abcd', width: 640, height: 480 },
},
},
{
name: 'disable video',
action: MediaActions.toggleDevice({ kind: 'video', enabled: false }),
wantState: {
enabled: false,
constraints: { deviceId: 'abcd', width: 640, height: 480 },
},
},
{
name: 'set default deviceId',
action: MediaActions.setDeviceId({ kind: 'video', deviceId: '' }),
wantState: {
enabled: true,
constraints: { facingMode: 'user', width: 640, height: 480 },
},
},
{
name: 'set deviceId again',
action: MediaActions.setDeviceId({ kind: 'video', deviceId: 'efgh' }),
wantState: {
enabled: true,
constraints: { deviceId: 'efgh', width: 640, height: 480 },
},
},
{
name: 'unset size constraint',
action: MediaActions.setSizeConstraint(null),
wantState: {
enabled: true,
constraints: { deviceId: 'efgh' },
},
},
]
it('test', () => {
tests.forEach(test => {
store.dispatch(test.action)
expect(store.getState().media.video).toEqual(test.wantState)
})
})
})
describe('media constraints: audio', () => {
type Action = MediaActions.MediaDeviceToggleAction |
MediaActions.MediaDeviceIdAction
const tests: {
name: string
action: Action
wantState: MediaConstraint
}[] = [
{
name: 'disable audio',
action: MediaActions.toggleDevice({ kind: 'audio', enabled: false }),
wantState: {
enabled: false,
constraints: {},
},
},
{
name: 'set deviceId',
action: MediaActions.setDeviceId({ kind: 'audio', deviceId: 'abcd' }),
wantState: {
enabled: true,
constraints: { deviceId: 'abcd' },
},
},
{
name: 'disable audio',
action: MediaActions.toggleDevice({ kind: 'audio', enabled: false }),
wantState: {
enabled: false,
constraints: { deviceId: 'abcd' },
},
},
{
name: 'set default deviceId',
action: MediaActions.setDeviceId({ kind: 'audio', deviceId: '' }),
wantState: {
enabled: true,
constraints: {},
},
},
{
name: 'set deviceId again',
action: MediaActions.setDeviceId({ kind: 'audio', deviceId: 'efgh' }),
wantState: {
enabled: true,
constraints: { deviceId: 'efgh' },
},
},
]
it('test', () => {
tests.forEach(test => {
store.dispatch(test.action)
expect(store.getState().media.audio).toEqual(test.wantState)
})
})
})
describe(MEDIA_STREAM, () => {
const track = new MediaStreamTrack()
const stream = new MediaStream()
stream.addTrack(track)
describe('using navigator.mediaDevices.getUserMedia', () => {
beforeEach(() => {
navigator.mediaDevices.getUserMedia = async () => stream
})
async function dispatch() {
const result = await store.dispatch(MediaActions.getMediaStream({
audio: true,
video: true,
}))
expect(result.stream).toBe(stream)
expect(result.type).toBe(StreamTypeCamera)
}
describe('reducers/streams', () => {
it('adds the local stream to the map of videos', async () => {
expect(store.getState().streams.localStreams).toEqual({})
await dispatch()
const { localStreams } = store.getState().streams
expect(Object.keys(localStreams).length).toBe(1)
const s = localStreams[StreamTypeCamera]!
expect(s).toBeTruthy()
expect(s.stream).toBe(stream)
expect(s.streamId).toBe(stream.id)
expect(s.type).toBe(StreamTypeCamera)
})
})
describe('reducers/peers', () => {
const peer1 = new SimplePeer()
const peer2 = new SimplePeer()
const peers = [peer1, peer2]
beforeEach(() => {
store.dispatch({
type: HANG_UP,
})
store.dispatch({
type: PEER_ADD,
payload: {
peerId: '1',
peer: peer1,
},
})
store.dispatch({
type: PEER_ADD,
payload: {
peerId: '2',
peer: peer2,
},
})
})
afterEach(() => {
store.dispatch({
type: HANG_UP,
})
})
it('adds local camera stream to all peers', async () => {
await dispatch()
peers.forEach(peer => {
expect((peer.addTrack as jest.Mock).mock.calls)
.toEqual([[ track, stream ]])
expect((peer.removeTrack as any).mock.calls).toEqual([])
})
await dispatch()
peers.forEach(peer => {
expect((peer.addTrack as jest.Mock).mock.calls)
.toEqual([[ track, stream ], [ track, stream ]])
expect((peer.removeTrack as jest.Mock).mock.calls)
.toEqual([[ track, stream ]])
})
})
})
});
['getUserMedia', 'mozGetUserMedia', 'webkitGetUserMedia'].forEach(item => {
describe('compatibility: navigator.' + item, () => {
beforeEach(() => {
const getUserMedia: typeof navigator.getUserMedia =
(constraint, onSuccess, onError) => onSuccess(stream);
(navigator as any)[item] = getUserMedia
})
afterEach(() => {
delete (navigator as any)[item]
})
it('returns a promise with media stream' + item, async () => {
const promise = MediaActions.getMediaStream({
audio: true,
video: true,
})
expect(promise.type).toBe('MEDIA_STREAM')
expect(promise.status).toBe('pending')
const result = await promise
expect(result.stream).toBe(stream)
})
})
})
})
describe('getDesktopStream (getDisplayMedia)', () => {
const stream: MediaStream = new MediaStream()
beforeEach(() => {
(navigator.mediaDevices as any).getDisplayMedia = async () => stream
})
async function dispatch() {
const result = await store.dispatch(MediaActions.getDesktopStream())
expect(result.stream).toBe(stream)
expect(result.type).toBe(StreamTypeDesktop)
}
it('adds the local stream to the map of videos', async () => {
expect(store.getState().streams.localStreams).toEqual({})
await dispatch()
const {localStreams } = store.getState().streams
expect(Object.keys(localStreams).length).toBe(1)
const s = localStreams[StreamTypeDesktop]!
expect(s.type).toBe(StreamTypeDesktop)
expect(s.stream).toBe(stream)
expect(s.streamId).toBe(stream.id)
})
})
describe('dialState', () => {
async function successfulDial() {
const promise = store.dispatch(dial({ nickname }))
expect(store.getState().media.dialState).toBe(DIAL_STATE_DIALLING)
socket.emit('users', {
initiator: 'test',
peerIds: [],
nicknames: {},
})
jest.runAllTimers()
await promise
expect(store.getState().media.dialState).toBe(DIAL_STATE_IN_CALL)
}
it('has dialState HUNG_UP by default', () => {
expect(store.getState().media.dialState).toBe(DIAL_STATE_HUNG_UP)
})
it('changes state from DIALLING to HUNG_UP', async () => {
const promise = store.dispatch(dial({ nickname }))
expect(store.getState().media.dialState).toBe(DIAL_STATE_DIALLING)
jest.runAllTimers()
let err!: Error
try {
await promise
} catch (e) {
err = e
}
expect(err).toBeTruthy()
expect(err.message).toMatch(/Dial timed out/)
expect(store.getState().media.dialState).toBe(DIAL_STATE_HUNG_UP)
})
it('changes state from DIALLING to IN_CALL', async () => {
await successfulDial()
})
it('changes state to HUNG_UP when hangUp action is dispatched', async() => {
await successfulDial()
const promise = new Promise<void>(
resolve => socket.once(SOCKET_EVENT_HANG_UP, () => resolve()),
)
store.dispatch(hangUp())
expect(store.getState().media.dialState).toBe(DIAL_STATE_HUNG_UP)
await promise
})
})
}) | the_stack |
import * as wasmlib from "wasmlib"
import * as coreaccounts from "wasmlib/coreaccounts"
import * as coregovernance from "wasmlib/coregovernance"
import * as sc from "./index";
const CONTRACT_NAME_DEPLOYED = "exampleDeployTR";
const MSG_CORE_ONLY_PANIC = "========== core only =========";
const MSG_FULL_PANIC = "========== panic FULL ENTRY POINT =========";
const MSG_VIEW_PANIC = "========== panic VIEW =========";
export function funcCallOnChain(ctx: wasmlib.ScFuncContext, f: sc.CallOnChainContext): void {
let paramInt = f.params.intValue().value();
let hnameContract = ctx.contract();
if (f.params.hnameContract().exists()) {
hnameContract = f.params.hnameContract().value();
}
let hnameEP = sc.HFuncCallOnChain;
if (f.params.hnameEP().exists()) {
hnameEP = f.params.hnameEP().value();
}
let counter = f.state.counter();
ctx.log("call depth = " + f.params.intValue().toString() +
", hnameContract = " + hnameContract.toString() +
", hnameEP = " + hnameEP.toString() +
", counter = " + counter.toString())
counter.setValue(counter.value() + 1);
let parms = wasmlib.ScMutableMap.create();
parms.getInt64(wasmlib.Key32.fromString(sc.ParamIntValue)).setValue(paramInt);
let ret = ctx.call(hnameContract, hnameEP, parms, null);
let retVal = ret.getInt64(wasmlib.Key32.fromString(sc.ResultIntValue));
f.results.intValue().setValue(retVal.value());
}
export function funcCheckContextFromFullEP(ctx: wasmlib.ScFuncContext, f: sc.CheckContextFromFullEPContext): void {
ctx.require(f.params.agentID().value().equals(ctx.accountID()), "fail: agentID");
ctx.require(f.params.caller().value().equals(ctx.caller()), "fail: caller");
ctx.require(f.params.chainID().value().equals(ctx.chainID()), "fail: chainID");
ctx.require(f.params.chainOwnerID().value().equals(ctx.chainOwnerID()), "fail: chainOwnerID");
ctx.require(f.params.contractCreator().value().equals(ctx.contractCreator()), "fail: contractCreator");
}
export function funcDoNothing(ctx: wasmlib.ScFuncContext, f: sc.DoNothingContext): void {
ctx.log("doing nothing...");
}
export function funcGetMintedSupply(ctx: wasmlib.ScFuncContext, f: sc.GetMintedSupplyContext): void {
let minted = ctx.minted();
let mintedColors = minted.colors();
ctx.require(mintedColors.length() == 1, "test only supports one minted color");
let color = mintedColors.getColor(0).value();
let amount = minted.balance(color);
f.results.mintedSupply().setValue(amount);
f.results.mintedColor().setValue(color);
}
export function funcIncCounter(ctx: wasmlib.ScFuncContext, f: sc.IncCounterContext): void {
let counter = f.state.counter();
counter.setValue(counter.value() + 1);
}
export function funcInit(ctx: wasmlib.ScFuncContext, f: sc.InitContext): void {
if (f.params.fail().exists()) {
ctx.panic("failing on purpose");
}
}
export function funcPassTypesFull(ctx: wasmlib.ScFuncContext, f: sc.PassTypesFullContext): void {
let hash = ctx.utility().hashBlake2b(wasmlib.Convert.fromString(sc.ParamHash));
ctx.require(f.params.hash().value().equals(hash), "Hash wrong");
ctx.require(f.params.int64().value() == 42, "int64 wrong");
ctx.require(f.params.int64Zero().value() == 0, "int64-0 wrong");
ctx.require(f.params.string().value() == sc.ParamString, "string wrong");
ctx.require(f.params.stringZero().value() == "", "string-0 wrong");
ctx.require(f.params.hname().value().equals(wasmlib.ScHname.fromName(sc.ParamHname)), "Hname wrong");
ctx.require(f.params.hnameZero().value().equals(new wasmlib.ScHname(0)), "Hname-0 wrong");
}
export function funcRunRecursion(ctx: wasmlib.ScFuncContext, f: sc.RunRecursionContext): void {
let depth = f.params.intValue().value();
if (depth <= 0) {
return;
}
let callOnChain = sc.ScFuncs.callOnChain(ctx);
callOnChain.params.intValue().setValue(depth - 1);
callOnChain.params.hnameEP().setValue(sc.HFuncRunRecursion);
callOnChain.func.call();
let retVal = callOnChain.results.intValue().value();
f.results.intValue().setValue(retVal);
}
export function funcSendToAddress(ctx: wasmlib.ScFuncContext, f: sc.SendToAddressContext): void {
let balances = wasmlib.ScTransfers.fromBalances(ctx.balances());
ctx.transferToAddress(f.params.address().value(), balances);
}
export function funcSetInt(ctx: wasmlib.ScFuncContext, f: sc.SetIntContext): void {
f.state.ints().getInt64(f.params.name().value()).setValue(f.params.intValue().value());
}
export function funcSpawn(ctx: wasmlib.ScFuncContext, f: sc.SpawnContext): void {
let spawnName = sc.ScName + "_spawned";
let spawnDescr = "spawned contract description";
ctx.deploy(f.params.progHash().value(), spawnName, spawnDescr, null);
let spawnHname = wasmlib.ScHname.fromName(spawnName);
for (let i = 0; i < 5; i++) {
ctx.call(spawnHname, sc.HFuncIncCounter, null, null);
}
}
export function funcTestBlockContext1(ctx: wasmlib.ScFuncContext, f: sc.TestBlockContext1Context): void {
ctx.panic(MSG_CORE_ONLY_PANIC);
}
export function funcTestBlockContext2(ctx: wasmlib.ScFuncContext, f: sc.TestBlockContext2Context): void {
ctx.panic(MSG_CORE_ONLY_PANIC);
}
export function funcTestCallPanicFullEP(ctx: wasmlib.ScFuncContext, f: sc.TestCallPanicFullEPContext): void {
sc.ScFuncs.testPanicFullEP(ctx).func.call();
}
export function funcTestCallPanicViewEPFromFull(ctx: wasmlib.ScFuncContext, f: sc.TestCallPanicViewEPFromFullContext): void {
sc.ScFuncs.testPanicViewEP(ctx).func.call();
}
export function funcTestChainOwnerIDFull(ctx: wasmlib.ScFuncContext, f: sc.TestChainOwnerIDFullContext): void {
f.results.chainOwnerID().setValue(ctx.chainOwnerID());
}
export function funcTestEventLogDeploy(ctx: wasmlib.ScFuncContext, f: sc.TestEventLogDeployContext): void {
// deploy the same contract with another name
let programHash = ctx.utility().hashBlake2b(wasmlib.Convert.fromString("testcore"));
ctx.deploy(programHash, CONTRACT_NAME_DEPLOYED, "test contract deploy log", null);
}
export function funcTestEventLogEventData(ctx: wasmlib.ScFuncContext, f: sc.TestEventLogEventDataContext): void {
ctx.event("[Event] - Testing Event...");
}
export function funcTestEventLogGenericData(ctx: wasmlib.ScFuncContext, f: sc.TestEventLogGenericDataContext): void {
let event = "[GenericData] Counter Number: ".toString() + f.params.counter().toString();
ctx.event(event);
}
export function funcTestPanicFullEP(ctx: wasmlib.ScFuncContext, f: sc.TestPanicFullEPContext): void {
ctx.panic(MSG_FULL_PANIC);
}
export function funcWithdrawToChain(ctx: wasmlib.ScFuncContext, f: sc.WithdrawToChainContext): void {
let xx = coreaccounts.ScFuncs.withdraw(ctx);
xx.func.transferIotas(1).postToChain(f.params.chainID().value());
}
export function viewCheckContextFromViewEP(ctx: wasmlib.ScViewContext, f: sc.CheckContextFromViewEPContext): void {
ctx.require(f.params.agentID().value().equals(ctx.accountID()), "fail: agentID");
ctx.require(f.params.chainID().value().equals(ctx.chainID()), "fail: chainID");
ctx.require(f.params.chainOwnerID().value().equals(ctx.chainOwnerID()), "fail: chainOwnerID");
ctx.require(f.params.contractCreator().value().equals(ctx.contractCreator()), "fail: contractCreator");
}
export function viewFibonacci(ctx: wasmlib.ScViewContext, f: sc.FibonacciContext): void {
let n = f.params.intValue().value();
if (n == 0 || n == 1) {
f.results.intValue().setValue(n);
return;
}
let fib = sc.ScFuncs.fibonacci(ctx);
fib.params.intValue().setValue(n - 1);
fib.func.call();
let n1 = fib.results.intValue().value();
fib.params.intValue().setValue(n - 2);
fib.func.call();
let n2 = fib.results.intValue().value();
f.results.intValue().setValue(n1 + n2);
}
export function viewGetCounter(ctx: wasmlib.ScViewContext, f: sc.GetCounterContext): void {
f.results.counter().setValue(f.state.counter().value());
}
export function viewGetInt(ctx: wasmlib.ScViewContext, f: sc.GetIntContext): void {
let name = f.params.name().value();
let value = f.state.ints().getInt64(name);
ctx.require(value.exists(), "param 'value' not found");
f.results.values().getInt64(name).setValue(value.value());
}
export function viewGetStringValue(ctx: wasmlib.ScViewContext, f: sc.GetStringValueContext): void {
ctx.panic(MSG_CORE_ONLY_PANIC);
}
export function viewJustView(ctx: wasmlib.ScViewContext, f: sc.JustViewContext): void {
ctx.log("doing nothing...");
}
export function viewPassTypesView(ctx: wasmlib.ScViewContext, f: sc.PassTypesViewContext): void {
let hash = ctx.utility().hashBlake2b(wasmlib.Convert.fromString(sc.ParamHash));
ctx.require(f.params.hash().value().equals(hash), "Hash wrong");
ctx.require(f.params.int64().value() == 42, "int64 wrong");
ctx.require(f.params.int64Zero().value() == 0, "int64-0 wrong");
ctx.require(f.params.string().value() == sc.ParamString, "string wrong");
ctx.require(f.params.stringZero().value() == "", "string-0 wrong");
ctx.require(f.params.hname().value().equals(wasmlib.ScHname.fromName(sc.ParamHname)), "Hname wrong");
ctx.require(f.params.hnameZero().value().equals(new wasmlib.ScHname(0)), "Hname-0 wrong");
}
export function viewTestCallPanicViewEPFromView(ctx: wasmlib.ScViewContext, f: sc.TestCallPanicViewEPFromViewContext): void {
sc.ScFuncs.testPanicViewEP(ctx).func.call();
}
export function viewTestChainOwnerIDView(ctx: wasmlib.ScViewContext, f: sc.TestChainOwnerIDViewContext): void {
f.results.chainOwnerID().setValue(ctx.chainOwnerID());
}
export function viewTestPanicViewEP(ctx: wasmlib.ScViewContext, f: sc.TestPanicViewEPContext): void {
ctx.panic(MSG_VIEW_PANIC);
}
export function viewTestSandboxCall(ctx: wasmlib.ScViewContext, f: sc.TestSandboxCallContext): void {
let getChainInfo = coregovernance.ScFuncs.getChainInfo(ctx);
getChainInfo.func.call();
f.results.sandboxCall().setValue(getChainInfo.results.description().value());
} | the_stack |
import {add, div, keep, mul, nextFrame, Scalar, Tensor, tidy, util} from '@tensorflow/tfjs-core';
import {Container} from './engine/container';
import {ValueError} from './errors';
import {Logs, resolveScalarsInLogs, UnresolvedLogs} from './logs';
import * as generic_utils from './utils/generic_utils';
/** Verbosity logging level when fitting a model. */
export enum ModelLoggingVerbosity {
SILENT = 0,
VERBOSE = 1
}
/** How often to yield to the main thread when training (in ms). */
export const DEFAULT_YIELD_EVERY_MS = 125;
export type Params = {
[key: string]: number|string|boolean|number[]|string[]|boolean[];
};
export type YieldEveryOptions = 'auto'|'batch'|'epoch'|'never'|number;
/**
* Abstract base class used to build new callbacks.
*
* The `logs` dictionary that callback methods take as argument will contain
* keys for quantities relevant to the current batch or epoch.
*
* Currently, the `.fit()` method of the `Sequential` model class
* will include the following quantities in the `logs` that
* it passes to its callbacks:
*
* onEpochEnd: Logs include `acc` and `loss`, and optionally include `valLoss`
* (if validation is enabled in `fit`), and `valAcc` (if validation and
* accuracy monitoring are enabled).
* onBatchBegin: Logs include `size`, the number of samples in the current
* batch.
* onBatchEnd: Logs include `loss`, and optionally `acc` (if accuracy monitoring
* is enabled).
*/
export abstract class BaseCallback {
// TODO(michaelterry): This type is a best guess.
validationData: Tensor|Tensor[] = null;
/**
* Training parameters (eg. verbosity, batch size, number of epochs...).
*/
params: Params;
setParams(params: Params): void {
this.params = params;
}
async onEpochBegin(epoch: number, logs?: UnresolvedLogs) {}
async onEpochEnd(epoch: number, logs?: UnresolvedLogs) {}
async onBatchBegin(batch: number, logs?: UnresolvedLogs) {}
async onBatchEnd(batch: number, logs?: UnresolvedLogs) {}
async onTrainBegin(logs?: UnresolvedLogs) {}
async onTrainEnd(logs?: UnresolvedLogs) {}
// LayersModel needs to call Callback.setModel(), but cannot actually depend
// on Callback because that creates a cyclic dependency. Providing this no-op
// method on BaseCallback breaks the cycle: this way LayersModel can depend on
// BaseCallback but not on Callback. The argument is typed as `Container`
// (the superclass of LayersModel) to avoid recapitulating the cycle. Callback
// overrides this method and enforces that the argument is really a
// LayersModel.
setModel(model: Container): void {
// Do nothing. Use Callback instead of BaseCallback to track the model.
}
}
/**
* Container abstracting a list of callbacks.
*/
export class CallbackList {
callbacks: BaseCallback[];
queueLength: number;
// TODO(cais): When the need arises, uncomment the following lines and
// implement the queue for time values.
// private deltaTBatch: number;
// private deltaTsBatchBegin: Array<number>;
// private deltaTsBatchEnd: Array<number>;
/**
* Constructor of CallbackList.
* @param callbacks Array of `Callback` instances.
* @param queueLength Queue length for keeping running statistics over
* callback execution time.
*/
constructor(callbacks?: BaseCallback[], queueLength = 10) {
// TODO(cais): Make use of queueLength when implementing the queue for time
// values.
if (callbacks == null) {
callbacks = [];
}
this.callbacks = callbacks;
this.queueLength = queueLength;
}
append(callback: BaseCallback): void {
this.callbacks.push(callback);
}
setParams(params: Params): void {
for (const callback of this.callbacks) {
callback.setParams(params);
}
}
setModel(model: Container): void {
for (const callback of this.callbacks) {
callback.setModel(model);
}
}
/**
* Called at the start of an epoch.
* @param epoch Index of epoch.
* @param logs Dictionary of logs.
*/
async onEpochBegin(epoch: number, logs?: UnresolvedLogs) {
if (logs == null) {
logs = {};
}
for (const callback of this.callbacks) {
await callback.onEpochBegin(epoch, logs);
}
}
/**
* Called at the end of an epoch.
* @param epoch Index of epoch.
* @param logs Dictionary of logs.
*/
async onEpochEnd(epoch: number, logs?: UnresolvedLogs) {
if (logs == null) {
logs = {};
}
for (const callback of this.callbacks) {
await callback.onEpochEnd(epoch, logs);
}
}
/**
* Called right before processing a batch.
* @param batch Index of batch within the current epoch.
* @param logs Dictionary of logs.
*/
async onBatchBegin(batch: number, logs?: UnresolvedLogs) {
if (logs == null) {
logs = {};
}
for (const callback of this.callbacks) {
await callback.onBatchBegin(batch, logs);
}
}
/**
* Called at the end of a batch.
* @param batch Index of batch within the current epoch.
* @param logs Dictionary of logs.
*/
async onBatchEnd(batch: number, logs?: UnresolvedLogs) {
if (logs == null) {
logs = {};
}
for (const callback of this.callbacks) {
await callback.onBatchEnd(batch, logs);
}
}
/**
* Called at the beginning of training.
* @param logs Dictionary of logs.
*/
async onTrainBegin(logs?: UnresolvedLogs) {
if (logs == null) {
logs = {};
}
for (const callback of this.callbacks) {
await callback.onTrainBegin(logs);
}
}
/**
* Called at the end of training.
* @param logs Dictionary of logs.
*/
async onTrainEnd(logs?: UnresolvedLogs) {
if (logs == null) {
logs = {};
}
for (const callback of this.callbacks) {
await callback.onTrainEnd(logs);
}
}
}
/**
* Callback that accumulates epoch averages of metrics.
*
* This callback is automatically applied to every LayersModel.
*/
export class BaseLogger extends BaseCallback {
private seen: number;
private totals: UnresolvedLogs;
constructor() {
super();
}
async onEpochBegin(epoch: number) {
this.seen = 0;
this.totals = {};
}
async onBatchEnd(batch: number, logs?: UnresolvedLogs) {
if (logs == null) {
logs = {};
}
const batchSize = logs['size'] == null ? 0 : logs['size'] as number;
this.seen += batchSize;
for (const key in logs) {
const value = logs[key];
if (typeof value === 'number') {
if (!this.totals.hasOwnProperty(key)) {
this.totals[key] = 0;
}
this.totals[key] = this.totals[key] as number + value * batchSize;
} else {
let oldTotalsToDispose: Scalar;
if (key in this.totals) {
oldTotalsToDispose = this.totals[key] as Scalar;
} else {
this.totals[key] = 0;
}
const total: Scalar =
tidy(() => add((this.totals[key]), mul(value, batchSize)));
this.totals[key] = total;
if (oldTotalsToDispose != null) {
oldTotalsToDispose.dispose();
}
}
}
}
async onEpochEnd(epoch: number, logs?: UnresolvedLogs) {
if (logs != null) {
for (const key of this.params['metrics'] as string[]) {
if (this.totals[key] == null) {
continue;
}
if (typeof this.totals[key] === 'number') {
logs[key] = this.totals[key] as number / this.seen;
} else {
tidy(() => {
const log: Scalar = mul(div(1, this.seen), this.totals[key]);
logs[key] = log;
(this.totals[key] as Tensor).dispose();
keep(logs[key] as Scalar);
});
}
}
}
}
}
/**
* Callback that records events into a `History` object. This callback is
* automatically applied to every TF.js Layers model. The `History` object
* gets returned by the `fit` method of models.
*/
export class History extends BaseCallback {
epoch: number[];
history: {[key: string]: Array<number|Tensor>};
async onTrainBegin(logs?: UnresolvedLogs) {
this.epoch = [];
this.history = {};
}
async onEpochEnd(epoch: number, logs?: UnresolvedLogs) {
if (logs == null) {
logs = {};
}
this.epoch.push(epoch);
for (const key in logs) {
if (this.history[key] == null) {
this.history[key] = [];
}
this.history[key].push(logs[key]);
}
}
/**
* Await the values of all losses and metrics.
*/
async syncData() {
const promises: Array<Promise<Float32Array|Int32Array|Uint8Array>> = [];
const keys: string[] = [];
const indices: number[] = [];
for (const key in this.history) {
const valueArray = this.history[key];
for (let i = 0; i < valueArray.length; ++i) {
if (typeof valueArray[i] !== 'number') {
const valueScalar = valueArray[i] as Tensor;
promises.push(valueScalar.data());
keys.push(key);
indices.push(i);
}
}
}
const values = await Promise.all(promises);
for (let n = 0; n < values.length; ++n) {
const tensorToDispose = this.history[keys[n]][indices[n]] as Tensor;
tensorToDispose.dispose();
this.history[keys[n]][indices[n]] = values[n][0];
}
}
}
export interface CustomCallbackArgs {
onTrainBegin?: (logs?: Logs) => void | Promise<void>;
onTrainEnd?: (logs?: Logs) => void | Promise<void>;
onEpochBegin?: (epoch: number, logs?: Logs) => void | Promise<void>;
onEpochEnd?: (epoch: number, logs?: Logs) => void | Promise<void>;
onBatchBegin?: (batch: number, logs?: Logs) => void | Promise<void>;
onBatchEnd?: (batch: number, logs?: Logs) => void | Promise<void>;
onYield?: (epoch: number, batch: number, logs: Logs) => void | Promise<void>;
// Used for test DI mocking.
nowFunc?: Function;
nextFrameFunc?: Function;
}
/**
* Custom callback for training.
*/
export class CustomCallback extends BaseCallback {
protected readonly trainBegin: (logs?: Logs) => void | Promise<void>;
protected readonly trainEnd: (logs?: Logs) => void | Promise<void>;
protected readonly epochBegin:
(epoch: number, logs?: Logs) => void | Promise<void>;
protected readonly epochEnd:
(epoch: number, logs?: Logs) => void | Promise<void>;
protected readonly batchBegin:
(batch: number, logs?: Logs) => void | Promise<void>;
protected readonly batchEnd:
(batch: number, logs?: Logs) => void | Promise<void>;
protected readonly yield:
(epoch: number, batch: number, logs: Logs) => void | Promise<void>;
private yieldEvery: YieldEveryOptions;
private currentEpoch = 0;
public nowFunc: Function;
public nextFrameFunc: Function;
constructor(args: CustomCallbackArgs, yieldEvery?: YieldEveryOptions) {
super();
this.nowFunc = args.nowFunc;
this.nextFrameFunc = args.nextFrameFunc || nextFrame;
this.yieldEvery = yieldEvery || 'auto';
if (this.yieldEvery === 'auto') {
this.yieldEvery = DEFAULT_YIELD_EVERY_MS;
}
if (this.yieldEvery === 'never' && args.onYield != null) {
throw new Error(
'yieldEvery is `never` but you provided an `onYield` callback. ' +
'Either change `yieldEvery` or remove the callback');
}
if (util.isNumber(this.yieldEvery)) {
// Decorate `maybeWait` so it will be called at most once every
// `yieldEvery` ms.
this.maybeWait = generic_utils.debounce(
this.maybeWait.bind(this), this.yieldEvery as number, this.nowFunc);
}
this.trainBegin = args.onTrainBegin;
this.trainEnd = args.onTrainEnd;
this.epochBegin = args.onEpochBegin;
this.epochEnd = args.onEpochEnd;
this.batchBegin = args.onBatchBegin;
this.batchEnd = args.onBatchEnd;
this.yield = args.onYield;
}
async maybeWait(epoch: number, batch: number, logs: UnresolvedLogs) {
const ps: Array<void|Promise<void>> = [];
if (this.yield != null) {
await resolveScalarsInLogs(logs);
ps.push(this.yield(epoch, batch, logs as Logs));
}
ps.push(this.nextFrameFunc());
await Promise.all(ps);
}
async onEpochBegin(epoch: number, logs?: UnresolvedLogs): Promise<void> {
this.currentEpoch = epoch;
if (this.epochBegin != null) {
await resolveScalarsInLogs(logs);
await this.epochBegin(epoch, logs as Logs);
}
}
async onEpochEnd(epoch: number, logs?: UnresolvedLogs): Promise<void> {
const ps: Array<void|Promise<void>> = [];
if (this.epochEnd != null) {
await resolveScalarsInLogs(logs);
ps.push(this.epochEnd(epoch, logs as Logs));
}
if (this.yieldEvery === 'epoch') {
ps.push(this.nextFrameFunc());
}
await Promise.all(ps);
}
async onBatchBegin(batch: number, logs?: UnresolvedLogs): Promise<void> {
if (this.batchBegin != null) {
await resolveScalarsInLogs(logs);
await this.batchBegin(batch, logs as Logs);
}
}
async onBatchEnd(batch: number, logs?: UnresolvedLogs): Promise<void> {
const ps: Array<void|Promise<void>> = [];
if (this.batchEnd != null) {
await resolveScalarsInLogs(logs);
ps.push(this.batchEnd(batch, logs as Logs));
}
if (this.yieldEvery === 'batch') {
ps.push(this.nextFrameFunc());
} else if (util.isNumber(this.yieldEvery)) {
ps.push(this.maybeWait(this.currentEpoch, batch, logs));
}
await Promise.all(ps);
}
async onTrainBegin(logs?: UnresolvedLogs): Promise<void> {
if (this.trainBegin != null) {
await resolveScalarsInLogs(logs);
await this.trainBegin(logs as Logs);
}
}
async onTrainEnd(logs?: UnresolvedLogs): Promise<void> {
if (this.trainEnd != null) {
await resolveScalarsInLogs(logs);
await this.trainEnd(logs as Logs);
}
}
}
/**
* Standardize callbacks or configurations of them to an Array of callbacks.
*/
export function standardizeCallbacks(
callbacks: BaseCallback|BaseCallback[]|CustomCallbackArgs|
CustomCallbackArgs[],
yieldEvery: YieldEveryOptions): BaseCallback[] {
if (callbacks == null) {
callbacks = {} as BaseCallback;
}
if (callbacks instanceof BaseCallback) {
return [callbacks];
}
if (Array.isArray(callbacks) && callbacks[0] instanceof BaseCallback) {
return callbacks as BaseCallback[];
}
// Convert custom callback configs to custom callback objects.
const callbackConfigs =
generic_utils.toList(callbacks) as CustomCallbackArgs[];
return callbackConfigs.map(
callbackConfig => new CustomCallback(callbackConfig, yieldEvery));
}
export declare type BaseCallbackConstructor = {
new (): BaseCallback
};
/**
* A global registry for callback constructors to be used during
* LayersModel.fit().
*/
export class CallbackConstructorRegistry {
private static constructors:
{[verbosityLevel: number]: BaseCallbackConstructor[]} = {};
/**
* Blocks public access to constructor.
*/
private constructor() {}
/**
* Register a tf.LayersModel.fit() callback constructor.
*
* The registered callback constructor will be used to instantiate
* callbacks for every tf.LayersModel.fit() call afterwards.
*
* @param verbosityLevel Level of verbosity at which the `callbackConstructor`
* is to be reigstered.
* @param callbackConstructor A no-arg constructor for `tf.Callback`.
* @throws Error, if the same callbackConstructor has been registered before,
* either at the same or a different `verbosityLevel`.
*/
static registerCallbackConstructor(
verbosityLevel: number, callbackConstructor: BaseCallbackConstructor) {
util.assert(
verbosityLevel >= 0 && Number.isInteger(verbosityLevel),
() => `Verbosity level is expected to be an integer >= 0, ` +
`but got ${verbosityLevel}`);
CallbackConstructorRegistry.checkForDuplicate(callbackConstructor);
if (CallbackConstructorRegistry.constructors[verbosityLevel] == null) {
CallbackConstructorRegistry.constructors[verbosityLevel] = [];
}
CallbackConstructorRegistry.constructors[verbosityLevel].push(
callbackConstructor);
}
private static checkForDuplicate(callbackConstructor:
BaseCallbackConstructor) {
for (const levelName in CallbackConstructorRegistry.constructors) {
const constructors = CallbackConstructorRegistry.constructors[+levelName];
constructors.forEach(ctor => {
if (ctor === callbackConstructor) {
throw new ValueError('Duplicate callback constructor.');
}
});
}
}
/**
* Clear all registered callback constructors.
*/
protected static clear() {
CallbackConstructorRegistry.constructors = {};
}
/**
* Create callbacks using the registered callback constructors.
*
* Given `verbosityLevel`, all constructors registered at that level or above
* will be called and the instantiated callbacks will be used.
*
* @param verbosityLevel: Level of verbosity.
*/
static createCallbacks(verbosityLevel: number): BaseCallback[] {
const constructors: BaseCallbackConstructor[] = [];
for (const levelName in CallbackConstructorRegistry.constructors) {
const level = +levelName;
if (verbosityLevel >= level) {
constructors.push(...CallbackConstructorRegistry.constructors[level]);
}
}
return constructors.map(ctor => new ctor());
}
}
export function configureCallbacks(
callbacks: BaseCallback[], verbose: ModelLoggingVerbosity, epochs: number,
initialEpoch: number, numTrainSamples: number, stepsPerEpoch: number,
batchSize: number, doValidation: boolean,
callbackMetrics: string[]): {callbackList: CallbackList, history: History} {
const history = new History();
const actualCallbacks: BaseCallback[] = [
new BaseLogger(), ...CallbackConstructorRegistry.createCallbacks(verbose)
];
if (callbacks != null) {
actualCallbacks.push(...callbacks);
}
actualCallbacks.push(history);
const callbackList = new CallbackList(actualCallbacks);
// TODO(cais): Figure out when this LayersModel instance can have a
// dynamically
// set property called 'callback_model' as in PyKeras.
callbackList.setParams({
epochs,
initialEpoch,
samples: numTrainSamples,
steps: stepsPerEpoch,
batchSize,
verbose,
doValidation,
metrics: callbackMetrics,
});
return {callbackList, history};
} | the_stack |
import {
Component, forwardRef, OnInit, ViewEncapsulation,
Input, Output, EventEmitter, AfterViewInit,
OnChanges
} from '@angular/core';
import { InputCoreComponent } from '@sq-ui/ng-sq-common';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { CalendarDay, InCalendarPicker } from '../interfaces/calendar-entities';
import { CalendarPeriodRelativityEnum } from '../enums/calendar-period-relativity.enum';
import { DateRange } from '../interfaces/date-range';
import { CalendarPeriodTypeEnum } from '../enums/calendar-period-type.enum';
import { DateObjectType } from '../enums/date-object-type.enum';
import { TimepickerConfig } from '../interfaces/timepicker-config';
import { List } from 'immutable';
import { CalendarManagerService } from '../calendar-manager.service';
// temporary fix for https://github.com/ng-packagr/ng-packagr/issues/217#issuecomment-360176759
import * as momentNs from 'moment';
const moment = momentNs;
const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => DatetimePickerComponent),
multi: true
};
@Component({
selector: 'sq-datetime-picker',
templateUrl: './datetime-picker.component.html',
styleUrls: ['./datetime-picker.component.scss'],
encapsulation: ViewEncapsulation.None,
providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class DatetimePickerComponent extends InputCoreComponent implements OnInit, AfterViewInit, OnChanges {
@Input() locale = 'en';
@Input() maxDate: momentNs.Moment | Date;
@Input() minDate: momentNs.Moment | Date;
@Input() isMultipleSelect = false;
@Input() format: string;
@Input() isTimepickerEnabled = false;
@Input() dateObjectType: string = DateObjectType.Moment;
@Input() timepickerConfig: TimepickerConfig;
@Output() dateSelectionChange: EventEmitter<momentNs.Moment | Date> = new EventEmitter<momentNs.Moment | Date>();
weekdays: string[];
months: InCalendarPicker[];
yearsList: InCalendarPicker[];
calendar: Array<CalendarDay[]>;
currentMonth: momentNs.Moment;
isMonthsPickerEnabled = false;
isYearsPickerEnabled = false;
time: momentNs.Moment;
calendarPeriodRelativity = CalendarPeriodRelativityEnum;
period: CalendarPeriodTypeEnum = CalendarPeriodTypeEnum.Month;
private selectedDates: List<momentNs.Moment> = List<momentNs.Moment>();
private parsedSelectedDates: any;
constructor(private calendarManager: CalendarManagerService) {
super();
}
ngOnInit() {
moment.locale(this.locale);
this.calendarManager.setLocale(this.locale);
const now = moment().hours(0).minutes(0).locale(this.locale);
this.selectedDates = List([now.clone()]);
this.weekdays = this.calendarManager.getWeekdays();
this.calendar = this.getMonthCalendar(now.clone());
this.initializeAuthorValuesIfAny();
}
ngAfterViewInit() {
setTimeout(() => {
this.setValueResult();
});
}
ngOnChanges(changesObj) {
if (changesObj.timepickerConfig && changesObj.timepickerConfig.currentValue) {
this.setValueResult();
}
}
onDateClick(date: CalendarDay) {
switch (date.relativityToCurrentMonth) {
case CalendarPeriodRelativityEnum.After:
this.select(date);
this.next();
break;
case CalendarPeriodRelativityEnum.Before:
this.select(date);
this.previous();
break;
default:
this.select(date);
break;
}
}
select(date: CalendarDay) {
const month = this.currentMonth.clone();
if (date.relativityToCurrentMonth === CalendarPeriodRelativityEnum.Before) {
month.subtract(1, 'month');
}
if (date.relativityToCurrentMonth === CalendarPeriodRelativityEnum.After) {
month.add(1, 'month');
}
this.markDateAsSelected(date);
this.dateSelectionChange.emit(this.value);
}
next() {
if (this.period === CalendarPeriodTypeEnum.Month) {
const nextMonth = this.currentMonth.add(1, 'month');
this.calendar = this.getMonthCalendar(nextMonth);
}
if (this.period === CalendarPeriodTypeEnum.Year) {
const dateRange = {
minDate: moment(this.minDate),
maxDate: moment(this.maxDate)
};
this.yearsList = this.calendarManager.generateYearPickerCollection(null, 19, dateRange);
}
}
previous() {
if (this.period === CalendarPeriodTypeEnum.Month) {
const previousMonth = this.currentMonth.subtract(1, 'month');
this.calendar = this.getMonthCalendar(previousMonth);
}
if (this.period === CalendarPeriodTypeEnum.Year) {
const dateRange = {
minDate: moment(this.minDate),
maxDate: moment(this.maxDate)
};
this.yearsList = this.calendarManager.generateYearPickerCollection(null, -19, dateRange);
}
}
getMonthCalendar(startPeriod: momentNs.Moment): Array<CalendarDay[]> {
const selectedDates = this.selectedDates.toArray();
const dateRange: DateRange = {
minDate: this.minDate,
maxDate: this.maxDate
};
this.currentMonth = startPeriod.clone();
return this.calendarManager.generateCalendarForMonth(startPeriod, this.currentMonth, selectedDates, dateRange);
}
showMonthsPicker(year: number = this.currentMonth.year()) {
this.deselectAll();
this.isYearsPickerEnabled = false;
this.isMonthsPickerEnabled = true;
this.currentMonth.year(year);
const dateRange = {
minDate: this.minDate,
maxDate: this.maxDate
};
this.period = CalendarPeriodTypeEnum.Month;
this.months = this.calendarManager.generateMonthPickerCollection(year, dateRange);
}
showYearsPicker() {
this.deselectAll();
this.isMonthsPickerEnabled = false;
this.isYearsPickerEnabled = true;
const dateRange = {
minDate: this.minDate,
maxDate: this.maxDate
};
this.period = CalendarPeriodTypeEnum.Year;
this.yearsList = this.calendarManager.generateYearPickerCollection(this.currentMonth, 19, dateRange);
}
selectMonth(month) {
this.calendar = this.getMonthCalendar(month.momentObj);
this.isMonthsPickerEnabled = false;
}
selectYear(year) {
this.showMonthsPicker(year.momentObj.year());
}
onTimeChange() {
this.setValueResult();
this.dateSelectionChange.emit(this.value);
}
private initializeAuthorValuesIfAny() {
const subscription = this._modelToViewChange.subscribe((newValue) => {
if (this.selectedDates.size === 1 && this.selectedDates.get(0).isSame(moment(), 'day')) {
if (newValue) {
this.deselectAll();
if (Array.isArray(newValue)) {
newValue.forEach((date) => {
const convertedDate = this.calendarManager.findADateFromCalendar(moment(date), this.calendar);
this.markDateAsSelected(convertedDate);
});
} else {
const calendarDay = this.calendarManager.findADateFromCalendar(moment(newValue), this.calendar);
this.markDateAsSelected(calendarDay);
}
}
}
subscription.unsubscribe();
});
}
private markDateAsSelected(date: CalendarDay) {
const selectedMomentObj = moment(date.momentObj);
const selectedIndex = this.calendarManager.getSelectedItemIndex(selectedMomentObj, this.selectedDates.toArray());
if (this.isMultipleSelect) {
if (selectedIndex > -1) {
date.isSelected = false;
this.selectedDates = this.selectedDates.remove(selectedIndex);
} else {
this.selectedDates = this.selectedDates.push(selectedMomentObj);
date.isSelected = true;
}
} else {
const previousDate = this.calendarManager.findADateFromCalendar(this.selectedDates.get(0), this.calendar);
if (previousDate) {
previousDate.isSelected = false;
}
this.selectedDates = this.selectedDates.clear();
this.selectedDates = this.selectedDates.push(selectedMomentObj);
date.isSelected = true;
}
this.setValueResult();
}
private deselectAll() {
this.selectedDates.toArray().forEach((selectedDate) => {
const calendarDay = this.calendarManager.findADateFromCalendar(selectedDate, this.calendar);
// this handles the case when we have a selected date
// from the previous month but we haven't selected anything
// from the current
if (calendarDay) {
calendarDay.isSelected = false;
}
});
this.selectedDates = List([]);
this.setValueResult();
}
private setValueResult() {
this.parsedSelectedDates = this.selectedDates.toArray();
if (this.parsedSelectedDates.length > 0) {
this.setValueTimeIfNeeded();
this.sortValueIfNeeded();
this.toValueDateObjectTypeIfNeeded();
this.toValueFormatIfNeeded();
}
if (this.isMultipleSelect) {
this.value = this.parsedSelectedDates;
} else {
this.value = this.parsedSelectedDates[0];
}
}
private toValueDateObjectTypeIfNeeded() {
if (!this.format) {
switch (this.dateObjectType) {
case DateObjectType.Date:
this.parsedSelectedDates = this.parsedSelectedDates.map((momentObj) => {
return momentObj.toDate();
});
break;
case DateObjectType.Unix:
this.parsedSelectedDates = this.parsedSelectedDates.map((momentObj) => {
return momentObj.toDate().getTime();
});
break;
}
}
}
private toValueFormatIfNeeded() {
if (this.format) {
const formattedDates = this.parsedSelectedDates.map((date) => {
return moment(date).format(this.format);
});
this.parsedSelectedDates = formattedDates;
}
}
private setValueTimeIfNeeded() {
if (this.isTimepickerEnabled && this.time) {
const datesWithTime = this.parsedSelectedDates.map((momentObj) => {
return momentObj.hours(this.time.hours()).minutes(this.time.minutes());
});
this.parsedSelectedDates = datesWithTime;
}
}
private sortValueIfNeeded() {
if (this.isMultipleSelect) {
const sortedDates = this.calendarManager.sortDatesAsc(this.parsedSelectedDates);
this.parsedSelectedDates = sortedDates;
}
}
} | the_stack |
import { Tree } from '@angular-devkit/schematics';
import { SchematicTestRunner } from '@angular-devkit/schematics/testing';
import { collectionPath } from './common';
describe('spec', () => {
let tree: Tree;
beforeEach(() => {
tree = Tree.empty();
tree.create('empty-class.ts', 'export class EmptyClass {}');
});
it('throws when name is not passed in', async () => {
const runner = new SchematicTestRunner('schematics', collectionPath);
return runner.runSchematicAsync('spec', {}, tree).toPromise()
.then(() => fail('should throw'))
.catch(e => expect(e).toBeDefined());;
});
it('creates a file when name is passed in', async () => {
const runner = new SchematicTestRunner('schematics', collectionPath);
const result = await runner.runSchematicAsync('spec', { name: 'empty-class.ts' }, tree).toPromise();
expect(result.files.length).toBe(2); // the empty class + the new spec file
expect(result.files[1]).toMatch('empty-class.spec.ts');
});
it('creates a file with a non-empty content ', async () => {
// arrange
const runner = new SchematicTestRunner('schematics', collectionPath);
// act
const result = await runner.runSchematicAsync('spec', { name: 'empty-class.ts' }, tree).toPromise();
// assert
expect(result.readContent('empty-class.spec.ts').length).toBeGreaterThan(0);
});
describe('targeting the EmptyClass', () => {
it('creates a file with the boilerplate setup method ', async () => {
// arrange
const runner = new SchematicTestRunner('schematics', collectionPath);
// act
const result = await runner.runSchematicAsync('spec', { name: 'empty-class.ts' }, tree).toPromise();
// assert
const contents = result.readContent('empty-class.spec.ts');
expect(contents).toMatch(/function setup\(\) {/);
expect(contents).toMatch(/const builder = {/);
expect(contents).toMatch(/return new EmptyClass\(\);/);
});
});
describe('targeting a nested path file', () => {
let tree: Tree;
beforeEach(() => {
tree = Tree.empty();
tree.create('./a-folder/with/an/empty-class.ts', 'export class EmptyClass {}');
});
it('creates a file in the same path depth as the name passed in', async () => {
const runner = new SchematicTestRunner('schematics', collectionPath);
const result = await runner.runSchematicAsync(
'spec',
{ name: './a-folder/with/an/empty-class.ts' },
tree
).toPromise();
expect(result.files.length).toBe(2); // the empty class + the new spec file
expect(result.files[1]).toMatch('/a-folder/with/an/empty-class.spec.ts');
});
});
describe('targeting the has-one-constructor-param class', () => {
beforeEach(() => {
tree = Tree.empty();
tree.create(
'has-one-constructor-parameter.ts',
`export class HasOneConstructorParameter {
constructor(service: Object) {}
}`
);
});
it('it creates boilerplate with a new instance with one matching constructor parameter ', async () => {
// arrange
const runner = new SchematicTestRunner('schematics', collectionPath);
// act
const result = await runner.runSchematicAsync(
'spec',
{ name: 'has-one-constructor-parameter.ts' },
tree
).toPromise();
// assert
const contents = result.readContent('has-one-constructor-parameter.spec.ts');
expect(contents).toMatch(/return new HasOneConstructorParameter\(service\);/);
});
});
describe('targeting the example component class', () => {
let exampleComponentTree: Tree;
beforeEach(() => {
exampleComponentTree = Tree.empty();
exampleComponentTree.create(
'example.component.ts',
`export class ExampleComponent {
publicProperty: boolean;
private privateProperty: string;
aMethod(dep: string, service: Object) {}
//a constructor comment
constructor(
/** shows in full text and is hidden in text */ dep: string,
service: Object
) {}
// an async public method
async anotherMethod() {}
private third() {}
public fourth() {}
protected protectedMethod() {}
}
`
);
});
it('creates a file with matching number of `it` calls for each public method ', async () => {
// arrange
const runner = new SchematicTestRunner('schematics', collectionPath);
// act
const result = await runner.runSchematicAsync(
'spec',
{ name: 'example.component.ts' },
exampleComponentTree
).toPromise();
// assert
const contents = result.readContent('example.component.spec.ts');
expect(contents).toMatch(/it\('when aMethod is called/);
expect(contents).toMatch(/it\('when anotherMethod is called/);
expect(contents).toMatch(/it\('when fourth is called/);
expect(contents).not.toMatch(
/it\('when third is called/
//'method `third` is private - we should not create a test for it '
);
expect(contents).not.toMatch(
/it\('when protectedMethod is called/
//'method `protectedMethod` is protected - we should not create a test for it '
);
});
it('creates a file with `it` tests actually calling the public methods of the component/class ', async () => {
// arrange
const runner = new SchematicTestRunner('schematics', collectionPath);
// act
const result = await runner.runSchematicAsync(
'spec',
{ name: 'example.component.ts' },
exampleComponentTree
).toPromise();
// assert
const contents = result.readContent('example.component.spec.ts');
expect(contents).toMatch(/it\('when aMethod is called/); // the `it` test method
expect(contents).toMatch(/\.aMethod\(\)/g); // the call to the component's `aMethod` method
});
});
describe('targeting a class with imports', () => {
let treeImports: Tree;
beforeEach(() => {
treeImports = Tree.empty();
treeImports.create(
'with-imports.component.ts',
`import { Router } from '@angular/core';
import { ADep} from '../../deps/a-dep.ts';
import {local} from './local.ts'
import * as AnotherDep from './local-deps/a-depth.service.ts';
export class WithImportsComponent {
constructor(
private router: Router,
private aDep: ADep,
private anoter: AnotherDep,
local: local,
simple: Object
) {}
}`
);
});
it('adds the imports for the dependencies', async () => {
// arrange
const runner = new SchematicTestRunner('schematics', collectionPath);
// act
const result = await runner.runSchematicAsync(
'spec',
{ name: 'with-imports.component.ts' },
treeImports
).toPromise();
// assert
const contents = result.readContent('with-imports.component.spec.ts');
expect(contents).toMatch(`import { Router } from '@angular/core';`);
expect(contents).toMatch(`import { ADep } from '../../deps/a-dep.ts';`);
expect(contents).toMatch(
`import { AnotherDep } from './local-deps/a-depth.service.ts';`
);
expect(contents).toMatch(`import { local } from './local.ts';`);
expect(contents).not.toMatch(`import { Object } from ''`);
});
it('adds the imports for the dependencies when updating', async () => {
// arrange
const runner = new SchematicTestRunner('schematics', collectionPath);
// act
treeImports.create(
'with-imports.component.spec.ts',
`describe("WithImports", () => {});
function setup() {
const builder = {
default() {
return builder;
},
build() {
return new WithImportsComponent();
}
};
return builder;
}
`
);
const result = await runner.runSchematicAsync(
'spec',
{ name: 'with-imports.component.ts', update: true },
treeImports
).toPromise();
// assert
const contents = result.readContent('with-imports.component.spec.ts');
expect(contents).toMatch(`import { Router } from '@angular/core';`);
expect(contents).toMatch(`import { ADep } from '../../deps/a-dep.ts';`);
expect(contents).toMatch(
`import { AnotherDep } from './local-deps/a-depth.service.ts';`
);
expect(contents).toMatch(`import { local } from './local.ts';`);
expect(contents).not.toMatch(`import { Object } from ''`);
});
});
}); | the_stack |
import {Component, Input, AfterViewInit, Output, EventEmitter, NgZone, ViewChild} from '@angular/core';
import {OGraph} from './d3-graph/OGraph';
import {AddEdgeModal} from './modal/addEdgeModal/addEdgeModal.component'
import {downgradeComponent} from '@angular/upgrade/static';
import {NotificationService} from "../../core/services/notification.service";
declare var angular:any;
// declare var OrientGraph:any;
@Component({
selector: 'graph',
templateUrl: "./graph.component.html",
})
class GraphComponent implements AfterViewInit {
private orientGraph:OGraph;
private self = this;
@Input() modellingConfig = this.modellingConfig !== 'undefined' ? this.modellingConfig : 'no config from parent.';
@Output() modellingConfigChange = new EventEmitter();
@Input() selectedElement;
@Output() onSelectedElement = new EventEmitter();
private elementId = '#graph';
private opts;
/**
* Modals
*/
@ViewChild('addEdgeModalWrapper') addEdgeModalWrapper;
constructor(private notification: NotificationService, private zone: NgZone) {
this.init();
}
init() {
this.opts = {
metadata: "no metadata",
config: {
height:460,
width: 700,
classes: {},
node: {
r: 15
},
linkDistance: 350,
linkStrength: 0.1,
charge: -1000,
friction: 0.9,
gravity: 0.1
},
edgeMenu: [
{
name: '\uf044',
onClick: function (e) {
// if (e.edge) {
// $scope.showModal(e, e.edge["@rid"]);
// }
}
},
{
name: '\uf06e',
onClick: function (e) {
// var title = "Edge (" + e.label + ")";
// $scope.doc = e.edge;
// Aside.show({
// scope: $scope,
// title: title,
// template: 'views/database/graph/asideEdge.html',
// show: true,
// absolute: false,
// fullscreen: $scope.fullscreen
// });
}
},
{
name: '\uf127',
onClick: function (e) {
// var recordID = e['@rid']
// Utilities.confirm($scope, $modal, $q, {
// title: 'Warning!',
// body: 'You are removing Edge ' + e.label + ' from ' + e.source["@rid"] + ' to ' + e.target["@rid"] + ' . Are you sure?',
// success: function () {
//
//
// var command = ""
// if (e.edge && e.edge["@rid"]) {
// command = "DELETE EDGE " + e.edge["@rid"];
// }
// else {
// command = "DELETE EDGE " + e.label + " FROM " + e.source["@rid"] + " TO " + e.target["@rid"] + " where @class='" + e.label + "'";
// }
//
// CommandApi.queryText({
// database: $routeParams.database,
// language: 'sql',
// text: command,
// verbose: false
// }, function (data) {
// $scope.graph.removeEdge(e);
// });
// }
// });
}
}
],
menu: [
{
name: '\uf044',
onClick: function (v) {
// if (v['@rid'].startsWith("#-")) {
//
// $scope.$apply(function () {
// Notification.push({content: 'Cannot edit a temporary node', autoHide: true, warning: true});
// });
//
// } else {
// $scope.showModal(v, v.source["@rid"]);
// }
}
},
{
name: "\uf18e",
onClick: function (v) {
},
submenu: {
type: "tree",
entries: function (v) {
var acts = [];
if (v.relationships && v.relationships.out) {
v.relationships.out.forEach(function (elem) {
var name = elem.replace("out_", "");
name = (name != "" ? name : "E");
var nameLabel = name;
var nameLabel = (name != "" ? name : "E");
if (v.relCardinality && v.relCardinality["out_" + name]) {
nameLabel += " (" + v.relCardinality["out_" + name] + ")"
}
acts.push(
{
name: nameLabel,
label: name,
onClick: function (v, label) {
// if (v['@rid'].startsWith("#-")) {
//
// $scope.$apply(function () {
// Notification.push({
// content: 'Cannot navigate relationship of a temporary node',
// autoHide: true,
// warning: true
// });
// });
//
// } else {
// if (label == "E") {
// label = "";
// }
// else {
// label = "'" + label + "'";
// }
//
// var props = {rid: v['@rid'], label: label};
// var query = "traverse out({{label}}) from {{rid}} while $depth < 2 "
// var queryText = S(query).template(props).s;
//
//
// CommandApi.graphQuery(queryText, {
// database: $routeParams.database,
// language: 'sql',
// limit: -1
// }).then(function (data) {
// $scope.graph.data(data.graph).redraw();
// })
//
// }
}
}
)
})
}
return acts;
}
}
},
{
name: "...",
onClick: function (v) {
},
submenu: {
type: "pie",
entries: [
{
name: "\uf014",
placeholder: "Delete",
onClick: function (v, label) {
// if (v['@rid'].startsWith("#-")) {
//
// $scope.$apply(function () {
// Notification.push({content: 'Cannot delete a temporary node', autoHide: true, warning: true});
// });
//
// } else {
// var recordID = v['@rid']
// Utilities.confirm($scope, $modal, $q, {
// title: 'Warning!',
// body: 'You are removing Vertex ' + recordID + '. Are you sure?',
// success: function () {
// var command = "DELETE Vertex " + recordID;
// CommandApi.queryText({
// database: $routeParams.database,
// language: 'sql',
// text: command,
// verbose: false
// }, function (data) {
// $scope.graph.removeVertex(v);
// });
// }
// });
// }
}
},
{
name: "\uf12d",
placeholder: "Remove from canvas",
onClick: function (v, label) {
// $scope.graph.removeVertex(v);
}
}
]
}
},
{
name: "\uf0c1",
placeholder: "Connect",
onClick: function (v) {
// if (v['@rid'].startsWith("#-")) {
//
// $scope.$apply(function () {
// Notification.push({content: 'Cannot connect a temporary node', autoHide: true, warning: true});
// });
//
// } else {
//
// $scope.graph.startEdge();
// }
}
},
{
name: "\uf18e",
onClick: function (v) {
},
submenu: {
type: "tree",
entries: function (v) {
var acts = [];
if (v.relationships || v.relationships.in) {
v.relationships.in.forEach(function (elem) {
var name = elem.replace("in_", "");
name = (name != "" ? name : "E");
var nameLabel = name;
if (v.relCardinality && v.relCardinality["in_" + name]) {
nameLabel += " (" + v.relCardinality["in_" + name] + ")"
}
acts.push(
{
name: nameLabel,
label: name,
onClick: function (v, label) {
// if (label == "E") {
// label = "";
// }
// else {
// label = "'" + label + "'";
// }
//
// var props = {rid: v['@rid'], label: label};
// var query = "traverse in({{label}}) from {{rid}} while $depth < 2 "
// var queryText = S(query).template(props).s;
//
//
// CommandApi.graphQuery(queryText, {
// database: $routeParams.database,
// language: 'sql',
// limit: -1
// }).then(function (data) {
// $scope.graph.data(data.graph).redraw();
// })
}
}
)
})
}
return acts;
}
}
},
{
name: "\uf06e",
onClick: function (v) {
// $scope.doc = v.source;
// var title = $scope.doc['@class'] + " - " + $scope.doc['@rid']
// Aside.show({
// scope: $scope,
// title: title,
// template: 'views/database/graph/asideVertex.html',
// show: true,
// absolute: false,
// fullscreen: $scope.fullscreen
// });
}
}
]
}
}
ngAfterViewInit() {
this.loadGraph();
}
loadGraph() {
if(this.opts.config) {
this.orientGraph = new OGraph(this.elementId, this.opts.config, this);
this.orientGraph.data(this.modellingConfig).draw();
}
}
searchNode(targetName) {
var matchingNode = this.orientGraph.searchNode(targetName);
if(!matchingNode) {
this.notification.push({content: "Node not found.", error: true, autoHide: true});
}
}
setSelectedElement(selectedElement) {
this.selectedElement = selectedElement;
this.onSelectedElement.emit(this.selectedElement);
}
renameElementInGraph(oldClassName, newClassName, classType) {
this.orientGraph.updateElementsAccordingToRenamedClassed(oldClassName, newClassName, classType);
}
removeClassInGraph(className, classType) {
this.orientGraph.removeClass(className, classType);
}
removeEdgeInstanceInGraph(edgeClassName, sourceName, targetName) {
this.orientGraph.removeEdgeInstance(edgeClassName, sourceName, targetName);
}
startEdgeCreation() {
this.orientGraph.startEdgeCreation();
}
openEdgeCreationModal(fromVertex, toVertex, edgeClassesNames) {
this.addEdgeModalWrapper.openAddEdgeModal(fromVertex, toVertex, edgeClassesNames);
}
endEdgeCreation(newEdge) {
this.orientGraph.endEdgeCreation(newEdge);
}
redraw() {
this.orientGraph.redraw();
}
}
angular.module('graph.component', []).directive(
`graph`,
downgradeComponent({component: GraphComponent}));
export {GraphComponent}; | the_stack |
import { minBy } from "lodash-es"
import { Twist } from "types"
import { mapObject } from "utils"
import Classical, { Facet, Family } from "data/specs/Classical"
import { makeOpPair, combineOps, Pose } from "./operationPairs"
import { angleBetween, getPlane, withOrigin, Vec3D } from "math/geom"
import { Polyhedron, Face, Edge } from "math/polyhedra"
import {
getOppTwist,
oppositeFace,
getTransformedVertices,
FacetOpts,
TwistOpts,
getGeometry,
} from "./operationUtils"
import Operation, { makeOperation } from "./Operation"
function getSnubTetrahedronFaces(polyhedron: Polyhedron) {
const f0 = polyhedron.faceWithNumSides(3)
return [f0, ...f0.edges.map((e) => oppositeFace(e, "right"))]
}
function getCantellatedTetrahedronFaces(polyhedron: Polyhedron, odd?: boolean) {
let f0 = polyhedron.faceWithNumSides(3)
if (odd) {
f0 = f0.edges[0].twin().next().twinFace()
}
return [f0, ...f0.edges.map((e) => oppositeFace(e))]
}
function getBevelledTetrahedronFaces(polyhedron: Polyhedron) {
const f0 = polyhedron.faceWithNumSides(6)
const rest = f0.edges
.filter((e) => e.twinFace().numSides === 4)
.map((e) => oppositeFace(e))
return [f0, ...rest]
}
function getSnubFaces(specs: Classical, polyhedron: Polyhedron, facet?: Facet) {
if (specs.isTetrahedral()) {
return getSnubTetrahedronFaces(polyhedron)
}
return polyhedron.faces.filter((face) =>
isSnubFace(face, getFaceType(specs, facet)),
)
}
function getBevelledFaces(specs: Classical, geom: Polyhedron, facet: Facet) {
if (specs.isTetrahedral()) {
return getBevelledTetrahedronFaces(geom)
}
return geom.faces.filter((f) => f.numSides === 2 * getFaceType(specs, facet))
}
function getCantellatedFaces(
specs: Classical,
geom: Polyhedron,
facet?: Facet,
odd?: boolean,
) {
if (specs.isTetrahedral()) {
return getCantellatedTetrahedronFaces(geom, odd)
}
return geom.faces.filter((face) =>
isCantellatedFace(face, getFaceType(specs, facet)),
)
}
/**
* Return the expanded vertices of the polyhedron resized to the given distance-from-center
* and rotated by the given angle
*
* @param faces the faces to transform
* @param distance the normalized distance from center to put those faces
* @param angle the angle to twist the faces by
*/
function getResizedVertices(
faces: Face[],
distance: number,
angle: number = 0,
) {
const resizedLength = faces[0].sideLength() * distance
const f0 = faces[0]
const scale = resizedLength - f0.distanceToCenter()
return getTransformedVertices(faces, (f) =>
withOrigin(f.centroid(), (v) =>
v.getRotatedAroundAxis(f.normal(), angle).add(f.normal().scale(scale)),
),
)
}
function getSchafli(specs: Classical) {
return specs.isFace() ? [specs.data.family, 3] : [3, specs.data.family]
}
const coxeterNum = { 3: 4, 4: 6, 5: 10 }
const { sin, cos, tan, PI } = Math
// get tan(theta/2) where theta is the dihedral angle of the platonic solid
function tanDihedralOver2(specs: Classical) {
const [, q] = getSchafli(specs)
const h = coxeterNum[specs.data.family]
return cos(PI / q) / sin(PI / h)
}
function getInradius(specs: Classical) {
const [p] = getSchafli(specs)
return tanDihedralOver2(specs) / tan(PI / p) / 2
}
function getMidradius(specs: Classical) {
const [p] = getSchafli(specs)
const h = coxeterNum[specs.data.family]
return cos(PI / p) / sin(PI / h) / 2
}
function getCircumradius(specs: Classical) {
const [, q] = getSchafli(specs)
return (tan(PI / q) * tanDihedralOver2(specs)) / 2
}
// Get the face type for the given facet and solid specs
function getFaceType(specs: Classical, facet?: Facet) {
return facet === "vertex" ? 3 : specs.data.family
}
function apothemVec(edge: Edge) {
return edge.midpoint().sub(edge.face.centroid())
}
/**
* Return the snub angle of the given polyhedron, given the list of expanded faces
*/
export function calcSnubAngle(specs: Classical, facet: Facet) {
// Choose one of the expanded faces and get its properties
const polyhedron = getGeometry(specs)
const expandedFaces = getSnubFaces(specs, polyhedron, facet)
const [face0, ...rest] = expandedFaces
const faceCentroid = face0.centroid()
const midpoint = face0.edges[0].midpoint()
// Choose one of the closest faces
const face1 = minBy(rest, (face) => midpoint.distanceTo(face.centroid()))!
const plane = getPlane([
faceCentroid,
face1.centroid(),
polyhedron.centroid(),
])
// Calculate the absolute angle between the two midpoints
return angleBetween(faceCentroid, midpoint, plane.getProjectedPoint(midpoint))
}
function createObject<T extends string | number, U>(
items: T[],
iter: (item: T) => U,
) {
return mapObject(items, (item) => [item, iter(item)])
}
// Cache snub angles, since they're always the same
const snubAngles = createObject([3, 4, 5], (family: Family) => {
const specs = Classical.query.withData({ family, operation: "snub" })
return {
face: calcSnubAngle(specs, "face"),
vertex: calcSnubAngle(specs, "vertex"),
}
})
function isCantellatedFace(face: Face, faceType: number) {
return (
face.numSides === faceType &&
face.adjacentFaces().every((f) => f.numSides === 4)
)
}
function isCantellatedEdgeFace(face: Face) {
return (
face.numSides === 4 && face.adjacentFaces().some((f) => f.numSides !== 4)
)
}
export function getCantellatedEdgeFace(geom: Polyhedron) {
const face = geom.faces.find(isCantellatedEdgeFace)
if (!face) throw new Error(`Could not find edge face for ${geom.name}`)
return face
}
export function getCantellatedFace(geom: Polyhedron, faceType: number) {
const face = geom.faces.find((f) => isCantellatedFace(f, faceType))
if (!face) throw new Error(`Could not find cantellated face for ${geom.name}`)
return face
}
function isSnubFace(face: Face, faceType: number) {
return (
face.numSides === faceType &&
face.adjacentFaces().every((f) => f.numSides === 3)
)
}
// TODO deduplicate these (note: bevel has a different criterion for getting face)
const cantellatedDists = createObject([3, 4, 5], (family: Family) => {
const specs = Classical.query.withData({ family, operation: "cantellate" })
const geom = getGeometry(specs)
const face = getCantellatedFace(geom, family)
return face.distanceToCenter() / geom.edgeLength()
})
function calcTruncatedDist(family: Family, facet: Facet) {
const _facet = family === 3 ? undefined : facet
const specs = Classical.query.withData({
family,
operation: "truncate",
facet: _facet,
})
const geom = getGeometry(specs)
const face = geom.largestFace()
return face.distanceToCenter() / geom.edgeLength()
}
const bevelledDists = createObject([3, 4, 5], (family: Family) => {
return {
face: calcTruncatedDist(family, "face"),
vertex: calcTruncatedDist(family, "vertex"),
}
})
function getSnubAngle(specs: Classical, facet: Facet) {
const sign = specs.data.twist === "left" ? -1 : 1
// if vertex-solid, reverse the sign
const sign2 = facet === "vertex" ? -1 : 1
const angle = snubAngles[specs.data.family][facet]
return sign2 * sign * angle
}
/**
* Get the common properties of a resize operation's pose.
*/
function getPose(geom: Polyhedron, face: Face, crossAxis: Vec3D): Pose {
return {
// Always centered on centroid
origin: geom.centroid(),
// Always scale to side length
scale: geom.edgeLength(),
// Use the normal of the given face as the first axis
orientation: [face.normal(), crossAxis],
}
}
// Get the pose of a regular solid for both expand/snub
function getRegularPose(geom: Polyhedron): Pose {
const face = geom.getFace()
return getPose(geom, face, apothemVec(face.edges[0]))
}
function getCantellatedPose(
geom: Polyhedron,
specs: Classical,
facet?: Facet,
): Pose {
const faceType = getFaceType(specs, facet)
// Use an expanded face as the face
const face = getCantellatedFace(geom, faceType)
// Pick one of the edges as cross axis
return getPose(geom, face, apothemVec(face.edges[0]))
}
function getSnubPose(geom: Polyhedron, specs: Classical, facet: Facet): Pose {
const faceType = getFaceType(specs, facet)
// Use an expanded face as the face
const face = geom.faces.find((face) => isSnubFace(face, faceType))!
// Rotate the apothem vector to align it correctly
const crossAxis = apothemVec(face.edges[0]).getRotatedAroundAxis(
face.normal(),
getSnubAngle(specs, facet),
)
return getPose(geom, face, crossAxis)
}
function twistOpts(specs: Classical): Twist[] {
// Snub tetrahedra aren't chiral (yet)
return specs.isTetrahedral() ? ["left"] : ["left", "right"]
}
// Expansion of truncated to bevelled solids
const semiExpand = makeOpPair<Classical, {}, FacetOpts>({
graph: Classical.query
.where((s) => s.isTruncated())
.map((entry) => ({
left: entry,
right: entry.withData({ operation: "bevel" }),
options: { left: {}, right: { facet: entry.data.facet } },
})),
middle: "right",
getPose(pos, { specs, geom }, { right: { facet } }) {
if (pos === "left") {
const face = geom.faces.find((f) => f.numSides > 5)!
const edge = face.edges.find(
(e) => e.twinFace().numSides === face.numSides,
)!
return getPose(geom, face, apothemVec(edge))
} else {
const faceType = 2 * getFaceType(specs, facet)
const face = geom.faceWithNumSides(faceType)
const edge = face.edges.find((e) => e.twinFace().numSides === 4)!
return getPose(geom, face, apothemVec(edge))
}
},
toLeft({ specs, geom }, { right: { facet = "face" } }) {
return getResizedVertices(
getBevelledFaces(specs, geom, facet),
bevelledDists[specs.data.family][facet],
)
},
})
const _expand = makeOpPair<Classical, {}, FacetOpts>({
graph: Classical.query
.where((s) => s.isRegular())
.map((entry) => {
return {
left: entry,
right: entry.withData({ operation: "cantellate" }),
options: { left: {}, right: { facet: entry.data.facet } },
}
}),
middle: "right",
getPose(pos, { geom, specs }, { right: { facet } }) {
return pos === "left"
? getRegularPose(geom)
: getCantellatedPose(geom, specs, facet)
},
toLeft({ specs, geom }, { right: { facet } }, result) {
// Take all the stuff and push it inwards
return getResizedVertices(
getCantellatedFaces(specs, geom, facet),
getInradius(result),
)
},
})
const _snub = makeOpPair<Classical, TwistOpts, FacetOpts>({
graph: Classical.query
.where((s) => s.isRegular())
.flatMap((entry) => {
return twistOpts(entry).map((twist) => ({
left: entry,
right: entry.withData({
operation: "snub",
// If a vertex-solid, the chirality of the result
// is *opposite* of the twist option
twist: entry.isVertex() ? getOppTwist(twist) : twist,
}),
options: { left: { twist }, right: { facet: entry.data.facet } },
}))
}),
middle: "right",
getPose(pos, { geom, specs }, { right: { facet = "face" } }) {
return pos === "left"
? getRegularPose(geom)
: getSnubPose(geom, specs, facet)
},
toLeft({ specs, geom }, { right: { facet = "face" } }, result) {
// Take all the stuff and push it inwards
return getResizedVertices(
getSnubFaces(specs, geom, result.data.facet),
getInradius(result),
getSnubAngle(specs, facet),
)
},
})
const _twist = makeOpPair<Classical, TwistOpts, {}>({
graph: Classical.query
.where((s) => s.isCantellated())
.flatMap((entry) => {
return twistOpts(entry).map((twist) => ({
left: entry,
right: entry.withData({ operation: "snub", twist }),
options: { left: { twist }, right: {} },
}))
}),
middle: "right",
getPose(pos, { specs, geom }) {
return pos === "left"
? getCantellatedPose(geom, specs, "face")
: getSnubPose(geom, specs, "face")
},
toLeft({ specs, geom }) {
return getResizedVertices(
getSnubFaces(specs, geom, "face"),
cantellatedDists[specs.data.family],
getSnubAngle(specs, "face"),
)
},
})
function getCantellatedMidradius(geom: Polyhedron) {
return getCantellatedEdgeFace(geom).distanceToCenter()
}
/**
* Take the cantellated intermediate solid and convert it to either dual
*/
function doDualTransform(specs: Classical, geom: Polyhedron, facet: Facet) {
const resultSpecs = specs.withData({ operation: "regular", facet })
const resultSideLength =
getCantellatedMidradius(geom) / getMidradius(resultSpecs)
const scale = resultSideLength * getCircumradius(resultSpecs)
const oppFacet = facet === "face" ? "vertex" : "face"
const faces = getCantellatedFaces(specs, geom, oppFacet, facet === "face")
return getTransformedVertices(faces, (f) => {
return geom.centroid().add(f.normal().scale(scale))
})
}
const _dual = makeOpPair({
graph: Classical.query
.where((s) => s.isRegular() && !s.isVertex())
.map((specs) => ({
left: specs,
right: specs.withData({ facet: "vertex" }),
})),
middle: (entry) => entry.left.withData({ operation: "cantellate" }),
getPose(pos, { specs, geom }) {
switch (pos) {
case "left": {
return {
...getRegularPose(geom),
// Everything is scaled with the same midradius
scale: geom.edges[0].distanceToCenter(),
}
}
case "right": {
// for the vertex figure, pick a vertex and align it with that edge
const vertex = geom.getVertex()
const normal = vertex.vec.sub(geom.centroid())
const v2 = vertex.adjacentVertices()[0]
return {
origin: geom.centroid(),
scale: geom.edges[0].distanceToCenter(),
orientation: [normal, v2.vec.sub(vertex.vec)],
}
}
case "middle": {
return {
...getCantellatedPose(geom, specs, "face"),
scale: getCantellatedMidradius(geom),
}
}
}
},
toLeft: ({ specs, geom }) => doDualTransform(specs, geom, "face"),
toRight: ({ specs, geom }) => doDualTransform(specs, geom, "vertex"),
})
// Exported members
type ExpansionType = "cantellate" | "snub"
function expansionType(polyhedron: Polyhedron): ExpansionType {
return polyhedron.getVertex().adjacentFaceCounts()[3] >= 3
? "snub"
: "cantellate"
}
const edgeShape = {
snub: 3,
cantellate: 4,
}
// TODO replace with isCantellatedFace and isSnubFace
export function isExpandedFace(
polyhedron: Polyhedron,
face: Face,
nSides?: number,
) {
const type = expansionType(polyhedron)
if (typeof nSides === "number" && face.numSides !== nSides) return false
if (!face.isValid()) return false
return face.adjacentFaces().every((f) => f.numSides === edgeShape[type])
}
export const dual = new Operation("dual", combineOps([_dual.left, _dual.right]))
export const expand = new Operation(
"expand",
combineOps([semiExpand.left, _expand.left]),
)
export const snub = makeOperation("snub", _snub.left)
export const twist = makeOperation(
"twist",
combineOps([_twist.left, _twist.right]),
)
// NOTE: We are using the same operation for contracting both expanded and snub solids.
export const contract = makeOperation<FacetOpts, Classical>("contract", {
...combineOps([_expand, _snub, semiExpand].map((op) => op.right)),
hitOption: "facet",
getHitOption({ specs, geom }, hitPoint) {
const hitFace = geom.hitFace(hitPoint)
const faceType = hitFace.numSides
if (specs.isBevelled()) {
const isValid = hitFace.numSides > 4
return isValid ? { facet: faceType === 6 ? "vertex" : "face" } : {}
}
const isValid = isExpandedFace(geom, hitFace)
return isValid ? { facet: faceType === 3 ? "vertex" : "face" } : {}
},
faceSelectionStates({ specs, geom }, { facet }) {
if (specs.isBevelled()) {
return geom.faces.map((face) => {
const faceType = facet === "vertex" ? 6 : specs.data.family * 2
if (facet && face.numSides === faceType) {
return "selected"
}
if (face.numSides !== 4) return "selectable"
return undefined
})
}
const faceType = !facet ? null : facet === "vertex" ? 3 : specs.data.family
return geom.faces.map((face) => {
if (faceType && isExpandedFace(geom, face, faceType)) return "selected"
if (isExpandedFace(geom, face)) return "selectable"
return undefined
})
},
}) | the_stack |
// Unfortunately, pbf doesn't output modules. And typescript gets upset about the types.
// If this file is regenerated, a lot of manual massaging is required to make it useful.
import Pbf from "pbf";
export abstract class ProtobufMessageReader<T> {
abstract readonly defaultMessage: T;
public read(pbf: Pbf, end?: number): T {
return pbf.readFields(this.readField, this.defaultMessage, end);
}
protected abstract readField(tag: number, obj?: T, pbf?: Pbf): void;
}
// FeedMessage ========================================
export interface FeedMessage {
header?: FeedHeader | null;
entity?: FeedEntity[];
}
export class FeedMessageReader extends ProtobufMessageReader<FeedMessage> {
readonly defaultMessage: FeedMessage = {
header: null,
entity: []
};
constructor() {
super();
}
protected readField(tag: number, obj?: FeedMessage, pbf?: Pbf): void {
if (pbf === null || pbf === undefined) {
return;
}
if (obj === null || obj === undefined) {
obj = {};
}
if (obj.entity === null || obj.entity === undefined) {
obj.entity = [];
}
if (tag === 1)
obj.header = new FeedHeaderReader().read(pbf, pbf.readVarint() + pbf.pos);
else if (tag === 2)
obj.entity.push(
new FeedEntityReader().read(pbf, pbf.readVarint() + pbf.pos)
);
}
}
// FeedHeader ========================================
enum FeedHeaderIncrementality {
FULL_DATASET,
DIFFERENTIAL
}
export interface FeedHeader {
gtfs_realtime_version?: string;
incrementality?: FeedHeaderIncrementality;
timestamp?: number;
}
export class FeedHeaderReader extends ProtobufMessageReader<FeedHeader> {
readonly defaultMessage: FeedHeader = {
gtfs_realtime_version: "",
incrementality: FeedHeaderIncrementality.FULL_DATASET,
timestamp: 0
};
protected readField(tag: number, obj?: FeedHeader, pbf?: Pbf): void {
if (pbf === null || pbf === undefined) {
return;
}
if (obj === null || obj === undefined) {
obj = {};
}
if (tag === 1) obj.gtfs_realtime_version = pbf.readString();
else if (tag === 2) obj.incrementality = pbf.readVarint();
else if (tag === 3) obj.timestamp = pbf.readVarint();
}
}
// FeedEntity ========================================
export interface FeedEntity {
id?: string;
is_deleted?: boolean;
trip_update?: TripUpdate | null;
vehicle?: VehiclePosition | null;
alert?: Alert | null;
}
export class FeedEntityReader extends ProtobufMessageReader<FeedEntity> {
readonly defaultMessage: FeedEntity = {
id: "",
is_deleted: false,
trip_update: null,
vehicle: null,
alert: null
};
protected readField(tag: number, obj?: FeedEntity, pbf?: Pbf): void {
if (pbf === null || pbf === undefined) {
return;
}
if (obj === null || obj === undefined) {
obj = {};
}
if (tag === 1) obj.id = pbf.readString();
else if (tag === 2) obj.is_deleted = pbf.readBoolean();
else if (tag === 3)
obj.trip_update = new TripUpdateReader().read(
pbf,
pbf.readVarint() + pbf.pos
);
else if (tag === 4)
obj.vehicle = new VehiclePositionReader().read(
pbf,
pbf.readVarint() + pbf.pos
);
else if (tag === 5)
obj.alert = new AlertReader().read(pbf, pbf.readVarint() + pbf.pos);
}
}
// TripUpdate ========================================
export interface TripUpdate {
trip?: TripDescriptor | null;
vehicle?: VehicleDescriptor | null;
stop_time_update?: StopTimeUpdate[];
timestamp?: number;
delay?: number;
}
export class TripUpdateReader extends ProtobufMessageReader<TripUpdate> {
readonly defaultMessage: TripUpdate = {
trip: {},
vehicle: {},
stop_time_update: [],
timestamp: 0,
delay: 0
};
protected readField(tag: number, obj?: TripUpdate, pbf?: Pbf): void {
if (pbf === null || pbf === undefined) {
return;
}
if (obj === null || obj === undefined) {
obj = {};
}
if (obj.stop_time_update === null || obj.stop_time_update === undefined) {
obj.stop_time_update = [];
}
if (tag === 1)
obj.trip = new TripDescriptorReader().read(
pbf,
pbf.readVarint() + pbf.pos
);
else if (tag === 3)
obj.vehicle = new VehicleDescriptorReader().read(
pbf,
pbf.readVarint() + pbf.pos
);
else if (tag === 2)
obj.stop_time_update.push(
new StopTimeUpdateReader().read(pbf, pbf.readVarint() + pbf.pos)
);
else if (tag === 4) obj.timestamp = pbf.readVarint();
else if (tag === 5) obj.delay = pbf.readVarint(true);
}
}
// TripUpdate.StopTimeEvent ========================================
export interface StopTimeEvent {
delay?: number;
time?: number;
uncertainty?: number;
}
export class StopTimeEventReader extends ProtobufMessageReader<StopTimeEvent> {
readonly defaultMessage: StopTimeEvent = {
delay: 0,
time: 0,
uncertainty: 0
};
protected readField(tag: number, obj?: StopTimeEvent, pbf?: Pbf): void {
if (pbf === null || pbf === undefined) {
return;
}
if (obj === null || obj === undefined) {
obj = {};
}
if (tag === 1) obj.delay = pbf.readVarint(true);
else if (tag === 2) obj.time = pbf.readVarint(true);
else if (tag === 3) obj.uncertainty = pbf.readVarint(true);
}
}
// TripUpdate.StopTimeUpdate ========================================
export interface StopTimeUpdate {
stop_sequence?: number;
stop_id?: string;
arrival?: StopTimeEvent | null;
departure?: StopTimeEvent | null;
schedule_relationship?: StopTimeUpdateScheduleRelationship;
}
export class StopTimeUpdateReader extends ProtobufMessageReader<
StopTimeUpdate
> {
readonly defaultMessage: StopTimeUpdate = {
stop_sequence: 0,
stop_id: "",
arrival: null,
departure: null,
schedule_relationship: StopTimeUpdateScheduleRelationship.NO_DATA
};
protected readField(tag: number, obj?: StopTimeUpdate, pbf?: Pbf): void {
if (pbf === null || pbf === undefined) {
return;
}
if (obj === null || obj === undefined) {
obj = {};
}
if (tag === 1) obj.stop_sequence = pbf.readVarint();
else if (tag === 4) obj.stop_id = pbf.readString();
else if (tag === 2)
obj.arrival = new StopTimeEventReader().read(
pbf,
pbf.readVarint() + pbf.pos
);
else if (tag === 3)
obj.departure = new StopTimeEventReader().read(
pbf,
pbf.readVarint() + pbf.pos
);
else if (tag === 5) obj.schedule_relationship = pbf.readVarint();
}
}
enum StopTimeUpdateScheduleRelationship {
SCHEDULED,
SKIPPED,
NO_DATA
}
// VehiclePosition ========================================
export interface VehiclePosition {
trip?: TripDescriptor | null;
vehicle?: VehicleDescriptor | null;
position?: Position | null;
current_stop_sequence?: number;
stop_id?: string;
current_status?: VehicleStopStatus;
timestamp?: number;
congestion_level?: CongestionLevel;
occupancy_status?: OccupancyStatus;
}
export class VehiclePositionReader extends ProtobufMessageReader<
VehiclePosition
> {
readonly defaultMessage: VehiclePosition = {
trip: null,
vehicle: null,
position: null,
current_stop_sequence: 0,
stop_id: "",
current_status: VehicleStopStatus.IN_TRANSIT_TO,
timestamp: 0,
congestion_level: CongestionLevel.UNKNOWN_CONGESTION_LEVEL,
occupancy_status: OccupancyStatus.EMPTY
};
protected readField(tag: number, obj?: VehiclePosition, pbf?: Pbf): void {
if (pbf === null || pbf === undefined) {
return;
}
if (obj === null || obj === undefined) {
obj = {};
}
if (tag === 1)
obj.trip = new TripDescriptorReader().read(
pbf,
pbf.readVarint() + pbf.pos
);
else if (tag === 8)
obj.vehicle = new VehicleDescriptorReader().read(
pbf,
pbf.readVarint() + pbf.pos
);
else if (tag === 2)
obj.position = new PositionReader().read(pbf, pbf.readVarint() + pbf.pos);
else if (tag === 3) obj.current_stop_sequence = pbf.readVarint();
else if (tag === 7) obj.stop_id = pbf.readString();
else if (tag === 4) obj.current_status = pbf.readVarint();
else if (tag === 5) obj.timestamp = pbf.readVarint();
else if (tag === 6) obj.congestion_level = pbf.readVarint();
else if (tag === 9) obj.occupancy_status = pbf.readVarint();
}
}
export enum VehicleStopStatus {
INCOMING_AT,
STOPPED_AT,
IN_TRANSIT_TO
}
export enum CongestionLevel {
UNKNOWN_CONGESTION_LEVEL,
RUNNING_SMOOTHLY,
STOP_AND_GO,
CONGESTION,
SEVERE_CONGESTION
}
export enum OccupancyStatus {
EMPTY,
MANY_SEATS_AVAILABLE,
FEW_SEATS_AVAILABLE,
STANDING_ROOM_ONLY,
CRUSHED_STANDING_ROOM_ONLY,
FULL,
NOT_ACCEPTING_PASSENGERS
}
// Alert ========================================
export interface Alert {
active_period?: TimeRange[];
informed_entity?: EntitySelector[];
cause?: AlertCause;
effect?: AlertEffect;
url?: TranslatedString | null;
header_text?: TranslatedString | null;
description_text?: TranslatedString | null;
}
export class AlertReader extends ProtobufMessageReader<Alert> {
readonly defaultMessage: Alert = {
active_period: [],
informed_entity: [],
cause: AlertCause.CONSTRUCTION,
effect: AlertEffect.STOP_MOVED,
url: null,
header_text: null,
description_text: null
};
protected readField(tag: number, obj?: Alert, pbf?: Pbf): void {
if (pbf === null || pbf === undefined) {
return;
}
if (obj === null || obj === undefined) {
obj = {};
}
if (obj.active_period === null || obj.active_period === undefined) {
obj.active_period = [];
}
if (obj.informed_entity === null || obj.informed_entity === undefined) {
obj.informed_entity = [];
}
if (tag === 1)
obj.active_period.push(
new TimeRangeReader().read(pbf, pbf.readVarint() + pbf.pos)
);
else if (tag === 5)
obj.informed_entity.push(
new EntitySelectorReader().read(pbf, pbf.readVarint() + pbf.pos)
);
else if (tag === 6) obj.cause = pbf.readVarint();
else if (tag === 7) obj.effect = pbf.readVarint();
else if (tag === 8)
obj.url = new TranslatedStringReader().read(
pbf,
pbf.readVarint() + pbf.pos
);
else if (tag === 10)
obj.header_text = new TranslatedStringReader().read(
pbf,
pbf.readVarint() + pbf.pos
);
else if (tag === 11)
obj.description_text = new TranslatedStringReader().read(
pbf,
pbf.readVarint() + pbf.pos
);
}
}
enum AlertCause {
UNKNOWN_CAUSE = 1,
OTHER_CAUSE,
TECHNICAL_PROBLEM,
STRIKE,
DEMONSTRATION,
ACCIDENT,
HOLIDAY,
WEATHER,
MAINTENANCE,
CONSTRUCTION,
POLICE_ACTIVITY,
MEDICAL_EMERGENCY
}
enum AlertEffect {
NO_SERVICE = 1,
REDUCED_SERVICE,
SIGNIFICANT_DELAYS,
ADDITIONAL_SERVICE,
MODIFIED_SERVICE,
OTHER_EFFECT,
UNKNOWN_EFFECT,
STOP_MOVED
}
// TimeRange ========================================
export interface TimeRange {
start?: number;
end?: number;
}
export class TimeRangeReader extends ProtobufMessageReader<TimeRange> {
readonly defaultMessage: TimeRange = {
start: 0,
end: 0
};
protected readField(tag: number, obj?: TimeRange, pbf?: Pbf): void {
if (pbf === null || pbf === undefined) {
return;
}
if (obj === null || obj === undefined) {
obj = {};
}
if (tag === 1) obj.start = pbf.readVarint();
else if (tag === 2) obj.end = pbf.readVarint();
}
}
// Position ========================================
export interface Position {
latitude?: number;
longitude?: number;
bearing?: number;
odometer?: number;
speed?: number;
}
export class PositionReader extends ProtobufMessageReader<Position> {
readonly defaultMessage: Position = {
latitude: 0,
longitude: 0,
bearing: 0,
odometer: 0,
speed: 0
};
protected readField(tag: number, obj?: Position, pbf?: Pbf): void {
if (pbf === null || pbf === undefined) {
return;
}
if (obj === null || obj === undefined) {
obj = {};
}
if (tag === 1) obj.latitude = pbf.readFloat();
else if (tag === 2) obj.longitude = pbf.readFloat();
else if (tag === 3) obj.bearing = pbf.readFloat();
else if (tag === 4) obj.odometer = pbf.readDouble();
else if (tag === 5) obj.speed = pbf.readFloat();
}
}
// TripDescriptor ========================================
export interface TripDescriptor {
trip_id?: string;
route_id?: string;
direction_id?: number;
start_time?: string;
start_date?: string;
schedule_relationship?: TripDescriptorScheduleRelationship;
}
export class TripDescriptorReader extends ProtobufMessageReader<
TripDescriptor
> {
readonly defaultMessage: TripDescriptor = {
trip_id: "",
route_id: "",
direction_id: 0,
start_time: "",
start_date: "",
schedule_relationship: TripDescriptorScheduleRelationship.SCHEDULED
};
protected readField(tag: number, obj?: TripDescriptor, pbf?: Pbf): void {
if (pbf === null || pbf === undefined) {
return;
}
if (obj === null || obj === undefined) {
obj = {};
}
if (tag === 1) obj.trip_id = pbf.readString();
else if (tag === 5) obj.route_id = pbf.readString();
else if (tag === 6) obj.direction_id = pbf.readVarint();
else if (tag === 2) obj.start_time = pbf.readString();
else if (tag === 3) obj.start_date = pbf.readString();
else if (tag === 4) obj.schedule_relationship = pbf.readVarint();
}
}
enum TripDescriptorScheduleRelationship {
SCHEDULED,
ADDED,
UNSCHEDULED,
CANCELED
}
// VehicleDescriptor ========================================
// const VehicleDescriptor = (self.VehicleDescriptor = {});
// VehicleDescriptor.read = function(pbf, end) {
// return pbf.readFields(
// VehicleDescriptor._readField,
// { id: "", label: "", license_plate: "" },
// end
// );
// };
// VehicleDescriptor._readField = function(tag, obj, pbf) {
// if (tag === 1) obj.id = pbf.readString();
// else if (tag === 2) obj.label = pbf.readString();
// else if (tag === 3) obj.license_plate = pbf.readString();
// };
export interface VehicleDescriptor {
id?: string;
label?: string;
license_plate?: string;
}
export class VehicleDescriptorReader extends ProtobufMessageReader<
VehicleDescriptor
> {
readonly defaultMessage: VehicleDescriptor = {
id: "",
label: "",
license_plate: ""
};
protected readField(tag: number, obj?: VehicleDescriptor, pbf?: Pbf): void {
if (pbf === null || pbf === undefined) {
return;
}
if (obj === null || obj === undefined) {
obj = {};
}
if (tag === 1) obj.id = pbf.readString();
else if (tag === 2) obj.label = pbf.readString();
else if (tag === 3) obj.license_plate = pbf.readString();
}
}
// EntitySelector ========================================
export interface EntitySelector {
agency_id?: string;
route_id?: string;
route_type?: number;
trip?: TripDescriptor | null;
stop_id?: string;
}
export class EntitySelectorReader extends ProtobufMessageReader<
EntitySelector
> {
readonly defaultMessage: EntitySelector = {
agency_id: "",
route_id: "",
route_type: 0,
trip: null,
stop_id: ""
};
protected readField(tag: number, obj?: EntitySelector, pbf?: Pbf): void {
if (pbf === null || pbf === undefined) {
return;
}
if (obj === null || obj === undefined) {
obj = {};
}
if (tag === 1) obj.agency_id = pbf.readString();
else if (tag === 2) obj.route_id = pbf.readString();
else if (tag === 3) obj.route_type = pbf.readVarint(true);
else if (tag === 4)
obj.trip = new TripDescriptorReader().read(
pbf,
pbf.readVarint() + pbf.pos
);
else if (tag === 5) obj.stop_id = pbf.readString();
}
}
// TranslatedString ========================================
export interface TranslatedString {
translation?: Translation[];
}
export class TranslatedStringReader extends ProtobufMessageReader<
TranslatedString
> {
readonly defaultMessage: TranslatedString = { translation: [] };
protected readField(tag: number, obj?: TranslatedString, pbf?: Pbf): void {
if (pbf === null || pbf === undefined) {
return;
}
if (obj === null || obj === undefined) {
obj = {};
}
if (obj.translation === null || obj.translation === undefined) {
obj.translation = [];
}
if (tag === 1)
obj.translation.push(
new TranslationReader().read(pbf, pbf.readVarint() + pbf.pos)
);
}
}
// TranslatedString.Translation ========================================
export interface Translation {
text?: string;
language?: string;
}
export class TranslationReader extends ProtobufMessageReader<Translation> {
readonly defaultMessage: Translation = { text: "", language: "" };
protected readField(tag: number, obj?: Translation, pbf?: Pbf): void {
if (pbf === null || pbf === undefined) {
return;
}
if (obj === null || obj === undefined) {
obj = {};
}
if (tag === 1) obj.text = pbf.readString();
else if (tag === 2) obj.language = pbf.readString();
}
} | the_stack |
* @module OrbitGT
*/
//package orbitgt.spatial.ecrs;
type int8 = number;
type int16 = number;
type int32 = number;
type float32 = number;
type float64 = number;
import { AList } from "../../system/collection/AList";
import { ASystem } from "../../system/runtime/ASystem";
import { Message } from "../../system/runtime/Message";
import { Numbers } from "../../system/runtime/Numbers";
import { Strings } from "../../system/runtime/Strings";
import { CRS } from "./CRS";
import { Datum } from "./Datum";
import { Ellipsoid } from "./Ellipsoid";
import { Operation } from "./Operation";
import { OperationMethod } from "./OperationMethod";
import { ParameterValue } from "./ParameterValue";
import { ParameterValueList } from "./ParameterValueList";
import { PrimeMeridian } from "./PrimeMeridian";
import { HotineObliqueMercator } from "./projection/HotineObliqueMercator";
import { KrovakObliqueConformalConic } from "./projection/KrovakObliqueConformalConic";
import { KrovakObliqueConformalConicEN } from "./projection/KrovakObliqueConformalConicEN";
import { LambertConical1SP } from "./projection/LambertConical1SP";
import { LambertConical2SP } from "./projection/LambertConical2SP";
import { Mercator1SP } from "./projection/Mercator1SP";
import { ObliqueMercator } from "./projection/ObliqueMercator";
import { ObliqueStereographic } from "./projection/ObliqueStereographic";
import { TransverseMercator } from "./projection/TransverseMercator";
import { Registry } from "./Registry";
import { PositionVector } from "./transformation/PositionVector";
import { Unit } from "./Unit";
import { WellKnownTextNode } from "./WellKnownTextNode";
/**
* Class WellKnownText parses Well-known Text Representations of Spatial Reference Systems.
*
* @version 1.0 December 2010
*/
/** @internal */
export class WellKnownText {
/** The name of this module */
private static readonly MODULE: string = "WellKnownText";
/** The dialect type in case of generic WKT */
public static readonly TYPE_GENERIC: string = "generic";
/** The conversion ratio from "arc-sec" to "radian" */
private static readonly _ARC_SEC_TO_RAD: float64 = (1.0 / 3600.0 * Math.PI / 180.0);
/** The counter for creating unique codes */
private static _CODES: int32 = 100000;
/**
* No instances.
*/
private constructor() { }
/**
* Unquote a name.
* @param name the name.
* @return the unquoted name.
*/
private static unquote(name: string): string {
name = Strings.trim(name);
ASystem.assert0(Strings.startsWith(name, "\""), "Name '" + name + "' does not start with a quote");
ASystem.assert0(Strings.endsWith(name, "\""), "Name '" + name + "' does not end with a quote");
return Strings.substring(name, 1, Strings.getLength(name) - 1);
}
/**
* Get a number.
* @param value the string value.
* @return the number.
*/
private static getInteger(value: string): int32 {
return Numbers.getInteger(value, 0);
}
/**
* Get a number.
* @param value the string value.
* @return the number.
*/
private static getDouble(value: string): float64 {
return Numbers.getDouble(value, 0.0);
}
/**
* Get a number.
* @param value the node value.
* @return the number.
*/
private static getNodeDouble(value: WellKnownTextNode): float64 {
if (value == null) return 0.0;
return Numbers.getDouble(value.getName(), 0.0);
}
/**
* Get an EPSG code for an element.
* @param authority the authority for the element.
* @param dialect the dialect of WKT to parse.
* @return the EPSG code (zero if not found).
*/
private static getEPSGCode(authority: WellKnownTextNode, dialect: string): int32 {
// example: AUTHORITY["EPSG","2320"]
if (authority == null) return 0;
let name: string = WellKnownText.unquote(authority.getArgument(0).getName());
let code: string = WellKnownText.unquote(authority.getArgument(1).getName());
if (Strings.equalsIgnoreCase(name, "EPSG") == false) return 0;
let epsgCode: int32 = Numbers.getInteger(code, 0);
return epsgCode; // Enabled on 06/06/2014
}
/**
* Parse a linear unit.
* @param node the well-known-text node.
* @param dialect the dialect of WKT to parse.
* @return the unit.
*/
private static parseLinearUnit(node: WellKnownTextNode, dialect: string): Unit {
/* Get the parameters */
let name: string = WellKnownText.unquote(node.getArgument(0).getName());
let conversionFactor: float64 = WellKnownText.getDouble(node.getArgument(1).getName());
let authority: WellKnownTextNode = node.getArgumentByName("AUTHORITY");
/* Do we have an EPGS code ? */
let epsgCode: int32 = WellKnownText.getEPSGCode(authority, dialect);
let code: int32 = (epsgCode == 0) ? WellKnownText._CODES++ : epsgCode;
/* Return the unit */
return new Unit(code, name, name/*abbreviation*/, "length", Unit.METER/*targetUnitCode*/, conversionFactor, 1.0);
}
/**
* Parse an angular unit.
* @param node the well-known-text node.
* @param dialect the dialect of WKT to parse.
* @return the unit.
*/
private static parseAngularUnit(node: WellKnownTextNode, dialect: string): Unit {
/* Get the parameters */
let name: string = WellKnownText.unquote(node.getArgument(0).getName());
let conversionFactor: float64 = WellKnownText.getDouble(node.getArgument(1).getName());
let authority: WellKnownTextNode = node.getArgumentByName("AUTHORITY");
/* Do we have an EPGS code ? */
let epsgCode: int32 = WellKnownText.getEPSGCode(authority, dialect);
let code: int32 = (epsgCode == 0) ? WellKnownText._CODES++ : epsgCode;
/* Return the unit */
return new Unit(code, name, name/*abbreviation*/, "angle", Unit.RADIAN/*targetUnitCode*/, conversionFactor, 1.0);
}
/**
* Parse a spheroid.
* @param crsCode the code of the CRS.
* @param node the well-known-text node.
* @param dialect the dialect of WKT to parse.
* @return the ellipsoid.
*/
private static parseSpheroid(crsCode: int32, node: WellKnownTextNode, dialect: string): Ellipsoid {
/* Get the parameters */
let name: string = WellKnownText.unquote(node.getArgument(0).getName());
let semiMajorAxis: float64 = WellKnownText.getDouble(node.getArgument(1).getName());
let invFlattening: float64 = WellKnownText.getDouble(node.getArgument(2).getName());
let authority: WellKnownTextNode = node.getArgumentByName("AUTHORITY");
/* Do we have an EPGS code ? */
let epsgCode: int32 = WellKnownText.getEPSGCode(authority, dialect);
let code: int32 = (epsgCode == 0) ? WellKnownText._CODES++ : epsgCode;
/* Return the ellipsoid */
return new Ellipsoid(code, name, Unit.METER, semiMajorAxis, invFlattening, 0.0);
}
/**
* Parse a prime-meridian.
* @param crsCode the code of the CRS.
* @param node the well-known-text node.
* @param dialect the dialect of WKT to parse.
* @return the prime-meridian.
*/
private static parsePrimeMeridian(crsCode: int32, node: WellKnownTextNode, dialect: string): PrimeMeridian {
/* Get the parameters */
let name: string = WellKnownText.unquote(node.getArgument(0).getName());
let longitude: float64 = WellKnownText.getDouble(node.getArgument(1).getName());
let authority: WellKnownTextNode = node.getArgumentByName("AUTHORITY");
/* Do we have an EPGS code ? */
let epsgCode: int32 = WellKnownText.getEPSGCode(authority, dialect);
let code: int32 = (epsgCode == 0) ? WellKnownText._CODES++ : epsgCode;
/* Return the prime-meridian */
return new PrimeMeridian(code, name, longitude/*lonFromGreenwich*/, Unit.DEGREE/*?*/);
}
/**
* Parse a to-wgs84 transform.
* @param node the well-known-text node (method position vector).
* @param dialect the dialect of WKT to parse.
* @return the transform.
*/
public static parseToWGS84(node: WellKnownTextNode, dialect: string): OperationMethod {
/* No transform ? */
if (node == null) return null;
/* Get the parameters */
let dx: float64 = WellKnownText.getNodeDouble(node.getArgument(0)); // meter
let dy: float64 = WellKnownText.getNodeDouble(node.getArgument(1));
let dz: float64 = WellKnownText.getNodeDouble(node.getArgument(2));
let rx: float64 = WellKnownText.getNodeDouble(node.getOptionalArgument(3)); // arc-second
let ry: float64 = WellKnownText.getNodeDouble(node.getOptionalArgument(4));
let rz: float64 = WellKnownText.getNodeDouble(node.getOptionalArgument(5));
let ppm: float64 = WellKnownText.getNodeDouble(node.getOptionalArgument(6)); // parts-per-million
/* Return the transform */
return PositionVector.create(dx, dy, dz, rx * WellKnownText._ARC_SEC_TO_RAD, ry * WellKnownText._ARC_SEC_TO_RAD, rz * WellKnownText._ARC_SEC_TO_RAD, ppm / 1.0e6);
}
/**
* Parse a datum.
* @param crsCode the code of the CRS.
* @param node the well-known-text node.
* @param primeMeridian the prime meridian.
* @param dialect the dialect of WKT to parse.
* @return the datum (with optional embedded datum transformation to WGS84).
*/
private static parseDatum(crsCode: int32, node: WellKnownTextNode, primeMeridian: PrimeMeridian, dialect: string): Datum {
/* Get the parameters */
let name: string = WellKnownText.unquote(node.getArgument(0).getName());
let spheroid: Ellipsoid = WellKnownText.parseSpheroid(crsCode, node.getArgumentByName("SPHEROID"), dialect);
let toWGS84: OperationMethod = WellKnownText.parseToWGS84(node.getArgumentByName("TOWGS84"), dialect);
if (toWGS84 == null) toWGS84 = PositionVector.create(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); // default (identity) transform added on 19/06/2013 to allow ViewTransform creation.
let authority: WellKnownTextNode = node.getArgumentByName("AUTHORITY");
/* Do we have an EPGS code ? */
let epsgCode: int32 = WellKnownText.getEPSGCode(authority, dialect);
let code: int32 = (epsgCode == 0) ? WellKnownText._CODES++ : epsgCode;
/* Return the datum */
let datum: Datum = new Datum(code, name, Datum.TYPE_GEODETIC, spheroid, primeMeridian);
datum.setToWGS84(toWGS84);
return datum;
}
/**
* Parse a projection method.
* @param projection the well-known-text projection node.
* @param parameters the well-known-text parameter nodes.
* @param dialect the dialect of WKT to parse.
* @return the projection method.
*/
private static parseProjectionMethod(projection: WellKnownTextNode, parameters: AList<WellKnownTextNode>, dialect: string): OperationMethod {
// See: http://www.remotesensing.org/geotiff/proj_list/
// for method names and parameter names and units
//
/* Get the projection name */
let projectionName: string = WellKnownText.unquote(projection.getArgument(0).getName());
/* Get the standard units */
let DEG: Unit = Registry.getUnit(Unit.DEGREE);
let METER: Unit = Registry.getUnit(Unit.METER);
let SCALE: Unit = Registry.getUnit(Unit.UNITY);
/* Convert to standard parameters */
let parameterList: ParameterValueList = new ParameterValueList();
for (let i: number = 0; i < parameters.size(); i++) {
/* Get the parameter name and value */
let parameter: WellKnownTextNode = parameters.get(i);
let parameterName: string = WellKnownText.unquote(parameter.getArgument(0).getName());
let parameterValue: float64 = WellKnownText.getDouble(parameter.getArgument(1).getName());
/* Hotine_Oblique_Mercator */
if (Strings.equalsIgnoreCase(projectionName, "Hotine_Oblique_Mercator")) {
if (Strings.equalsIgnoreCase(parameterName, "latitude_of_center")) parameterList.add(new ParameterValue(8811, parameterValue, DEG));
if (Strings.equalsIgnoreCase(parameterName, "longitude_of_center")) parameterList.add(new ParameterValue(8812, parameterValue, DEG));
if (Strings.equalsIgnoreCase(parameterName, "azimuth")) parameterList.add(new ParameterValue(8813, parameterValue, DEG));
if (Strings.equalsIgnoreCase(parameterName, "rectified_grid_angle")) parameterList.add(new ParameterValue(8814, parameterValue, DEG));
if (Strings.equalsIgnoreCase(parameterName, "scale_factor")) parameterList.add(new ParameterValue(8815, parameterValue, SCALE));
if (Strings.equalsIgnoreCase(parameterName, "false_easting")) parameterList.add(new ParameterValue(8806, parameterValue, METER));
if (Strings.equalsIgnoreCase(parameterName, "false_northing")) parameterList.add(new ParameterValue(8807, parameterValue, METER));
}
/* Krovak */
if (Strings.equalsIgnoreCase(projectionName, "Krovak") || Strings.equalsIgnoreCase(projectionName, "KrovakEN")) {
if (Strings.equalsIgnoreCase(parameterName, "latitude_of_center")) parameterList.add(new ParameterValue(8811, parameterValue, DEG));
if (Strings.equalsIgnoreCase(parameterName, "longitude_of_center")) parameterList.add(new ParameterValue(8833, parameterValue, DEG));
if (Strings.equalsIgnoreCase(parameterName, "azimuth")) parameterList.add(new ParameterValue(1036, parameterValue, DEG)); // changed from 8813 to 1036 on 31/08/2017
if (Strings.equalsIgnoreCase(parameterName, "pseudo_standard_parallel_1")) parameterList.add(new ParameterValue(8818, parameterValue, DEG));
if (Strings.equalsIgnoreCase(parameterName, "scale_factor")) parameterList.add(new ParameterValue(8819, parameterValue, SCALE));
if (Strings.equalsIgnoreCase(parameterName, "false_easting")) parameterList.add(new ParameterValue(8806, parameterValue, METER));
if (Strings.equalsIgnoreCase(parameterName, "false_northing")) parameterList.add(new ParameterValue(8807, parameterValue, METER));
}
/* Lambert_Conformal_Conic_1SP */
if (Strings.equalsIgnoreCase(projectionName, "Lambert_Conformal_Conic_1SP")) {
if (Strings.equalsIgnoreCase(parameterName, "latitude_of_origin")) parameterList.add(new ParameterValue(8801, parameterValue, DEG));
if (Strings.equalsIgnoreCase(parameterName, "central_meridian")) parameterList.add(new ParameterValue(8802, parameterValue, DEG));
if (Strings.equalsIgnoreCase(parameterName, "scale_factor")) parameterList.add(new ParameterValue(8805, parameterValue, SCALE));
if (Strings.equalsIgnoreCase(parameterName, "false_easting")) parameterList.add(new ParameterValue(8806, parameterValue, METER));
if (Strings.equalsIgnoreCase(parameterName, "false_northing")) parameterList.add(new ParameterValue(8807, parameterValue, METER));
}
/* Lambert_Conformal_Conic_2SP / Lambert_Conformal_Conic_2SP_Belgium / Lambert_Conformal_Conic */
if (Strings.equalsIgnoreCase(projectionName, "Lambert_Conformal_Conic_2SP") || Strings.equalsIgnoreCase(projectionName, "Lambert_Conformal_Conic_2SP_Belgium") || Strings.equalsIgnoreCase(projectionName, "Lambert_Conformal_Conic")) {
if (Strings.equalsIgnoreCase(parameterName, "latitude_of_origin")) parameterList.add(new ParameterValue(8821, parameterValue, DEG));
if (Strings.equalsIgnoreCase(parameterName, "central_meridian")) parameterList.add(new ParameterValue(8822, parameterValue, DEG));
if (Strings.equalsIgnoreCase(parameterName, "standard_parallel_1")) parameterList.add(new ParameterValue(8823, parameterValue, DEG));
if (Strings.equalsIgnoreCase(parameterName, "standard_parallel_2")) parameterList.add(new ParameterValue(8824, parameterValue, DEG));
if (Strings.equalsIgnoreCase(parameterName, "false_easting")) parameterList.add(new ParameterValue(8826, parameterValue, METER));
if (Strings.equalsIgnoreCase(parameterName, "false_northing")) parameterList.add(new ParameterValue(8827, parameterValue, METER));
// if (Strings.equalsIgnoreCase(parameterName,"scale_factor")) {if (parameterValue!=1.0) throw new IllegalArgumentException(MODULE+" : Invalid parameter '"+parameterName+"' with value "+parameterValue);}
}
/* Mercator_1SP */
if (Strings.equalsIgnoreCase(projectionName, "Mercator_1SP")) {
if (Strings.equalsIgnoreCase(parameterName, "latitude_of_origin")) parameterList.add(new ParameterValue(8801, parameterValue, DEG));
if (Strings.equalsIgnoreCase(parameterName, "central_meridian")) parameterList.add(new ParameterValue(8802, parameterValue, DEG));
if (Strings.equalsIgnoreCase(parameterName, "scale_factor")) parameterList.add(new ParameterValue(8805, parameterValue, SCALE));
if (Strings.equalsIgnoreCase(parameterName, "false_easting")) parameterList.add(new ParameterValue(8806, parameterValue, METER));
if (Strings.equalsIgnoreCase(parameterName, "false_northing")) parameterList.add(new ParameterValue(8807, parameterValue, METER));
}
/* Oblique_Mercator */
if (Strings.equalsIgnoreCase(projectionName, "Oblique_Mercator")) {
if (Strings.equalsIgnoreCase(parameterName, "latitude_of_center")) parameterList.add(new ParameterValue(8811, parameterValue, DEG));
if (Strings.equalsIgnoreCase(parameterName, "longitude_of_center")) parameterList.add(new ParameterValue(8812, parameterValue, DEG));
if (Strings.equalsIgnoreCase(parameterName, "azimuth")) parameterList.add(new ParameterValue(8813, parameterValue, DEG));
if (Strings.equalsIgnoreCase(parameterName, "rectified_grid_angle")) parameterList.add(new ParameterValue(8814, parameterValue, DEG));
if (Strings.equalsIgnoreCase(parameterName, "scale_factor")) parameterList.add(new ParameterValue(8815, parameterValue, SCALE));
if (Strings.equalsIgnoreCase(parameterName, "false_easting")) parameterList.add(new ParameterValue(8816, parameterValue, METER));
if (Strings.equalsIgnoreCase(parameterName, "false_northing")) parameterList.add(new ParameterValue(8817, parameterValue, METER));
}
/* Oblique_Stereographic /Transverse_Mercator */
if (Strings.equalsIgnoreCase(projectionName, "Oblique_Stereographic") || Strings.equalsIgnoreCase(projectionName, "Transverse_Mercator")) {
if (Strings.equalsIgnoreCase(parameterName, "latitude_of_origin")) parameterList.add(new ParameterValue(8801, parameterValue, DEG));
if (Strings.equalsIgnoreCase(parameterName, "central_meridian")) parameterList.add(new ParameterValue(8802, parameterValue, DEG));
if (Strings.equalsIgnoreCase(parameterName, "scale_factor")) parameterList.add(new ParameterValue(8805, parameterValue, SCALE));
if (Strings.equalsIgnoreCase(parameterName, "false_easting")) parameterList.add(new ParameterValue(8806, parameterValue, METER));
if (Strings.equalsIgnoreCase(parameterName, "false_northing")) parameterList.add(new ParameterValue(8807, parameterValue, METER));
}
}
/* Create the right method */
if (Strings.equalsIgnoreCase(projectionName, "Hotine_Oblique_Mercator")) return new HotineObliqueMercator(parameterList);
if (Strings.equalsIgnoreCase(projectionName, "Krovak")) return new KrovakObliqueConformalConic(parameterList);
if (Strings.equalsIgnoreCase(projectionName, "KrovakEN")) return new KrovakObliqueConformalConicEN(parameterList);
if (Strings.equalsIgnoreCase(projectionName, "Lambert_Conformal_Conic_1SP")) return new LambertConical1SP(parameterList);
if (Strings.equalsIgnoreCase(projectionName, "Lambert_Conformal_Conic_2SP")) return new LambertConical2SP(parameterList);
if (Strings.equalsIgnoreCase(projectionName, "Lambert_Conformal_Conic")) return new LambertConical2SP(parameterList);
if (Strings.equalsIgnoreCase(projectionName, "Mercator_1SP")) return new Mercator1SP(parameterList);
if (Strings.equalsIgnoreCase(projectionName, "Oblique_Mercator")) return new ObliqueMercator(parameterList);
if (Strings.equalsIgnoreCase(projectionName, "Oblique_Stereographic")) return new ObliqueStereographic(parameterList);
if (Strings.equalsIgnoreCase(projectionName, "Transverse_Mercator")) return new TransverseMercator(parameterList);
ASystem.assert0(false, "Unknown projection type '" + projectionName + "'");
return null;
}
/**
* Parse a geocentric CRS.
* @param crsCode the code of the CRS.
* @param node the well-known-text node.
* @param dialect the dialect of WKT to parse.
* @return the CRS.
*/
private static parseGeocentric(crsCode: int32, node: WellKnownTextNode, dialect: string): CRS {
/* Get the parameters */
let name: string = WellKnownText.unquote(node.getArgument(0).getName());
let primeMeridian: PrimeMeridian = WellKnownText.parsePrimeMeridian(crsCode, node.getArgumentByName("PRIMEM"), dialect);
let datum: Datum = WellKnownText.parseDatum(crsCode, node.getArgumentByName("DATUM"), primeMeridian, dialect);
let toWGS84m: OperationMethod = datum.getToWGS84();
let toWGS84s: AList<Operation> = new AList<Operation>();
let linearUnit: Unit = WellKnownText.parseLinearUnit(node.getArgumentByName("UNIT"), dialect);
let axis: AList<WellKnownTextNode> = node.getArgumentsByName("AXIS");
let authority: WellKnownTextNode = node.getArgumentByName("AUTHORITY");
/* Do we have an EPGS code ? */
let epsgCode: int32 = WellKnownText.getEPSGCode(authority, dialect);
let code: int32 = (epsgCode == 0) ? crsCode : epsgCode;
/* Return the CRS */
if (toWGS84m != null) toWGS84s.add(new Operation(0/*code*/, ""/*name*/, Operation.TRANSFORMATION, code, CRS.WGS84_2D_CRS_CODE, 0/*area*/, toWGS84m));
return new CRS(code, name, 0/*area*/, CRS.GEOCENTRIC, 0/*csCode*/, datum, null/*baseCRS*/, null/*projection*/, toWGS84s);
}
/**
* Parse a geographic CRS.
* @param crsCode the code of the CRS.
* @param node the well-known-text node.
* @param dialect the dialect of WKT to parse.
* @return the CRS.
*/
private static parseGeographic(crsCode: int32, node: WellKnownTextNode, dialect: string): CRS {
/* Get the parameters */
let name: string = WellKnownText.unquote(node.getArgument(0).getName());
let primeMeridian: PrimeMeridian = WellKnownText.parsePrimeMeridian(crsCode, node.getArgumentByName("PRIMEM"), dialect);
let datum: Datum = WellKnownText.parseDatum(crsCode, node.getArgumentByName("DATUM"), primeMeridian, dialect);
let toWGS84m: OperationMethod = datum.getToWGS84();
let toWGS84s: AList<Operation> = new AList<Operation>();
let angularUnit: Unit = WellKnownText.parseAngularUnit(node.getArgumentByName("UNIT"), dialect);
let axis: AList<WellKnownTextNode> = node.getArgumentsByName("AXIS");
let authority: WellKnownTextNode = node.getArgumentByName("AUTHORITY");
/* Do we have an EPGS code ? */
let epsgCode: int32 = WellKnownText.getEPSGCode(authority, dialect);
let code: int32 = (epsgCode == 0) ? crsCode : epsgCode;
/* Return the CRS */
if (toWGS84m != null) toWGS84s.add(new Operation(0/*code*/, ""/*name*/, Operation.TRANSFORMATION, code, CRS.WGS84_2D_CRS_CODE, 0/*area*/, toWGS84m));
return new CRS(code, name, 0/*area*/, CRS.GEOGRAPHIC_2D, 0/*csCode*/, datum, null/*baseCRS*/, null/*projection*/, toWGS84s);
}
/**
* Parse a projected CRS.
* @param crsCode the code of the CRS.
* @param node the well-known-text node.
* @param dialect the dialect of WKT to parse.
* @return the CRS.
*/
private static parseProjection(crsCode: int32, node: WellKnownTextNode, dialect: string): CRS {
/* Get the parameters */
let name: string = WellKnownText.unquote(node.getArgument(0).getName());
let baseCRS: CRS = WellKnownText.parseGeographic(-crsCode, node.getArgumentByName("GEOGCS"), dialect);
let projection: WellKnownTextNode = node.getArgumentByName("PROJECTION");
let parameters: AList<WellKnownTextNode> = node.getArgumentsByName("PARAMETER");
let projectionMethod: OperationMethod = WellKnownText.parseProjectionMethod(projection, parameters, dialect);
let linearUnit: Unit = WellKnownText.parseLinearUnit(node.getArgumentByName("UNIT"), dialect);
let axis: AList<WellKnownTextNode> = node.getArgumentsByName("AXIS");
let authority: WellKnownTextNode = node.getArgumentByName("AUTHORITY");
/* Do we have an EPGS code ? */
let epsgCode: int32 = WellKnownText.getEPSGCode(authority, dialect);
let code: int32 = (epsgCode == 0) ? crsCode : epsgCode;
/* Return the CRS */
let projectionOperation: Operation = new Operation(0/*code*/, ""/*name*/, Operation.CONVERSION, code, baseCRS.getCode(), 0/*area*/, projectionMethod);
return new CRS(code, name, 0/*area*/, CRS.PROJECTED, 0/*csCode*/, null/*datum*/, baseCRS, projectionOperation, null/*toWGS84*/);
}
/**
* Parse a vertical CRS.
* @param crsCode the code of the CRS.
* @param node the well-known-text node.
* @param dialect the dialect of WKT to parse.
* @return the CRS.
*/
private static parseVertical(crsCode: int32, node: WellKnownTextNode, dialect: string): CRS {
/* Get the parameters */
let name: string = WellKnownText.unquote(node.getArgument(0).getName());
let authority: WellKnownTextNode = node.getArgumentByName("AUTHORITY");
/* Do we have an EPGS code ? */
let epsgCode: int32 = WellKnownText.getEPSGCode(authority, dialect);
let code: int32 = (epsgCode == 0) ? crsCode : epsgCode;
/* Create the datum */
let datum: Datum = new Datum(code, name, Datum.TYPE_VERTICAL, null/*spheroid*/, null/*primeMeridian*/);
/* Return the CRS */
return new CRS(code, name, 0/*area*/, CRS.VERTICAL, 6499/*csCode*/, datum, null/*baseCRS*/, null/*projectionOperation*/, null/*toWGS84*/);
}
/**
* Parse a CRS well-known-text.
* @param crsCode the code of the CRS.
* @param text the well-known-text.
* @param dialect the dialect of WKT to parse.
* @return the CRS (null if unable to parse).
*/
public static parseSpatialReferenceSystem(crsCode: int32, text: string, dialect: string): CRS {
let node: WellKnownTextNode = WellKnownTextNode.parse(text);
if (Strings.equalsIgnoreCase(node.getName(), "GEOCCS")) return WellKnownText.parseGeocentric(crsCode, node, dialect);
if (Strings.equalsIgnoreCase(node.getName(), "GEOGCS")) return WellKnownText.parseGeographic(crsCode, node, dialect);
if (Strings.equalsIgnoreCase(node.getName(), "PROJCS")) return WellKnownText.parseProjection(crsCode, node, dialect);
if (Strings.equalsIgnoreCase(node.getName(), "VERTCS")) return WellKnownText.parseVertical(crsCode, node, dialect);
Message.printWarning(WellKnownText.MODULE, "Invalid spatial reference system WKT '" + text + "'");
return null;
}
} | the_stack |
import { IconEvent } from '@defencedigital/icon-library'
import { isValid } from 'date-fns'
import React, { useState } from 'react'
import { Placement } from '@popperjs/core'
import { DayModifiers, DayPickerProps } from 'react-day-picker'
import { ComponentWithClass } from '../../common/ComponentWithClass'
import { DATE_FORMAT } from '../../constants'
import { DATE_VALIDITY, WEEKDAY_TITLES } from './constants'
import { formatDatesForInput } from './formatDatesForInput'
import { hasClass } from '../../helpers'
import { InlineButton } from '../InlineButtons/InlineButton'
import { InputValidationProps } from '../../common/InputValidationProps'
import { StyledLabel } from '../TextInputE/partials/StyledLabel'
import { StyledDatePickerEInput } from './partials/StyledDatePickerEInput'
import { StyledDayPicker } from './partials/StyledDayPicker'
import { StyledFloatingBox } from './partials/StyledFloatingBox'
import { StyledInlineButtons } from '../InlineButtons/partials/StyledInlineButtons'
import { StyledInput } from '../TextInputE/partials/StyledInput'
import { StyledInputWrapper } from './partials/StyledInputWrapper'
import { StyledOuterWrapper } from './partials/StyledOuterWrapper'
import { useCloseOnEscape } from './useCloseOnEscape'
import { useDatePickerEOpenClose } from './useDatePickerEOpenClose'
import { useExternalId } from '../../hooks/useExternalId'
import { useFocus } from '../../hooks/useFocus'
import { useInput } from './useInput'
import { useRangeHoverOrFocusDate } from './useRangeHoverOrFocusDate'
import { useSelection } from './useSelection'
import { useStatefulRef } from '../../hooks/useStatefulRef'
declare module 'react-day-picker' {
// eslint-disable-next-line no-shadow
interface DayPickerProps {
// This prop is currently missing from the react-day-picker types
onDayFocus?: (
day: Date,
modifiers: DayModifiers,
e: React.FocusEvent<HTMLDivElement>
) => void
}
}
export type DatePickerEDateValidityType =
| typeof DATE_VALIDITY.VALID
| typeof DATE_VALIDITY.INVALID
| typeof DATE_VALIDITY.DISABLED
export interface DatePickerEOnChangeData {
startDate: Date | null
startDateValidity: DatePickerEDateValidityType | null
endDate: Date | null
endDateValidity: DatePickerEDateValidityType | null
}
export interface DatePickerEProps
extends ComponentWithClass,
InputValidationProps {
/**
* End date of the picker (only relevant in range mode).
*/
endDate?: Date
/**
* Custom date format (e.g. `yyyy/MM/dd`).
*/
format?: string
/**
* Optional unique ID to apply to the component.
*/
id?: string
/**
* Toggles whether the component is disabled or not (preventing user interaction).
*/
isDisabled?: boolean
/**
* Toggles whether the component is a range variant (allowing selection of start and end dates).
*/
isRange?: boolean
/**
* Optional text label to display within the picker input.
*/
label?: string
/**
* Optional HTML `name` attribute to apply to the component.
*/
name?: string
/**
* Optional handler to be invoked when the blur event is emitted.
*/
onBlur?: (event: React.FormEvent) => void
/**
* Optional handler to be invoked when the value of the component changes.
*
* Note: If an invalid date is typed, `data.startDate` will be set to an
* invalid date object and the `data.startDateValidity` will be set to
* `"invalid"`. (If you're using `yup` for validation, you may wish to
* use the `.typeError()` chainer to display an appropriate error message.)
*
* If a date that is disabled using the `disabledDays` prop is typed,
* `data.startDate` will be populated and `data.startDateValidity` will
* be set to `"disabled"`. You should check for this and ensure an
* appropriate error message is displayed.
*/
onChange?: (data: DatePickerEOnChangeData) => void
/**
* Optional handler to be invoked when the calendar is focussed.
*/
onCalendarFocus?: (e: React.SyntheticEvent) => void
/**
* Start date of the picker (the first date selected by end user).
*/
startDate?: Date
/**
* Toggles whether or not the picker is open.
*/
isOpen?: boolean
/**
* An array of dates to disabled within the picker, preventing them from
* being selected in the date picker calendar.
*
* Note that these dates can still be manually typed in. You should still
* check for them in your validation logic and display an appropriate
* error message if they are received. See the `onChange` prop for more
* information.
*/
disabledDays?: DayPickerProps['disabledDays']
/**
* Optional month from which to display the picker calendar on first render.
*/
initialMonth?: DayPickerProps['initialMonth']
/**
* Position to display the picker relative to the input.
* NOTE: This is now calculated automatically by default based on available screen real-estate.
*/
placement?: Placement
/**
* Not used. Use `startDate` and `endDate` instead.
*/
value?: never
}
const replaceInvalidDate = (date: Date) => (isValid(date) ? date : undefined)
export const DatePickerE: React.FC<DatePickerEProps> = ({
className,
endDate,
format: datePickerFormat = DATE_FORMAT.SHORT,
id: externalId,
isDisabled,
isInvalid,
isRange,
label = 'Date',
onChange,
onCalendarFocus,
startDate,
isOpen,
disabledDays,
initialMonth,
placement = 'bottom-start',
onBlur,
// Formik can pass value – drop it to stop it being forwarded to the input
value: _,
...rest
}) => {
const id = useExternalId(externalId)
const titleId = `datepicker-title-${useExternalId()}`
const contentId = `datepicker-contentId-${useExternalId()}`
const { hasFocus, onLocalBlur, onLocalFocus } = useFocus()
const {
floatingBoxChildrenRef,
handleOnClose,
handleOnOpen,
inputButtonRef,
open,
} = useDatePickerEOpenClose(isOpen)
const { handleDayPickerKeyDown } = useCloseOnEscape(handleOnClose)
const [inputValue, setInputValue] = useState<string>(
formatDatesForInput(startDate, endDate, datePickerFormat)
)
const { state, handleDayClick } = useSelection(
startDate,
endDate,
isRange,
datePickerFormat,
disabledDays,
setInputValue,
onChange
)
const [hasError, setHasError] = useState<boolean>(
isInvalid || hasClass(className, 'is-invalid')
)
const [floatingBoxTarget, setFloatingBoxTarget] = useStatefulRef()
const {
rangeHoverOrFocusDate,
handleDayFocus,
handleDayMouseEnter,
handleDayMouseLeave,
} = useRangeHoverOrFocusDate(isRange)
const { from, to } = state
const { handleKeyDown, handleInputBlur, handleInputChange } = useInput(
datePickerFormat,
isRange,
handleDayClick,
state,
setHasError,
setInputValue
)
const modifiers = {
start: replaceInvalidDate(from),
end: replaceInvalidDate(to),
}
const hasContent = Boolean(from)
const placeholder = !isRange ? datePickerFormat.toLowerCase() : null
return (
<>
<StyledDatePickerEInput
className={className}
data-testid="datepicker-input-wrapper"
$isDisabled={isDisabled}
ref={setFloatingBoxTarget}
>
<StyledOuterWrapper
data-testid="datepicker-outer-wrapper"
$hasFocus={hasFocus}
$isInvalid={hasError}
$isDisabled={isDisabled}
>
<StyledInputWrapper $isRange={isRange}>
<StyledLabel
id={titleId}
$hasFocus={hasFocus && !isRange}
$hasContent={hasContent}
htmlFor={id}
data-testid="datepicker-label"
>
{label}
{placeholder && ` (${placeholder})`}
</StyledLabel>
<StyledInput
$hasLabel={Boolean(label)}
aria-label="Choose date"
data-testid="datepicker-input"
id={id}
type="text"
disabled={isDisabled}
readOnly={isRange}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
onBlur={(e) => {
onLocalBlur(e)
handleInputBlur()
if (onBlur) {
onBlur(e)
}
}}
onFocus={() => {
onLocalFocus()
if (isRange) {
handleOnOpen()
}
}}
placeholder={placeholder}
value={inputValue}
{...rest}
/>
</StyledInputWrapper>
<StyledInlineButtons>
<InlineButton
aria-expanded={!!open}
aria-label={`${open ? 'Hide' : 'Show'} day picker`}
aria-owns={contentId}
data-testid="datepicker-input-button"
isDisabled={isDisabled}
onClick={open ? handleOnClose : handleOnOpen}
ref={inputButtonRef}
>
<IconEvent size={18} />
</InlineButton>
</StyledInlineButtons>
</StyledOuterWrapper>
</StyledDatePickerEInput>
<StyledFloatingBox
isVisible={open}
placement={placement}
targetElement={floatingBoxTarget}
role="dialog"
aria-modal
aria-labelledby={titleId}
aria-live="polite"
>
<div ref={floatingBoxChildrenRef}>
<StyledDayPicker
firstDayOfWeek={1}
weekdaysShort={WEEKDAY_TITLES}
selectedDays={[
{
from: replaceInvalidDate(from),
to: replaceInvalidDate(to) || rangeHoverOrFocusDate,
},
]}
modifiers={modifiers}
onDayClick={(day, { disabled }) => {
if (disabled) {
return
}
setHasError(false)
const newState = handleDayClick(day)
setInputValue(
formatDatesForInput(
newState.from,
newState.to,
datePickerFormat
)
)
if (newState.to || !isRange) {
setTimeout(() => handleOnClose())
}
}}
onKeyDown={handleDayPickerKeyDown}
initialMonth={replaceInvalidDate(from) || initialMonth}
disabledDays={disabledDays}
$isRange={isRange}
$isVisible={open}
onFocus={onCalendarFocus}
onDayMouseEnter={handleDayMouseEnter}
onDayMouseLeave={handleDayMouseLeave}
onDayFocus={handleDayFocus}
/>
</div>
</StyledFloatingBox>
</>
)
}
DatePickerE.displayName = 'DatePickerE' | the_stack |
import test from 'ava';
import { IocContext, NotfoundTypeError } from '../lib/IocContext';
import { inject, classInfo, injectable, imports, postConstruct, aspect } from '../lib';
import { FunctionContext } from '../lib/class/metadata';
import * as co from 'co';
import { preDestroy } from '../lib/decorator/preDestroy';
test('decorator, custom IocContext.', t => {
const context = new IocContext();
@injectable()
class NRService {}
@injectable()
class LITestService {
@inject()
public testService: NRService;
}
const test = context.get(LITestService);
t.true(test.testService instanceof NRService);
});
test('decorator, function IocContext.', t => {
const context = new IocContext();
@injectable()
class NRService {}
@injectable()
class LITestService {
@inject()
public testService: NRService;
}
const test = context.get(LITestService);
t.true(test.testService instanceof NRService);
});
test('decorator, default IocContext.', t => {
@injectable()
class NRService {}
@injectable()
class LITestService {
@inject()
public testService: NRService;
}
const test = IocContext.DefaultInstance.get(LITestService);
t.true(test.testService instanceof NRService);
});
// default context, register decorators
const context = new IocContext();
test('inject decorator.', t => {
@injectable()
class DTestService {}
@injectable()
class ITestService {
@inject({ lazy: false })
public testService: DTestService;
@inject({ type: DTestService, lazy: false })
public testService2: DTestService;
}
const test = context.get(ITestService);
t.true(test.testService instanceof DTestService);
t.true(test.testService2 instanceof DTestService);
});
test('inject decorator, no data.', t => {
class NRService {}
@injectable()
class ITestService {
@inject({ lazy: false, optional: true })
public testService: NRService;
}
t.true(!context.get(ITestService).testService);
});
test('inject decorator, must have instance.', t => {
class NRService {}
@injectable()
class ITestService {
@inject({ lazy: false })
public testService: NRService;
}
t.throws(() => !context.get(ITestService).testService, {
instanceOf: NotfoundTypeError,
});
});
test('lazyInject decorator.', t => {
@injectable()
class DTestService {}
@injectable()
class LITestService {
@inject()
public testService: DTestService;
@inject({ type: DTestService })
public testService2: DTestService;
}
const test = context.get(LITestService);
t.true(test.testService instanceof DTestService);
t.true(test.testService2 instanceof DTestService);
});
test('lazyInject decorator, no data.', t => {
class NRService {}
@injectable()
class LITestService {
@inject({ optional: true })
public testService: NRService;
}
const test = context.get<LITestService>(LITestService);
t.true(!test.testService);
});
test('lazyInject decorator, no data, then have.', t => {
class NRService {}
@injectable()
class LITestService {
@inject({ optional: true })
public testService: NRService;
}
const test = context.get<LITestService>(LITestService);
t.true(!test.testService);
context.register(NRService);
t.true(test.testService instanceof NRService);
});
test('lazyInject decorator, always option true.', t => {
@injectable()
class NRService {}
@injectable()
class LITestService {
@inject({ always: true })
public testService: NRService;
}
const test = context.get(LITestService);
t.true(test.testService instanceof NRService);
t.true(test.testService === test.testService);
const old = test.testService;
context.remove(NRService);
t.true(test.testService !== old);
});
test('lazyInject decorator, always option false.', t => {
@injectable()
class NRService {}
@injectable()
class LITestService {
@inject({ always: false })
public testService: NRService;
}
const test = context.get<LITestService>(LITestService);
t.true(test.testService instanceof NRService);
context.remove(NRService);
t.true(test.testService instanceof NRService);
});
test('lazyInject decorator, imports.', t => {
abstract class A {}
@classInfo()
class B extends A {}
@classInfo()
class C extends A {}
@injectable()
class LITestService {
@imports({ type: A })
public testService: A[];
@imports({ type: A })
public testServiceAgain: A[];
}
// t.throws(() => {
// class LITestService {
// @imports({ type: A })
// public testService: A; // need Array
// }
// });
const test = context.get(LITestService);
t.true(test.testService.length === 2);
t.true(test.testService[0] instanceof B);
t.true(test.testService[1] instanceof C);
t.true(test.testServiceAgain.length === 2);
t.true(test.testService === test.testServiceAgain);
t.deepEqual(test.testService, test.testServiceAgain);
});
test('lazyInject decorator, defaultValue, auto optional.', t => {
class NRService {}
const defaultValue = new NRService();
class LITestService {
@inject()
public testService: NRService = defaultValue;
}
const context = new IocContext();
context.register(LITestService);
const test = context.get<LITestService>(LITestService);
t.true(test.testService === defaultValue);
const value2 = new NRService();
test.testService = value2;
t.true(test.testService === value2);
});
test('inject decorator, setter.', t => {
class NRService {}
class LITestService {
@inject({ lazy: false })
public testService: NRService;
}
const context = new IocContext();
context.register(NRService);
context.register(LITestService);
const test = context.get<LITestService>(LITestService);
t.true(!!test.testService);
const oldService = test.testService;
const newService = new NRService();
test.testService = newService;
t.true(test.testService !== oldService);
t.true(test.testService === newService);
});
test('lazyInject decorator, setter.', t => {
class NRService {}
class LITestService {
@inject()
public testService: NRService;
}
const context = new IocContext();
context.register(NRService);
context.register(LITestService);
const test = context.get<LITestService>(LITestService);
t.true(!!test.testService);
const oldService = test.testService;
const newService = new NRService();
test.testService = newService;
t.true(test.testService !== oldService);
t.true(test.testService === newService);
});
test('multi level inject.', t => {
class A {
echo() {
return 'a';
}
}
class B {
@inject()
a: A;
}
class C {
@inject()
b: B;
}
const ctx = new IocContext({ autoRegisterSelf: true });
const c = ctx.get(C);
t.is(c.b.a.echo(), 'a');
});
test('postConstruct.', t => {
@injectable()
class A {
@postConstruct()
init() {
t.pass();
}
}
const ioc = new IocContext();
ioc.get(A);
});
test('postConstruct, after inject.', t => {
@injectable()
class B {
id = 1;
}
@injectable()
class A {
@inject()
b: B;
@postConstruct()
init() {
t.true(this.b.id === 1);
}
}
const ioc = new IocContext();
ioc.get(A);
});
test('postConstruct, without get.', t => {
let count = 0;
@injectable()
class A {
constructor() {
count++;
}
@postConstruct()
init() {
count++;
}
}
const a = new A();
const ioc = new IocContext();
ioc.inject(a);
t.true(count === 2);
});
test('postConstruct, parent and subClass.', t => {
let count = 0;
class A {
@postConstruct()
init() {
t.fail();
}
}
@injectable()
class B extends A {
@postConstruct()
init() {
count++;
}
}
const ioc = new IocContext();
ioc.get(B);
t.is(count, 1);
@injectable()
class C extends B {
@postConstruct()
init2() {
count++;
}
}
ioc.get(C);
t.is(count, 3);
});
test('class inject use interface.', t => {
abstract class AInterface {}
const BInterface = Symbol('BInterface');
interface BInterface {}
@classInfo({ implements: [AInterface] })
@injectable()
class A implements AInterface {}
@injectable()
@classInfo({ implements: [BInterface] })
class B implements BInterface {}
const ioc = new IocContext();
t.true(ioc.get(AInterface) instanceof A);
t.true(ioc.get(BInterface) instanceof B);
});
test('throw error when inject Object/undefined.', t => {
interface AInterface {}
const AInterface = Symbol('AInterface');
t.throws(() => {
class Test {
@inject()
a: AInterface;
}
});
});
test('aspect', t => {
let aspectFnCtx: FunctionContext;
function aAspect(): MethodDecorator {
return (target, key, desc) => {
return aspect<{ before: string }>({
before: ctx => {
ctx.data.before = 'before';
},
after: ctx => {
t.deepEqual(ctx.data.before, 'before');
aspectFnCtx = ctx;
},
})(target, key, desc);
};
}
@injectable()
class A {
@aspect()
a() {
return 'oka';
}
@aAspect()
b(x: string) {
return 'okb' + x;
}
}
const context = new IocContext();
const a = context.get(A);
t.deepEqual(a.a(), 'oka');
t.deepEqual(a.b('!'), 'okb!');
t.true(aspectFnCtx.ioc instanceof IocContext);
t.true(aspectFnCtx.inst instanceof A);
t.deepEqual(aspectFnCtx.functionName, 'b');
t.deepEqual(aspectFnCtx.data, { before: 'before' });
t.deepEqual(aspectFnCtx.args, ['!']);
t.deepEqual(aspectFnCtx.ret, 'okb!');
});
test('aspect, promise', async t => {
let aspectFnCtx: FunctionContext;
function aAspect(): MethodDecorator {
return (target, key, desc) => {
return aspect<{ before: string }>({
before: ctx => {
ctx.data.before = 'before';
},
after: ctx => {
t.deepEqual(ctx.data.before, 'before');
aspectFnCtx = ctx;
},
})(target, key, desc);
};
}
@injectable()
class A {
@aspect()
async a() {
return 'oka';
}
@aAspect()
async b(x: string) {
return 'okb' + x;
}
}
const context = new IocContext();
const a = context.get(A);
t.deepEqual(await a.a(), 'oka');
t.deepEqual(await a.b('!'), 'okb!');
t.true(aspectFnCtx.ioc instanceof IocContext);
t.true(aspectFnCtx.inst instanceof A);
t.deepEqual(aspectFnCtx.functionName, 'b');
t.deepEqual(aspectFnCtx.data, { before: 'before' });
t.deepEqual(aspectFnCtx.args, ['!']);
t.deepEqual(aspectFnCtx.ret, 'okb!');
});
test('aspect, generator', async t => {
let aspectFnCtx: FunctionContext;
function aAspect(): MethodDecorator {
return (target, key, desc) => {
return aspect<{ before: string }>({
before: ctx => {
ctx.data.before = 'before';
},
after: ctx => {
t.deepEqual(ctx.data.before, 'before');
aspectFnCtx = ctx;
},
})(target, key, desc);
};
}
@injectable()
class A {
@aspect()
*a() {
return 'oka';
}
@aAspect()
*b(x: string) {
return 'okb' + x;
}
}
const context = new IocContext();
const a = context.get(A);
await co(function* () {
t.deepEqual(yield a.a(), 'oka');
t.deepEqual(yield a.b('!'), 'okb!');
t.true(aspectFnCtx.ioc instanceof IocContext);
t.true(aspectFnCtx.inst instanceof A);
t.deepEqual(aspectFnCtx.functionName, 'b');
t.deepEqual(aspectFnCtx.data, { before: 'before' });
t.deepEqual(aspectFnCtx.args, ['!']);
t.deepEqual(aspectFnCtx.ret, 'okb!');
});
});
test('aspect, error', t => {
let aspectFnCtx: FunctionContext;
function aAspect(): MethodDecorator {
return (target, key, desc) => {
return aspect({
error: ctx => {
aspectFnCtx = ctx;
},
})(target, key, desc);
};
}
function ignoreErr(): MethodDecorator {
return (target, key, desc) => {
return aspect({
error: ctx => {
ctx.err = undefined;
},
})(target, key, desc);
};
}
@injectable()
class A {
@aAspect()
a() {
throw new Error();
}
@ignoreErr()
b() {
throw new Error();
}
}
const context = new IocContext();
const a = context.get(A);
t.throws(() => a.a());
t.true(aspectFnCtx.err instanceof Error);
t.notThrows(() => a.b());
});
test('aspect, error, promise', async t => {
let aspectFnCtx: FunctionContext;
function aAspect(): MethodDecorator {
return (target, key, desc) => {
return aspect({
error: ctx => {
aspectFnCtx = ctx;
},
})(target, key, desc);
};
}
function ignoreErr(): MethodDecorator {
return (target, key, desc) => {
return aspect({
error: ctx => {
ctx.err = undefined;
},
})(target, key, desc);
};
}
@injectable()
class A {
@aAspect()
async a() {
throw new Error();
}
@ignoreErr()
async b() {
throw new Error();
}
}
const context = new IocContext();
const a = context.get(A);
await t.throwsAsync(() => a.a());
t.true(aspectFnCtx.err instanceof Error);
await t.notThrowsAsync(() => a.b());
});
test('aspect, error, generator', async t => {
let aspectFnCtx: FunctionContext;
function aAspect(): MethodDecorator {
return (target, key, desc) => {
return aspect({
error: ctx => {
aspectFnCtx = ctx;
},
})(target, key, desc);
};
}
function ignoreErr(): MethodDecorator {
return (target, key, desc) => {
return aspect({
error: ctx => {
ctx.err = undefined;
},
})(target, key, desc);
};
}
@injectable()
class A {
@aAspect()
*a() {
throw new Error();
}
@ignoreErr()
*b() {
throw new Error();
}
}
const context = new IocContext();
const a = context.get(A);
await t.throwsAsync(() =>
co(function* () {
return yield a.a();
})
);
t.true(aspectFnCtx.err instanceof Error);
await t.notThrowsAsync(() =>
co(function* () {
return yield a.b();
})
);
});
test('aspect, skipRunning', async t => {
function aAspect(): MethodDecorator {
return (target, key, desc) => {
return aspect<{ before: string }>({
before: ctx => {
if (ctx.args[0] === 'xxx') {
ctx.ret = 'yyy';
ctx.skipRunning = true;
}
},
})(target, key, desc);
};
}
@injectable()
class A {
@aAspect()
a(str: string) {
return str;
}
@aAspect()
*b(str: string) {
return str;
}
}
const context = new IocContext();
const a = context.get(A);
t.deepEqual(a.a('oka'), 'oka');
t.deepEqual(a.a('xxx'), 'yyy');
t.deepEqual(
await co(function* () {
return yield a.b('oka');
}),
'oka' as any
);
t.deepEqual(
await co(function* () {
return yield a.b('xxx');
}),
'yyy' as any
);
});
test('preDestroy.', t => {
let count = 0;
@injectable()
class A {
@preDestroy()
destroy() {
count++;
}
}
const ioc = new IocContext();
ioc.register(A);
ioc.clear();
t.is(count, 0);
t.true(ioc.get(A) instanceof A);
ioc.remove(A);
t.is(count, 1);
t.false(ioc.has(A));
t.true(ioc.get(A) instanceof A);
ioc.clear();
t.is(count, 2);
t.false(ioc.has(A));
});
test('preDestroy, parent and subClass.', t => {
let count = 0;
class A {
@preDestroy()
destroy() {
t.fail();
}
}
@injectable()
class B extends A {
@preDestroy()
destroy() {
count++;
}
}
const ioc = new IocContext();
ioc.get(B);
ioc.clear();
t.is(count, 1);
@injectable()
class C extends B {
@preDestroy()
destroy2() {
count++;
}
}
ioc.get(C);
ioc.clear();
t.is(count, 3);
}); | the_stack |
import * as coder from '../src/country-coder';
function tuple<T extends any[]>(...data: T) {
return data;
}
describe('country-coder', () => {
describe('borders', () => {
it('exports borders as a feature collection', () => {
expect(coder.borders).toHaveProperty('features');
});
describe('properties', () => {
it('all identifying values are unique', () => {
let ids = {};
let identifierProps = [
'iso1A2',
'iso1A3',
'm49',
'wikidata',
'emojiFlag',
'ccTLD',
'nameEn'
];
for (let i in coder.borders.features) {
let identifiers = identifierProps
.map(function (prop) {
return coder.borders.features[i].properties[prop];
})
.concat(coder.borders.features[i].properties.aliases || [])
.filter(Boolean);
for (let j in identifiers) {
let id = identifiers[j];
expect(ids[id]).toBeUndefined();
ids[id] = true;
}
}
});
it('each feature has either member features or geometry but not both', () => {
for (let i in coder.borders.features) {
let feature = coder.borders.features[i];
let hasMembers = feature.properties.members && feature.properties.members.length;
expect(hasMembers || feature.geometry || null).not.toBeNull();
expect((hasMembers && feature.geometry) || null).toBeNull();
}
});
});
describe('id', () => {
it('assigns unique id to every feature', () => {
let ids = {};
for (let i in coder.borders.features) {
let id = coder.borders.features[i].properties.id;
expect(id).not.toBeNull();
expect(ids[id]).toBeUndefined();
ids[id] = true;
}
});
});
describe('level', () => {
it('assigns appropriate level values', () => {
expect(coder.feature('AC')?.properties.level).toBe('subterritory');
expect(coder.feature('SH-HL')?.properties.level).toBe('subterritory');
expect(coder.feature('DG')?.properties.level).toBe('subterritory');
expect(coder.feature('CP')?.properties.level).toBe('subterritory');
expect(coder.feature('Alderney')?.properties.level).toBe('subterritory');
expect(coder.feature('Akrotiri')?.properties.level).toBe('subterritory');
expect(coder.feature('FX')?.properties.level).toBe('subterritory');
expect(coder.feature('IC')?.properties.level).toBe('subterritory');
expect(coder.feature('SBA')?.properties.level).toBe('territory');
expect(coder.feature('EA')?.properties.level).toBe('territory');
expect(coder.feature('IM')?.properties.level).toBe('territory');
expect(coder.feature('SH')?.properties.level).toBe('territory');
expect(coder.feature('IO')?.properties.level).toBe('territory');
expect(coder.feature('PR')?.properties.level).toBe('territory');
expect(coder.feature('GU')?.properties.level).toBe('territory');
expect(coder.feature('GB-SCT')?.properties.level).toBe('territory');
expect(coder.feature('Bir Tawil')?.properties.level).toBe('territory');
expect(coder.feature('East Malaysia')?.properties.level).toBe('territory');
expect(coder.feature('Cook Islands')?.properties.level).toBe('territory');
expect(coder.feature('Niue')?.properties.level).toBe('territory');
expect(coder.feature('US')?.properties.level).toBe('country');
expect(coder.feature('CA')?.properties.level).toBe('country');
expect(coder.feature('GB')?.properties.level).toBe('country');
expect(coder.feature('NZ')?.properties.level).toBe('country');
expect(coder.feature('IL')?.properties.level).toBe('country');
expect(coder.feature('PS')?.properties.level).toBe('country');
expect(coder.feature('XK')?.properties.level).toBe('country');
expect(coder.feature('BOTS')?.properties.level).toBe('subcountryGroup');
expect(coder.feature('OMR')?.properties.level).toBe('subunion');
expect(coder.feature('OCT')?.properties.level).toBe('subunion');
expect(coder.feature('EU')?.properties.level).toBe('union');
expect(coder.feature('UN')?.properties.level).toBe('unitedNations');
expect(coder.feature('001')?.properties.level).toBe('world');
});
it('each feature may have only one group per level (except North America)', () => {
for (let i in coder.borders.features) {
let feature = coder.borders.features[i];
let groups = feature.properties.groups;
if (groups) {
groups = groups.slice().filter(function (group) {
// North America and Northern America are overlapping subregions
// defined by the UN, but ignore that here
return group !== '003';
});
let levels = groups.map(function (group) {
return coder.feature(group)?.properties.level;
});
levels.push(feature.properties.level);
expect(levels.length).toBe([...new Set(levels)].length);
}
}
});
});
});
describe('feature', () => {
it('does not find feature for empty string', () => {
expect(coder.feature('')).toBeNull();
});
it('does not find feature for garbage string', () => {
expect(coder.feature('fv 239uasˇÁ¨·´€Óı¨ıÎ∆πˆç´œª -aÔ˚øØTˇ°\\asdf \nK')).toBeNull();
});
describe('by ISO 3166-1 alpha-2', () => {
it('finds feature by uppercase code: US', () => {
expect(coder.feature('US')?.properties.iso1N3).toBe('840');
});
it('finds feature by lowercase code: us', () => {
expect(coder.feature('us')?.properties.iso1N3).toBe('840');
});
it('finds feature by mixed-case code: Us', () => {
expect(coder.feature('Us')?.properties.iso1N3).toBe('840');
});
it('does not find feature for unassigned code in range: AB', () => {
expect(coder.feature('AB'))?.toBeNull();
});
});
describe('by ISO 3166-1 alpha-3', () => {
it('finds features by uppercase codes', () => {
expect(coder.feature('AND')?.properties.iso1A2).toBe('AD');
expect(coder.feature('BES')?.properties.iso1A2).toBe('BQ');
expect(coder.feature('ETH')?.properties.iso1A2).toBe('ET');
expect(coder.feature('SGS')?.properties.iso1A2).toBe('GS');
expect(coder.feature('SRB')?.properties.iso1A2).toBe('RS');
expect(coder.feature('USA')?.properties.iso1A2).toBe('US');
});
it('finds features by lowercase codes', () => {
expect(coder.feature('and')?.properties.iso1A2).toBe('AD');
expect(coder.feature('bes')?.properties.iso1A2).toBe('BQ');
expect(coder.feature('eth')?.properties.iso1A2).toBe('ET');
expect(coder.feature('sgs')?.properties.iso1A2).toBe('GS');
expect(coder.feature('srb')?.properties.iso1A2).toBe('RS');
expect(coder.feature('usa')?.properties.iso1A2).toBe('US');
});
it('finds features by mixed-case codes', () => {
expect(coder.feature('And')?.properties.iso1A2).toBe('AD');
expect(coder.feature('Bes')?.properties.iso1A2).toBe('BQ');
expect(coder.feature('Eth')?.properties.iso1A2).toBe('ET');
expect(coder.feature('Sgs')?.properties.iso1A2).toBe('GS');
expect(coder.feature('Srb')?.properties.iso1A2).toBe('RS');
expect(coder.feature('Usa')?.properties.iso1A2).toBe('US');
});
it('does not find features for unassigned codes in range', () => {
expect(coder.feature('ABC')).toBeNull();
expect(coder.feature('Abc')).toBeNull();
expect(coder.feature('abc')).toBeNull();
});
});
describe('by ISO 3166-1 numeric-3 / M49', () => {
it('finds feature by string: "840"', () => {
expect(coder.feature('840')?.properties.iso1A2).toBe('US');
});
it('finds feature by three-digit number: 840', () => {
expect(coder.feature(840)?.properties.iso1A2).toBe('US');
});
it('finds feature by two-digit number: 61', () => {
expect(coder.feature(61)?.properties.wikidata).toBe('Q35942');
});
it('finds feature by one-digit number: 2', () => {
expect(coder.feature(2)?.properties.wikidata).toBe('Q15');
});
it('finds feature by number with extra precision: 840.000', () => {
expect(coder.feature(840.0)?.properties.iso1A2).toBe('US');
});
it('finds world feature: "001"', () => {
expect(coder.feature('001')?.properties.wikidata).toBe('Q2');
});
it('does not find feature for unassigned code in range: "123"', () => {
expect(coder.feature('123')).toBeNull();
});
it('does not find feature for number outside range: 1234', () => {
expect(coder.feature(1234)).toBeNull();
});
});
describe('by emoji flag sequence', () => {
it('finds feature for emoji flag sequence: 🇺🇸', () => {
expect(coder.feature('🇺🇸')?.properties.iso1N3).toBe('840');
});
it('does not find feature for unassigned emoji flag sequence: 🇦🇧', () => {
expect(coder.feature('🇦🇧')).toBeNull();
});
});
describe('by ccTLD', () => {
it('finds feature by uppercase code: .US', () => {
expect(coder.feature('.US')?.properties.iso1N3).toBe('840');
});
it('finds feature by lowercase code: .us', () => {
expect(coder.feature('.us')?.properties.iso1N3).toBe('840');
});
it('finds feature by mixed-case code: .Us', () => {
expect(coder.feature('.Us')?.properties.iso1N3).toBe('840');
});
it('does not find feature for unassigned code in range: .AB', () => {
expect(coder.feature('.AB')).toBeNull();
});
it('finds United Kingdom feature by code: .uk', () => {
expect(coder.feature('.uk')?.properties.iso1N3).toBe('826');
});
it('does not find United Kingdom feature by code: .gb', () => {
expect(coder.feature('.gb')).toBeNull();
});
});
describe('by Wikidata QID', () => {
it('finds feature by uppercase QID: Q30', () => {
expect(coder.feature('Q30')?.properties.iso1A2).toBe('US');
});
it('finds feature by lowercase QID: q30', () => {
expect(coder.feature('q30')?.properties.iso1A2).toBe('US');
});
it('finds feature with no ISO or M49 codes by QID: Q153732', () => {
expect(coder.feature('Q153732')?.properties.nameEn).toBe('Mariana Islands');
});
it('does not find feature for non-feature QID: Q123456', () => {
expect(coder.feature('Q123456')).toBeNull();
});
});
describe('by English name', () => {
it('finds feature for exact name: Bhutan', () => {
expect(coder.feature('Bhutan')?.properties.iso1A2).toBe('BT');
});
it('finds feature for exact name containing "And": Andorra', () => {
expect(coder.feature('Andorra')?.properties.iso1A2).toBe('AD');
});
it('finds feature for lowercase name containing "and": andorra', () => {
expect(coder.feature('andorra')?.properties.iso1A2).toBe('AD');
});
it('finds feature for name containing "the": Northern Europe', () => {
expect(coder.feature('Northern Europe')?.properties.m49).toBe('154');
});
it('finds feature for name with extra "The": The United States of America', () => {
expect(coder.feature('The United States of America')?.properties.iso1A2).toBe('US');
});
it('finds feature for name without "The": Gambia', () => {
expect(coder.feature('Gambia')?.properties.iso1A2).toBe('GM');
});
it('finds feature not in country for name: Bir Tawil', () => {
expect(coder.feature('Bir Tawil')?.properties.wikidata).toBe('Q620634');
});
});
describe('by alias', () => {
it('finds by European Commission codes', () => {
expect(coder.feature('EL')?.properties.iso1N3).toBe('300');
expect(coder.feature('el')?.properties.iso1N3).toBe('300');
expect(coder.feature('UK')?.properties.iso1N3).toBe('826');
});
it('finds by transitionally-reserved codes', () => {
expect(coder.feature('BU')?.properties.iso1N3).toBe('104');
});
it('finds by indeterminately-reserved codes', () => {
expect(coder.feature('PI')?.properties.iso1N3).toBe('608');
expect(coder.feature('RP')?.properties.iso1N3).toBe('608');
});
it('finds by ISO 3166-2 codes', () => {
expect(coder.feature('UM-71')?.properties.nameEn).toBe('Midway Atoll');
expect(coder.feature('UM71')?.properties.nameEn).toBe('Midway Atoll');
expect(coder.feature('UM 71')?.properties.nameEn).toBe('Midway Atoll');
expect(coder.feature('US-AK')?.properties.nameEn).toBe('Alaska');
});
it('finds by deleted codes', () => {
expect(coder.feature('MI')?.properties.nameEn).toBe('Midway Atoll');
expect(coder.feature('MID')?.properties.nameEn).toBe('Midway Atoll');
expect(coder.feature('488')?.properties.nameEn).toBe('Midway Atoll');
});
it('finds by common abbreviations', () => {
expect(coder.feature('CONUS')?.properties.nameEn).toBe('Contiguous United States');
expect(coder.feature('SBA')?.properties.wikidata).toBe('Q37362');
expect(coder.feature('BOTS')?.properties.wikidata).toBe('Q46395');
expect(coder.feature('UKOTS')?.properties.wikidata).toBe('Q46395');
});
});
describe('by location', () => {
it('returns country feature by default', () => {
expect(coder.feature([12.59, 55.68])?.properties.iso1A2).toBe('DK');
expect(coder.feature([-74, 40.6])?.properties.iso1A2).toBe('US');
expect(coder.feature([-12.3, -37.1])?.properties.iso1A2).toBe('GB');
expect(coder.feature([153, -27.4])?.properties.iso1A2).toBe('AU');
});
it('returns country feature for country level', () => {
expect(coder.feature([12.59, 55.68], { level: 'country' })?.properties.iso1A2).toBe('DK');
expect(coder.feature([-74, 40.6], { level: 'country' })?.properties.iso1A2).toBe('US');
expect(coder.feature([-12.3, -37.1], { level: 'country' })?.properties.iso1A2).toBe('GB');
expect(coder.feature([153, -27.4], { level: 'country' })?.properties.iso1A2).toBe('AU');
});
it('returns next-higher-level feature for country level where no country exists (Bir Tawil)', () => {
expect(coder.feature([33.75, 21.87])?.properties.m49).toBe('015');
expect(coder.feature([33.75, 21.87], { level: 'country' })?.properties.m49).toBe('015');
});
it('returns null for country level where no country exists', () => {
expect(coder.feature([33.75, 21.87], { maxLevel: 'country' })).toBeNull();
expect(coder.feature([33.75, 21.87], { level: 'country', maxLevel: 'country' })).toBeNull();
});
it('returns subterritory feature for subterritory level', () => {
expect(coder.feature([-12.3, -37.1], { level: 'subterritory' })?.properties.iso1A2).toBe(
'TA'
);
});
it('returns country feature for subterritory level where no subterritory or territory exists', () => {
expect(coder.feature([-79.4, 43.7], { level: 'subterritory' })?.properties.iso1A2).toBe(
'CA'
);
});
it('returns territory feature for territory level', () => {
expect(coder.feature([-12.3, -37.1], { level: 'territory' })?.properties.iso1A2).toBe('SH');
expect(coder.feature([33.75, 21.87], { level: 'territory' })?.properties.wikidata).toBe(
'Q620634'
);
expect(coder.feature([33.75, 21.87], { level: 'territory' })?.properties.wikidata).toBe(
'Q620634'
);
});
it('returns country feature for territory level where no territory exists', () => {
expect(coder.feature([-79.4, 43.7], { level: 'territory' })?.properties.iso1A2).toBe('CA');
});
it('returns null for territory level where no territory exists', () => {
expect(
coder.feature([-79.4, 43.7], { level: 'territory', maxLevel: 'territory' })
).toBeNull();
});
it('returns intermediateRegion feature for intermediateRegion level', () => {
expect(coder.feature([-12.3, -37.1], { level: 'intermediateRegion' })?.properties.m49).toBe(
'011'
);
});
it('returns subregion feature for subregion level', () => {
expect(coder.feature([-12.3, -37.1], { level: 'subregion' })?.properties.m49).toBe('202');
});
it('returns region feature for region level', () => {
expect(coder.feature([-12.3, -37.1], { level: 'region' })?.properties.m49).toBe('002');
});
it('returns union feature for union level', () => {
expect(coder.feature([2.35, 48.85], { level: 'union' })?.properties.iso1A2).toBe('EU');
});
it('returns null for invalid level options', () => {
expect(coder.feature([-12.3, -37.1], { level: 'planet' })).toBeNull();
expect(coder.feature([-12.3, -37.1], { maxLevel: 'mars' })).toBeNull();
expect(coder.feature([-12.3, -37.1], { maxLevel: 'subterritory' })).toBeNull();
expect(
coder.feature([-12.3, -37.1], { level: 'country', maxLevel: 'subterritory' })
).toBeNull();
});
it('returns Antarctica for South Pole, country level', () => {
expect(coder.feature([0, -90])?.properties.iso1A2).toBe('AQ');
expect(coder.feature([0, -90], { level: 'country' })?.properties.iso1A2).toBe('AQ');
});
it('returns null for North Pole', () => {
expect(coder.feature([0, 90])).toBeNull();
expect(coder.feature([0, 90], { level: 'country' })).toBeNull();
expect(coder.feature([0, 90], { level: 'subterritory' })).toBeNull();
});
});
});
describe('iso1A2Code', () => {
describe('by ISO 3166-1 alpha-2', () => {
it('finds by ISO 3166-1 alpha-2 code: US', () => {
expect(coder.iso1A2Code('US')).toBe('US');
});
it('does not find for unassigned alpha-2 code: AB', () => {
expect(coder.iso1A2Code('AB')).toBeNull();
});
});
describe('by ISO 3166-1 alpha-3', () => {
it('finds by ISO 3166-1 alpha-3 code: USA', () => {
expect(coder.iso1A2Code('USA')).toBe('US');
});
it('does not find feature for unassigned alpha-3 code: ABC', () => {
expect(coder.iso1A2Code('ABC')).toBeNull();
});
});
describe('by ISO 3166-1 numeric-3', () => {
it('finds by ISO 3166-1 numeric-3 code: "840"', () => {
expect(coder.iso1A2Code('840')).toBe('US');
});
it('does not find for unassigned numeric-3 code: "123"', () => {
expect(coder.iso1A2Code('123')).toBeNull();
});
});
describe('finds by emoji flag sequence', () => {
it('finds feature for emoji flag sequence: 🇺🇸', () => {
expect(coder.iso1A2Code('🇺🇸')).toBe('US');
});
it('does not find for unassigned emoji flag sequence: 🇦🇧', () => {
expect(coder.iso1A2Code('🇦🇧')).toBeNull();
});
});
describe('by ccTLD', () => {
it('finds by ccTLD code: .us', () => {
expect(coder.iso1A2Code('.us')).toBe('US');
});
it('does not find for unassigned ccTLD code: .ab', () => {
expect(coder.iso1A2Code('.ab')).toBeNull();
});
it('finds United Kingdom by ccTLD code: .uk', () => {
expect(coder.iso1A2Code('.uk')).toBe('GB');
});
it('does not find United Kingdom by ccTLD code: .gb', () => {
expect(coder.iso1A2Code('.gb')).toBeNull();
});
it('finds Germany by ccTLD code: .de', () => {
expect(coder.iso1A2Code('.de')).toBe('DE');
});
});
describe('by Wikidata QID', () => {
it('finds by Wikidata QID: Q30', () => {
expect(coder.iso1A2Code('Q30')).toBe('US');
});
it('does not find for non-feature Wikidata QID code: Q123456', () => {
expect(coder.iso1A2Code('Q123456')).toBeNull();
});
});
describe('by alias', () => {
it('finds Greece by European Commission code: EL', () => {
expect(coder.iso1A2Code('EL')).toBe('GR');
});
it('finds United Kingdom by European Commission code: UK', () => {
expect(coder.iso1A2Code('UK')).toBe('GB');
});
it('finds Myanmar by transitionally-reserved code: BU', () => {
expect(coder.iso1A2Code('BU')).toBe('MM');
});
it('finds Philippines by indeterminately-reserved code 1: PI', () => {
expect(coder.iso1A2Code('PI')).toBe('PH');
});
it('finds Philippines by indeterminately-reserved code 2: RP', () => {
expect(coder.iso1A2Code('RP')).toBe('PH');
});
});
describe('by M49', () => {
it('does not find for feature with geography but no ISO code', () => {
expect(coder.iso1A2Code('680')).toBeNull();
});
it('does not find for feature with no geography and no ISO code', () => {
expect(coder.iso1A2Code('142')).toBeNull();
});
});
describe('by location, country level', () => {
it('codes location in officially-assigned country: Toronto, Canada as CA', () => {
expect(coder.iso1A2Code([-79.4, 43.7], { level: 'country' })).toBe('CA');
});
it('codes location in non-ISO territory of officially-assigned country: New York, United States as US', () => {
expect(coder.iso1A2Code([-74, 40.6], { level: 'country' })).toBe('US');
});
it('codes location in officially-assigned country, outside but surrounded by EU: Geneva, Switzerland as CH', () => {
expect(coder.iso1A2Code([6.1, 46.2], { level: 'country' })).toBe('CH');
});
it('codes location in officially-assigned country, in EU, outside Eurozone: Copenhagen, Denmark as DK', () => {
expect(coder.iso1A2Code([12.59, 55.68], { level: 'country' })).toBe('DK');
});
it('codes location in officially-assigned country, in EU, in Eurozone: Berlin, Germany as DE', () => {
expect(coder.iso1A2Code([13.4, 52.5], { level: 'country' })).toBe('DE');
});
it('codes location in officially-assigned subfeature of officially-assigned country: Isle of Man, United Kingdom as GB', () => {
expect(coder.iso1A2Code([-4.5, 54.2], { level: 'country' })).toBe('GB');
});
it('codes location in exceptionally-reserved subfeature of officially-assigned country: Paris, Metropolitan France as FR', () => {
expect(coder.iso1A2Code([2.35, 48.85], { level: 'country' })).toBe('FR');
});
it('codes location in exceptionally-reserved subfeature of officially-assigned subfeature of officially-assigned country: Tristan da Cunha, SH, UK as GB', () => {
expect(coder.iso1A2Code([-12.3, -37.1], { level: 'country' })).toBe('GB');
});
it('codes location in user-assigned, de facto country: Kosovo as XK', () => {
expect(coder.iso1A2Code([21, 42.6], { level: 'country' })).toBe('XK');
});
it('codes location in exclave of officially-assigned country: Sokh District, Uzbekistan as UZ', () => {
expect(coder.iso1A2Code([71.13, 39.96], { level: 'country' })).toBe('UZ');
});
it('codes location in feature without an ISO code: Sark as GB', () => {
expect(coder.iso1A2Code([-2.35, 49.43], { level: 'country' })).toBe('GB');
});
it('codes South Pole as AQ', () => {
expect(coder.iso1A2Code([0, -90], { level: 'country' })).toBe('AQ');
});
it('does not code North Pole', () => {
expect(coder.iso1A2Code([0, 90], { level: 'country' })).toBeNull();
});
it('does not code location in Bir Tawil', () => {
expect(coder.iso1A2Code([33.75, 21.87])).toBeNull();
expect(coder.iso1A2Code([33.75, 21.87], { level: 'country' })).toBeNull();
});
});
describe('by location, territory level', () => {
it('codes location in officially-assigned country: Toronto, Canada as CA', () => {
expect(coder.iso1A2Code([-79.4, 43.7], { level: 'territory' })).toBe('CA');
});
it('codes location in non-ISO territory of officially-assigned country: New York, United States as US', () => {
expect(coder.iso1A2Code([-74, 40.6], { level: 'territory' })).toBe('US');
});
it('codes location in officially-assigned country, outside but surrounded by EU: Geneva, Switzerland as CH', () => {
expect(coder.iso1A2Code([6.1, 46.2], { level: 'territory' })).toBe('CH');
});
it('codes location in officially-assigned country, in EU, outside Eurozone: Copenhagen, Denmark as DK', () => {
expect(coder.iso1A2Code([12.59, 55.68], { level: 'territory' })).toBe('DK');
});
it('codes location in officially-assigned country, in EU, in Eurozone: Berlin, Germany as DE', () => {
expect(coder.iso1A2Code([13.4, 52.5], { level: 'territory' })).toBe('DE');
});
it('codes location in officially-assigned subfeature of officially-assigned country: Isle of Man, United Kingdom as IM', () => {
expect(coder.iso1A2Code([-4.5, 54.2], { level: 'territory' })).toBe('IM');
});
it('codes location in exceptionally-reserved subfeature of officially-assigned country: Paris, Metropolitan France as FR', () => {
expect(coder.iso1A2Code([2.35, 48.85], { level: 'territory' })).toBe('FR');
});
it('codes location in exceptionally-reserved subfeature of officially-assigned subfeature of officially-assigned country: Tristan da Cunha, SH, UK as SH', () => {
expect(coder.iso1A2Code([-12.3, -37.1], { level: 'territory' })).toBe('SH');
});
it('codes location in user-assigned, de facto country: Kosovo as XK', () => {
expect(coder.iso1A2Code([21, 42.6], { level: 'territory' })).toBe('XK');
});
it('codes location in exclave of officially-assigned country: Sokh District, Uzbekistan as UZ', () => {
expect(coder.iso1A2Code([71.13, 39.96], { level: 'territory' })).toBe('UZ');
});
it('codes location in feature without an ISO code: Sark as GG', () => {
expect(coder.iso1A2Code([-2.35, 49.43], { level: 'territory' })).toBe('GG');
});
it('codes South Pole as AQ', () => {
expect(coder.iso1A2Code([0, -90], { level: 'territory' })).toBe('AQ');
});
it('does not code North Pole', () => {
expect(coder.iso1A2Code([0, 90], { level: 'territory' })).toBeNull();
});
it('does not code location in Bir Tawil', () => {
expect(coder.iso1A2Code([33.75, 21.87], { level: 'territory' })).toBeNull();
});
});
describe('by GeoJSON point feature, country level', () => {
it('codes location in officially-assigned country: New York, United States as US', () => {
const coords = tuple(-74, 40.6);
let pointFeature = {
type: 'Feature',
properties: null,
geometry: {
type: 'Point',
coordinates: coords
}
};
expect(coder.iso1A2Code(pointFeature)).toBe('US');
});
});
describe('by GeoJSON point geometry, country level', () => {
it('codes location in officially-assigned country: New York, United States as US', () => {
let pointGeometry = {
type: 'Point',
coordinates: tuple(-74, 40.6)
};
expect(coder.iso1A2Code(pointGeometry)).toBe('US');
});
});
});
// this doesn't need extensive tests since it's just a fetcher using `feature`
describe('iso1A3Code', () => {
it('codes location in officially-assigned country: New York, United States as USA', () => {
expect(coder.iso1A3Code([-74, 40.6])).toBe('USA');
expect(coder.iso1A3Code([-74, 40.6], { level: 'country' })).toBe('USA');
});
it('codes location in user-assigned, de facto country: Kosovo as XKX', () => {
expect(coder.iso1A3Code([21, 42.6])).toBe('XKX');
expect(coder.iso1A3Code([21, 42.6], { level: 'country' })).toBe('XKX');
});
it('does not code location of North Pole', () => {
expect(coder.iso1A3Code([0, 90])).toBeNull();
expect(coder.iso1A3Code([0, 90], { level: 'country' })).toBeNull();
});
it('does not code location in Bir Tawil', () => {
expect(coder.iso1A3Code([33.75, 21.87])).toBeNull();
expect(coder.iso1A3Code([33.75, 21.87], { level: 'country' })).toBeNull();
});
it('does not code feature without alpha-3 code by identifier', () => {
expect(coder.iso1A3Code('Bir Tawil')).toBeNull();
expect(coder.iso1A3Code('Sark')).toBeNull();
expect(coder.iso1A3Code('830')).toBeNull();
expect(coder.iso1A3Code('Northern America')).toBeNull();
expect(coder.iso1A3Code('Oceania')).toBeNull();
});
});
// this doesn't need extensive tests since it's just a fetcher using `feature`
describe('iso1N3Code', () => {
it('codes location in officially-assigned country: New York, United States as 840', () => {
expect(coder.iso1N3Code([-74, 40.6], { level: 'country' })).toBe('840');
});
it('does not have code for location in user-assigned, de facto country: Kosovo', () => {
expect(coder.iso1N3Code([21, 42.6], { level: 'country' })).toBeNull();
});
it('does not code non-geography, non-ISO feature by Wikidata QID: Q48', () => {
expect(coder.iso1N3Code('Q48')).toBeNull();
});
it('does not code North Pole', () => {
expect(coder.iso1N3Code([0, 90], { level: 'country' })).toBeNull();
});
it('does not code location in Bir Tawil', () => {
expect(coder.iso1N3Code([33.75, 21.87], { level: 'country' })).toBeNull();
});
});
describe('m49Code', () => {
it('codes location in officially-assigned country: New York, United States as 840', () => {
expect(coder.m49Code([-74, 40.6], { level: 'country' })).toBe('840');
});
it('codes non-geography, non-ISO feature by Wikidata QID: Q48 as 142', () => {
expect(coder.m49Code('Q48')).toBe('142');
});
it('does not have code for location in user-assigned, de facto country: Kosovo', () => {
expect(coder.m49Code([21, 42.6], { maxLevel: 'country' })).toBeNull();
expect(coder.m49Code([21, 42.6], { level: 'country', maxLevel: 'country' })).toBeNull();
});
it('does not code location of North Pole', () => {
expect(coder.m49Code([0, 90], { level: 'country' })).toBeNull();
});
it('does not code "Bir Tawil"', () => {
expect(coder.m49Code('Bir Tawil')).toBeNull();
});
it('codes location in Bir Tawil as 015', () => {
expect(coder.m49Code([33.75, 21.87])).toBe('015');
expect(coder.m49Code([33.75, 21.87], { level: 'country' })).toBe('015');
});
it('does not code location in Bir Tawil, maxLevel=country', () => {
expect(coder.m49Code([33.75, 21.87], { maxLevel: 'country' })).toBeNull();
expect(coder.m49Code([33.75, 21.87], { level: 'country', maxLevel: 'country' })).toBeNull();
});
});
// this doesn't need extensive tests since it's just a fetcher using `feature`
describe('wikidataQID', () => {
it('codes location in officially-assigned country: New York, United States as Q30', () => {
expect(coder.wikidataQID([-74, 40.6], { level: 'country' })).toBe('Q30');
});
it('codes location in user-assigned, de facto country: Kosovo as Q1246', () => {
expect(coder.wikidataQID([21, 42.6], { level: 'country' })).toBe('Q1246');
});
it('does not code North Pole', () => {
expect(coder.wikidataQID([0, 90], { level: 'country' })).toBeNull();
});
it('codes Bir Tawil', () => {
expect(coder.wikidataQID('Bir Tawil')).toBe('Q620634');
});
});
// this doesn't need extensive tests since it's just a fetcher using `feature`
describe('emojiFlag', () => {
it('codes location in officially-assigned country: New York, United States as 🇺🇸', () => {
expect(coder.emojiFlag([-74, 40.6], { level: 'country' })).toBe('🇺🇸');
});
it('codes location in user-assigned, de facto country: Kosovo as 🇽🇰', () => {
expect(coder.emojiFlag([21, 42.6], { level: 'country' })).toBe('🇽🇰');
});
it('does not find for M49 code with no corresponding ISO code', () => {
expect(coder.emojiFlag('150')).toBeNull();
});
it('does not code North Pole', () => {
expect(coder.emojiFlag([0, 90], { level: 'country' })).toBeNull();
});
});
// this doesn't need extensive tests since it's just a fetcher using `feature`
describe('ccTLD', () => {
it('returns ccTLD in officially-assigned country: New York, United States as .us', () => {
expect(coder.ccTLD([-74, 40.6], { level: 'country' })).toBe('.us');
});
it('returns ccTLD in officially-assigned country: London, United Kingdom as .uk', () => {
expect(coder.ccTLD([0, 51.5], { level: 'country' })).toBe('.uk'); // not .gb
});
it('does not return a ccTLD for a region with no ccTLD', () => {
expect(coder.ccTLD('Bir Tawil')).toBeNull();
});
it('does not return a ccTLD for uncovered location North Pole', () => {
expect(coder.ccTLD([0, 90])).toBeNull();
});
});
describe('iso1A2Codes', () => {
it('codes locations', () => {
expect(coder.iso1A2Codes([-4.5, 54.2])).toStrictEqual(['IM', 'GB', 'UN']);
expect(coder.iso1A2Codes([-2.35, 49.43])).toStrictEqual(['GG', 'GB', 'UN']);
expect(coder.iso1A2Codes([-12.3, -37.1])).toStrictEqual(['TA', 'SH', 'GB', 'UN']);
expect(coder.iso1A2Codes([12.59, 55.68])).toStrictEqual(['DK', 'EU', 'UN']);
expect(coder.iso1A2Codes([2.35, 48.85])).toStrictEqual(['FX', 'FR', 'EU', 'UN']);
expect(coder.iso1A2Codes([-74, 40.6])).toStrictEqual(['US', 'UN']);
expect(coder.iso1A2Codes([21, 42.6])).toStrictEqual(['XK']);
expect(coder.iso1A2Codes([0, -90])).toStrictEqual(['AQ']);
});
it('codes bounding boxes', () => {
expect(coder.iso1A2Codes([-4.5, 54.2, -4.4, 54.3])).toStrictEqual(['IM', 'GB', 'UN']);
// area of US overlapping Canada's bounding box but not its polygon
expect(coder.iso1A2Codes([-74, 40.6, -71.3, 44.7])).toStrictEqual(['US', 'UN']);
// area overlapping both US and Canada
expect(coder.iso1A2Codes([-74, 40.6, -71.3, 45])).toStrictEqual(['CA', 'UN', 'US']);
});
it('does not code invalid arguments', () => {
expect(coder.iso1A2Codes([] as any)).toStrictEqual([]);
expect(coder.iso1A2Codes([-900, 900])).toStrictEqual([]);
});
it('does not code North Pole', () => {
expect(coder.iso1A2Codes([0, 90])).toStrictEqual([]);
expect(coder.iso1A2Codes([-0.1, 89.9, 0, 90])).toStrictEqual([]);
});
it('does not code location in Bir Tawil', () => {
expect(coder.iso1A2Codes([33.75, 21.87])).toStrictEqual([]);
});
});
describe('iso1A3Codes', () => {
it('codes locations', () => {
expect(coder.iso1A3Codes([-4.5, 54.2])).toStrictEqual(['IMN', 'GBR']);
expect(coder.iso1A3Codes([-2.35, 49.43])).toStrictEqual(['GGY', 'GBR']);
expect(coder.iso1A3Codes([-12.3, -37.1])).toStrictEqual(['TAA', 'SHN', 'GBR']);
expect(coder.iso1A3Codes([12.59, 55.68])).toStrictEqual(['DNK', 'EUE']);
expect(coder.iso1A3Codes([2.35, 48.85])).toStrictEqual(['FXX', 'FRA', 'EUE']);
expect(coder.iso1A3Codes([-74, 40.6])).toStrictEqual(['USA']);
expect(coder.iso1A3Codes([21, 42.6])).toStrictEqual(['XKX']);
expect(coder.iso1A3Codes([0, -90])).toStrictEqual(['ATA']);
});
it('does not code North Pole', () => {
expect(coder.iso1A3Codes([0, 90])).toStrictEqual([]);
});
it('does not code location in Bir Tawil', () => {
expect(coder.iso1A3Codes([33.75, 21.87])).toStrictEqual([]);
});
});
describe('iso1N3Codes', () => {
it('codes locations', () => {
expect(coder.iso1N3Codes([-4.5, 54.2])).toStrictEqual(['833', '826']);
expect(coder.iso1N3Codes([-2.35, 49.43])).toStrictEqual(['831', '826']);
expect(coder.iso1N3Codes([-12.3, -37.1])).toStrictEqual(['654', '826']);
expect(coder.iso1N3Codes([12.59, 55.68])).toStrictEqual(['208']);
expect(coder.iso1N3Codes([2.35, 48.85])).toStrictEqual(['249', '250']);
expect(coder.iso1N3Codes([-74, 40.6])).toStrictEqual(['840']);
expect(coder.iso1N3Codes([21, 42.6])).toStrictEqual([]);
expect(coder.iso1N3Codes([0, -90])).toStrictEqual(['010']);
});
it('does not code North Pole', () => {
expect(coder.iso1N3Codes([0, 90])).toStrictEqual([]);
});
it('does not code location in Bir Tawil', () => {
expect(coder.iso1N3Codes([33.75, 21.87])).toStrictEqual([]);
});
});
describe('m49Codes', () => {
it('codes locations', () => {
// isle of man
expect(coder.m49Codes([-4.5, 54.2])).toStrictEqual(['833', '826', '154', '150', '001']);
expect(coder.m49Codes([-2.35, 49.43])).toStrictEqual([
'680',
'831',
'826',
'830',
'154',
'150',
'001'
]);
expect(coder.m49Codes([-12.3, -37.1])).toStrictEqual([
'654',
'826',
'011',
'202',
'002',
'001'
]);
expect(coder.m49Codes([12.59, 55.68])).toStrictEqual(['208', '154', '150', '001']);
expect(coder.m49Codes([2.35, 48.85])).toStrictEqual(['249', '250', '155', '150', '001']);
expect(coder.m49Codes([-74, 40.6])).toStrictEqual(['840', '021', '003', '019', '001']);
expect(coder.m49Codes([21, 42.6])).toStrictEqual(['039', '150', '001']);
expect(coder.m49Codes([0, -90])).toStrictEqual(['010', '001']);
expect(coder.m49Codes([33.75, 21.87])).toStrictEqual(['015', '002', '001']);
});
it('does not code North Pole', () => {
expect(coder.m49Codes([0, 90])).toStrictEqual([]);
});
});
describe('wikidataQIDs', () => {
it('codes locations', () => {
// isle of man
expect(coder.wikidataQIDs([-4.5, 54.2])).toStrictEqual([
'Q9676',
'Q185086',
'Q145',
'Q27479',
'Q46',
'Q1065',
'Q2'
]);
expect(coder.wikidataQIDs([-2.35, 49.43])).toStrictEqual([
'Q3405693',
'Q25230',
'Q185086',
'Q145',
'Q42314',
'Q27479',
'Q46',
'Q1065',
'Q2'
]);
expect(coder.wikidataQIDs([-12.3, -37.1])).toStrictEqual([
'Q220982',
'Q192184',
'Q46395',
'Q145',
'Q4412',
'Q132959',
'Q15',
'Q1065',
'Q2'
]);
expect(coder.wikidataQIDs([12.59, 55.68])).toStrictEqual([
'Q35',
'Q756617',
'Q27479',
'Q46',
'Q458',
'Q1065',
'Q2'
]);
expect(coder.wikidataQIDs([2.35, 48.85])).toStrictEqual([
'Q212429',
'Q142',
'Q27496',
'Q46',
'Q458',
'Q1065',
'Q2'
]);
expect(coder.wikidataQIDs([-74, 40.6])).toStrictEqual([
'Q578170',
'Q35657',
'Q30',
'Q2017699',
'Q49',
'Q828',
'Q1065',
'Q2'
]);
expect(coder.wikidataQIDs([21, 42.6])).toStrictEqual(['Q1246', 'Q27449', 'Q46', 'Q2']);
expect(coder.wikidataQIDs([0, -90])).toStrictEqual(['Q51', 'Q2']);
expect(coder.wikidataQIDs([33.75, 21.87])).toStrictEqual(['Q620634', 'Q27381', 'Q15', 'Q2']);
});
it('does not code North Pole', () => {
expect(coder.wikidataQIDs([0, 90])).toStrictEqual([]);
});
});
describe('emojiFlags', () => {
it('codes locations', () => {
// isle of man
expect(coder.emojiFlags([-4.5, 54.2])).toStrictEqual(['🇮🇲', '🇬🇧', '🇺🇳']);
expect(coder.emojiFlags([-2.35, 49.43])).toStrictEqual(['🇬🇬', '🇬🇧', '🇺🇳']);
expect(coder.emojiFlags([-12.3, -37.1])).toStrictEqual(['🇹🇦', '🇸🇭', '🇬🇧', '🇺🇳']);
expect(coder.emojiFlags([12.59, 55.68])).toStrictEqual(['🇩🇰', '🇪🇺', '🇺🇳']);
expect(coder.emojiFlags([2.35, 48.85])).toStrictEqual(['🇫🇽', '🇫🇷', '🇪🇺', '🇺🇳']);
expect(coder.emojiFlags([-74, 40.6])).toStrictEqual(['🇺🇸', '🇺🇳']);
expect(coder.emojiFlags([21, 42.6])).toStrictEqual(['🇽🇰']);
expect(coder.emojiFlags([0, -90])).toStrictEqual(['🇦🇶']);
});
it('does not code North Pole', () => {
expect(coder.emojiFlags([0, 90])).toStrictEqual([]);
});
it('does not code location in Bir Tawil', () => {
expect(coder.emojiFlags([33.75, 21.87])).toStrictEqual([]);
});
});
describe('ccTLDs', () => {
it('codes locations', () => {
expect(coder.ccTLDs([-4.5, 54.2])).toStrictEqual(['.im', '.uk']); // not .gb
expect(coder.ccTLDs([-2.35, 49.43])).toStrictEqual(['.gg', '.uk']); // not .gb
expect(coder.ccTLDs([-12.3, -37.1])).toStrictEqual(['.ta', '.sh', '.uk']); // not .gb
expect(coder.ccTLDs([12.59, 55.68])).toStrictEqual(['.dk', '.eu']);
expect(coder.ccTLDs([2.35, 48.85])).toStrictEqual(['.fx', '.fr', '.eu']);
expect(coder.ccTLDs([-74, 40.6])).toStrictEqual(['.us']);
expect(coder.ccTLDs([21, 42.6])).toStrictEqual(['.xk']);
expect(coder.ccTLDs([0, -90])).toStrictEqual(['.aq']);
});
it('codes bounding boxes', () => {
expect(coder.ccTLDs([-4.5, 54.2, -4.4, 54.3])).toStrictEqual(['.im', '.uk']); // not .gb
// area of US overlapping Canada's bounding box but not its polygon
expect(coder.ccTLDs([-74, 40.6, -71.3, 44.7])).toStrictEqual(['.us']);
// area overlapping both US and Canada
expect(coder.ccTLDs([-74, 40.6, -71.3, 45])).toStrictEqual(['.ca', '.us']);
});
it('does not code invalid arguments', () => {
expect(coder.ccTLDs([] as any)).toStrictEqual([]);
expect(coder.ccTLDs([-900, 900])).toStrictEqual([]);
});
it('does not code North Pole', () => {
expect(coder.ccTLDs([0, 90])).toStrictEqual([]);
expect(coder.ccTLDs([-0.1, 89.9, 0, 90])).toStrictEqual([]);
});
it('does not code location in Bir Tawil', () => {
expect(coder.ccTLDs([33.75, 21.87])).toStrictEqual([]);
});
});
describe('featuresContaining', () => {
describe('by location', () => {
it('codes location in officially-assigned country: New York, United States', () => {
let features = coder.featuresContaining([-74, 40.6]);
expect(features.length).toBe(8);
expect(features[0].properties.nameEn).toBe('Contiguous United States');
expect(features[1].properties.nameEn).toBe('US States');
expect(features[2].properties.iso1A2).toBe('US');
expect(features[3].properties.m49).toBe('021');
expect(features[4].properties.m49).toBe('003');
expect(features[5].properties.m49).toBe('019');
expect(features[6].properties.iso1A2).toBe('UN');
expect(features[7].properties.m49).toBe('001');
});
it('codes location in officially-assigned country: New York, United States, strict', () => {
let features = coder.featuresContaining([-74, 40.6], true);
expect(features.length).toBe(8);
expect(features[0].properties.nameEn).toBe('Contiguous United States');
expect(features[1].properties.nameEn).toBe('US States');
expect(features[2].properties.iso1A2).toBe('US');
expect(features[3].properties.m49).toBe('021');
expect(features[4].properties.m49).toBe('003');
expect(features[5].properties.m49).toBe('019');
expect(features[6].properties.iso1A2).toBe('UN');
expect(features[7].properties.m49).toBe('001');
});
it('codes location in officially-assigned country, outside but surrounded by EU: Geneva, Switzerland', () => {
let features = coder.featuresContaining([6.1, 46.2]);
expect(features.length).toBe(5);
expect(features[0].properties.iso1A2).toBe('CH');
expect(features[1].properties.m49).toBe('155');
expect(features[2].properties.m49).toBe('150');
expect(features[3].properties.iso1A2).toBe('UN');
expect(features[4].properties.m49).toBe('001');
});
it('codes location in officially-assigned country, in EU, outside Eurozone: Copenhagen, Denmark', () => {
let features = coder.featuresContaining([12.59, 55.68]);
expect(features.length).toBe(7);
expect(features[0].properties.wikidata).toBe('Q35');
expect(features[1].properties.iso1A2).toBe('DK');
expect(features[2].properties.m49).toBe('154');
expect(features[3].properties.m49).toBe('150');
expect(features[4].properties.iso1A2).toBe('EU');
expect(features[5].properties.iso1A2).toBe('UN');
expect(features[6].properties.m49).toBe('001');
});
it('codes location in officially-assigned country, in EU, in Eurozone: Berlin, Germany', () => {
let features = coder.featuresContaining([13.4, 52.5]);
expect(features.length).toBe(6);
expect(features[0].properties.iso1A2).toBe('DE');
expect(features[1].properties.m49).toBe('155');
expect(features[2].properties.m49).toBe('150');
expect(features[3].properties.iso1A2).toBe('EU');
expect(features[4].properties.iso1A2).toBe('UN');
expect(features[5].properties.m49).toBe('001');
});
it('codes location in officially-assigned subfeature, outside EU, of officially-assigned country, in EU: Isle of Man, United Kingdom', () => {
let features = coder.featuresContaining([-4.5, 54.2]);
expect(features.length).toBe(7);
expect(features[0].properties.iso1A2).toBe('IM');
expect(features[1].properties.wikidata).toBe('Q185086');
expect(features[2].properties.iso1A2).toBe('GB');
expect(features[3].properties.m49).toBe('154');
expect(features[4].properties.m49).toBe('150');
expect(features[5].properties.iso1A2).toBe('UN');
expect(features[6].properties.m49).toBe('001');
});
it('codes location in England, United Kingdom', () => {
let features = coder.featuresContaining([0, 51.5]);
expect(features.length).toBe(8);
expect(features[0].properties.nameEn).toBe('England');
expect(features[1].properties.nameEn).toBe('Countries of the United Kingdom');
expect(features[2].properties.iso1A2).toBe('GB');
expect(features[3].properties.nameEn).toBe('Great Britain');
expect(features[4].properties.m49).toBe('154');
expect(features[5].properties.m49).toBe('150');
expect(features[6].properties.iso1A2).toBe('UN');
expect(features[7].properties.m49).toBe('001');
});
it('codes location in exceptionally-reserved subfeature of officially-assigned country, in EU, in Eurozone: Paris, Metropolitan France', () => {
let features = coder.featuresContaining([2.35, 48.85]);
expect(features.length).toBe(7);
expect(features[0].properties.iso1A2).toBe('FX');
expect(features[1].properties.iso1A2).toBe('FR');
expect(features[2].properties.m49).toBe('155');
expect(features[3].properties.m49).toBe('150');
expect(features[4].properties.iso1A2).toBe('EU');
expect(features[5].properties.iso1A2).toBe('UN');
expect(features[6].properties.m49).toBe('001');
});
it('codes location in exceptionally-reserved subfeature of officially-assigned subfeature, outside EU, of officially-assigned country, in EU: Tristan da Cunha, SH, UK', () => {
let features = coder.featuresContaining([-12.3, -37.1]);
expect(features.length).toBe(9);
expect(features[0].properties.iso1A2).toBe('TA');
expect(features[1].properties.iso1A2).toBe('SH');
expect(features[2].properties.wikidata).toBe('Q46395');
expect(features[3].properties.iso1A2).toBe('GB');
expect(features[4].properties.m49).toBe('011');
expect(features[5].properties.m49).toBe('202');
expect(features[6].properties.m49).toBe('002');
expect(features[7].properties.iso1A2).toBe('UN');
expect(features[8].properties.m49).toBe('001');
});
it('codes location in user-assigned, de facto country: Kosovo', () => {
let features = coder.featuresContaining([21, 42.6]);
expect(features.length).toBe(4);
expect(features[0].properties.iso1A2).toBe('XK');
expect(features[1].properties.m49).toBe('039');
expect(features[2].properties.m49).toBe('150');
expect(features[3].properties.m49).toBe('001');
});
it('codes location in exclave of officially-assigned country: Sokh District, Uzbekistan', () => {
let features = coder.featuresContaining([71.13, 39.96]);
expect(features.length).toBe(5);
expect(features[0].properties.iso1A2).toBe('UZ');
expect(features[1].properties.m49).toBe('143');
expect(features[2].properties.m49).toBe('142');
expect(features[3].properties.iso1A2).toBe('UN');
expect(features[4].properties.m49).toBe('001');
});
it('codes South Pole as AQ', () => {
let features = coder.featuresContaining([0, -90]);
expect(features.length).toBe(2);
expect(features[0].properties.iso1A2).toBe('AQ');
expect(features[1].properties.m49).toBe('001');
});
it('does not code North Pole', () => {
expect(coder.featuresContaining([0, 90])).toStrictEqual([]);
});
});
describe('by code', () => {
it('codes US', () => {
let features = coder.featuresContaining('US');
expect(features.length).toBe(3);
expect(features[0].properties.iso1A2).toBe('US');
expect(features[1].properties.iso1A2).toBe('UN');
expect(features[2].properties.m49).toBe('001');
});
it('codes US, strict', () => {
let features = coder.featuresContaining('US', true);
expect(features.length).toBe(2);
expect(features[0].properties.iso1A2).toBe('UN');
expect(features[1].properties.m49).toBe('001');
});
it('codes CONUS', () => {
let features = coder.featuresContaining('CONUS');
expect(features.length).toBe(8);
expect(features[0].properties.nameEn).toBe('Contiguous United States');
expect(features[1].properties.nameEn).toBe('US States');
expect(features[2].properties.iso1A2).toBe('US');
expect(features[3].properties.m49).toBe('021');
expect(features[4].properties.m49).toBe('003');
expect(features[5].properties.m49).toBe('019');
expect(features[6].properties.iso1A2).toBe('UN');
expect(features[7].properties.m49).toBe('001');
});
it('codes CONUS, strict', () => {
let features = coder.featuresContaining('CONUS', true);
expect(features.length).toBe(7);
expect(features[0].properties.nameEn).toBe('US States');
expect(features[1].properties.iso1A2).toBe('US');
expect(features[2].properties.m49).toBe('021');
expect(features[3].properties.m49).toBe('003');
expect(features[4].properties.m49).toBe('019');
expect(features[5].properties.iso1A2).toBe('UN');
expect(features[6].properties.m49).toBe('001');
});
it('codes CH', () => {
let features = coder.featuresContaining('CH');
expect(features.length).toBe(5);
expect(features[0].properties.iso1A2).toBe('CH');
expect(features[1].properties.m49).toBe('155');
expect(features[2].properties.m49).toBe('150');
expect(features[3].properties.iso1A2).toBe('UN');
expect(features[4].properties.m49).toBe('001');
});
it('codes DK', () => {
let features = coder.featuresContaining('DK');
expect(features.length).toBe(3);
expect(features[0].properties.iso1A2).toBe('DK');
expect(features[1].properties.iso1A2).toBe('UN');
expect(features[2].properties.m49).toBe('001');
});
it('codes DE', () => {
let features = coder.featuresContaining('DE');
expect(features.length).toBe(6);
expect(features[0].properties.iso1A2).toBe('DE');
expect(features[1].properties.m49).toBe('155');
expect(features[2].properties.m49).toBe('150');
expect(features[3].properties.iso1A2).toBe('EU');
expect(features[4].properties.iso1A2).toBe('UN');
expect(features[5].properties.m49).toBe('001');
});
it('codes IM', () => {
let features = coder.featuresContaining('IM');
expect(features.length).toBe(7);
expect(features[0].properties.iso1A2).toBe('IM');
expect(features[1].properties.wikidata).toBe('Q185086');
expect(features[2].properties.iso1A2).toBe('GB');
expect(features[3].properties.m49).toBe('154');
expect(features[4].properties.m49).toBe('150');
expect(features[5].properties.iso1A2).toBe('UN');
expect(features[6].properties.m49).toBe('001');
});
it('codes GB', () => {
let features = coder.featuresContaining('GB');
expect(features.length).toBe(3);
expect(features[0].properties.iso1A2).toBe('GB');
expect(features[1].properties.iso1A2).toBe('UN');
expect(features[2].properties.m49).toBe('001');
});
it('codes FX', () => {
let features = coder.featuresContaining('FX');
expect(features.length).toBe(7);
expect(features[0].properties.iso1A2).toBe('FX');
expect(features[1].properties.iso1A2).toBe('FR');
expect(features[2].properties.m49).toBe('155');
expect(features[3].properties.m49).toBe('150');
expect(features[4].properties.iso1A2).toBe('EU');
expect(features[5].properties.iso1A2).toBe('UN');
expect(features[6].properties.m49).toBe('001');
});
it('codes TA', () => {
let features = coder.featuresContaining('TA');
expect(features.length).toBe(9);
expect(features[0].properties.iso1A2).toBe('TA');
expect(features[1].properties.iso1A2).toBe('SH');
expect(features[2].properties.wikidata).toBe('Q46395');
expect(features[3].properties.iso1A2).toBe('GB');
expect(features[4].properties.m49).toBe('011');
expect(features[5].properties.m49).toBe('202');
expect(features[6].properties.m49).toBe('002');
expect(features[7].properties.iso1A2).toBe('UN');
expect(features[8].properties.m49).toBe('001');
});
it('codes XK', () => {
let features = coder.featuresContaining('XK');
expect(features.length).toBe(4);
expect(features[0].properties.iso1A2).toBe('XK');
expect(features[1].properties.m49).toBe('039');
expect(features[2].properties.m49).toBe('150');
expect(features[3].properties.m49).toBe('001');
});
it('codes UZ', () => {
let features = coder.featuresContaining('UZ');
expect(features.length).toBe(5);
expect(features[0].properties.iso1A2).toBe('UZ');
expect(features[1].properties.m49).toBe('143');
expect(features[2].properties.m49).toBe('142');
expect(features[3].properties.iso1A2).toBe('UN');
expect(features[4].properties.m49).toBe('001');
});
it('codes AQ', () => {
let features = coder.featuresContaining('AQ');
expect(features.length).toBe(2);
expect(features[0].properties.iso1A2).toBe('AQ');
expect(features[1].properties.m49).toBe('001');
});
});
});
describe('featuresIn', () => {
it('codes CN', () => {
let features = coder.featuresIn('CN');
expect(features.length).toBe(4);
expect(features[0].properties.iso1A2).toBe('CN');
expect(features[1].properties.wikidata).toBe('Q19188');
expect(features[2].properties.iso1A2).toBe('HK');
expect(features[3].properties.iso1A2).toBe('MO');
});
it('codes CN, strict', () => {
let features = coder.featuresIn('CN', true);
expect(features.length).toBe(3);
expect(features[0].properties.wikidata).toBe('Q19188');
expect(features[1].properties.iso1A2).toBe('HK');
expect(features[2].properties.iso1A2).toBe('MO');
});
it('codes 830', () => {
let features = coder.featuresIn(830);
expect(features.length).toBe(6);
expect(features[0].properties.m49).toBe('830');
expect(features[1].properties.wikidata).toBe('Q179313');
expect(features[2].properties.wikidata).toBe('Q3311985');
expect(features[3].properties.m49).toBe('680');
expect(features[4].properties.iso1A2).toBe('GG');
expect(features[5].properties.iso1A2).toBe('JE');
});
it('codes 830, strict', () => {
let features = coder.featuresIn(830, true);
expect(features.length).toBe(5);
expect(features[0].properties.wikidata).toBe('Q179313');
expect(features[1].properties.wikidata).toBe('Q3311985');
expect(features[2].properties.m49).toBe('680');
expect(features[3].properties.iso1A2).toBe('GG');
expect(features[4].properties.iso1A2).toBe('JE');
});
it('codes "Crown Dependencies", strict', () => {
let features = coder.featuresIn('Crown Dependencies', true);
expect(features.length).toBe(6);
expect(features[0].properties.wikidata).toBe('Q179313');
expect(features[1].properties.wikidata).toBe('Q3311985');
expect(features[2].properties.m49).toBe('680');
expect(features[3].properties.iso1A2).toBe('GG');
expect(features[4].properties.iso1A2).toBe('IM');
expect(features[5].properties.iso1A2).toBe('JE');
});
it('codes "SBA", strict', () => {
let features = coder.featuresIn('SBA', true);
expect(features.length).toBe(2);
expect(features[0].properties.wikidata).toBe('Q9143535');
expect(features[1].properties.wikidata).toBe('Q9206745');
});
it('codes 🇸🇭 (Saint Helena)', () => {
let features = coder.featuresIn('🇸🇭');
expect(features.length).toBe(4);
expect(features[0].properties.iso1A2).toBe('SH');
expect(features[1].properties.wikidata).toBe('Q34497');
expect(features[2].properties.iso1A2).toBe('AC');
expect(features[3].properties.iso1A2).toBe('TA');
});
it('codes 🇸🇭 (Saint Helena), strict', () => {
let features = coder.featuresIn('🇸🇭', true);
expect(features.length).toBe(3);
expect(features[0].properties.wikidata).toBe('Q34497');
expect(features[1].properties.iso1A2).toBe('AC');
expect(features[2].properties.iso1A2).toBe('TA');
});
it('codes UN', () => {
let features = coder.featuresIn('UN').filter(function (feature) {
return feature.properties.level === 'country';
});
// there are exactly 193 UN member states as of August 2020
expect(features.length).toBe(193);
});
it('codes AQ', () => {
let features = coder.featuresIn('AQ');
expect(features.length).toBe(1);
expect(features[0].properties.iso1A2).toBe('AQ');
});
it('codes AQ, strict', () => {
expect(coder.featuresIn('AQ', true)).toStrictEqual([]);
});
it('does not code ABC', () => {
expect(coder.featuresIn('ABC')).toStrictEqual([]);
});
});
describe('aggregateFeature', () => {
it('returns aggregate for feature with geometry', () => {
expect(coder.aggregateFeature('TA')?.geometry.coordinates.length).toBe(1);
});
it('returns aggregate for feature without geometry', () => {
expect(coder.aggregateFeature('CN')?.geometry.coordinates.length).toBe(3);
expect(coder.aggregateFeature('SH')?.geometry.coordinates.length).toBe(3);
expect(coder.aggregateFeature('EU')?.geometry.coordinates.length).toBe(50);
});
it('returns null for invalid ID', () => {
expect(coder.aggregateFeature('ABC')).toBeNull();
});
});
describe('isIn', () => {
describe('by location', () => {
it('returns true: US location in US', () => {
expect(coder.isIn([-74, 40.6], 'US')).toBe(true);
});
it('returns false: US location in CH', () => {
expect(coder.isIn([-74, 40.6], 'CH')).toBe(false);
});
it('returns true: US location in 19 (Americas)', () => {
expect(coder.isIn([-74, 40.6], 19)).toBe(true);
});
it('returns true: US location in "021" (Northern America)', () => {
expect(coder.isIn([-74, 40.6], '021')).toBe(true);
});
it('returns true: US location in Q2 (World)', () => {
expect(coder.isIn([-74, 40.6], 'Q2')).toBe(true);
});
it('returns false: US location in Q15 (Africa)', () => {
expect(coder.isIn([-74, 40.6], 'Q15')).toBe(false);
});
});
describe('by code', () => {
it('returns true: US in US', () => {
expect(coder.isIn('US', 'US')).toBe(true);
});
it('returns false: US in CH', () => {
expect(coder.isIn('US', 'CH')).toBe(false);
});
it('returns false: USA in 19 (Americas)', () => {
expect(coder.isIn('USA', 19)).toBe(false);
});
it('returns false: US in "021" (Northern America)', () => {
expect(coder.isIn('US', '021')).toBe(false);
});
it('returns false: US location in Q15 (Africa)', () => {
expect(coder.isIn('US', 'Q15')).toBe(false);
});
it('returns true: CONUS in 19 (Americas)', () => {
expect(coder.isIn('CONUS', 19)).toBe(true);
});
it('returns true: CONUS in "021" (Northern America)', () => {
expect(coder.isIn('CONUS', '021')).toBe(true);
});
it('returns true: PR in US', () => {
expect(coder.isIn('PR', 'US')).toBe(true);
});
it('returns false: US in PR', () => {
expect(coder.isIn('US', 'PR')).toBe(false);
});
it('returns true: TA in SH', () => {
expect(coder.isIn('TA', 'SH')).toBe(true);
});
it('returns true: TA in GB', () => {
expect(coder.isIn('TA', 'GB')).toBe(true);
});
it('returns false: TA in EU', () => {
expect(coder.isIn('TA', 'EU')).toBe(false);
});
it('returns true: MP in "Q153732"', () => {
expect(coder.isIn('MP', 'Q153732')).toBe(true);
});
it('returns true: "Navassa Island" in "UM"', () => {
expect(coder.isIn('Navassa Island', 'UM')).toBe(true);
});
it('returns true: "Navassa Island" in "029" (Caribbean)', () => {
expect(coder.isIn('Navassa Island', '029')).toBe(true);
});
it('returns false: "UM" in "029"', () => {
expect(coder.isIn('UM', '029')).toBe(false);
});
it('returns true: "Midway Atoll" in "UM"', () => {
expect(coder.isIn('Midway Atoll', 'UM')).toBe(true);
});
it('returns true: "Midway Atoll" in "US"', () => {
expect(coder.isIn('Midway Atoll', 'US')).toBe(true);
});
it('returns false: "Midway Atoll" in "Hawaii"', () => {
expect(coder.isIn('Midway Atoll', 'Hawaii')).toBe(false);
});
it('returns true: GU in "Q153732" (Mariana Islands)', () => {
expect(coder.isIn('GU', 'Q153732')).toBe(true);
});
it('returns true: "GU" in US', () => {
expect(coder.isIn('GU', 'US')).toBe(true);
});
it('returns true: "Alaska" in "US"', () => {
expect(coder.isIn('Alaska', 'US')).toBe(true);
});
it('returns true: "Hawaii" in "US"', () => {
expect(coder.isIn('Hawaii', 'US')).toBe(true);
});
it('returns true: "CONUS" in "US"', () => {
expect(coder.isIn('CONUS', 'US')).toBe(true);
});
it('returns false: "US" in "CONUS"', () => {
expect(coder.isIn('US', 'CONUS')).toBe(false);
});
it('returns false: "Q153732" in "019" (Mariana Islands in Americas)', () => {
expect(coder.isIn('Q153732', '019')).toBe(false);
});
it('returns false: "Hawaii" in "019"', () => {
expect(coder.isIn('Hawaii', '019')).toBe(false);
});
it('returns true: "Alaska" in "019"', () => {
expect(coder.isIn('Alaska', '019')).toBe(true);
});
it('returns true: "021" in "019" (Northern America in Americas)', () => {
expect(coder.isIn('021', '019')).toBe(true);
});
it('returns true: "XK" in "europe"', () => {
expect(coder.isIn('XK', 'europe')).toBe(true);
});
it('returns true: "TW" in "Asia"', () => {
expect(coder.isIn('TW', 'Asia')).toBe(true);
});
it('returns true: 🇵🇷 in 🇺🇸', () => {
expect(coder.isIn('🇵🇷', '🇺🇸')).toBe(true);
});
it('returns true: "Bir Tawil" in "015"', () => {
expect(coder.isIn('Bir Tawil', '015')).toBe(true);
});
it('returns false: "Bir Tawil" in "Sudan"', () => {
expect(coder.isIn('Bir Tawil', 'Sudan')).toBe(false);
});
it('returns false: "Bir Tawil" in "Egypt"', () => {
expect(coder.isIn('Bir Tawil', 'Egypt')).toBe(false);
});
it('returns true: "Subsaharan africa" in "AFRICA"', () => {
expect(coder.isIn('Subsaharan africa', 'AFRICA')).toBe(true);
});
it('returns true: "Africa" in "World"', () => {
expect(coder.isIn('Africa', 'World')).toBe(true);
});
});
});
describe('isInEuropeanUnion', () => {
describe('by location', () => {
it('returns false for location in officially-assigned country, outside EU: New York, United States', () => {
expect(coder.isInEuropeanUnion([-74, 40.6])).toBe(false);
});
it('returns false for location in officially-assigned country, outside but surrounded by EU: Geneva, Switzerland', () => {
expect(coder.isInEuropeanUnion([6.1, 46.2])).toBe(false);
});
it('returns true for location in officially-assigned country, in EU, outside Eurozone: Copenhagen, Denmark', () => {
expect(coder.isInEuropeanUnion([12.59, 55.68])).toBe(true);
});
it('returns true for location in officially-assigned country, in EU, in Eurozone: Berlin, Germany', () => {
expect(coder.isInEuropeanUnion([13.4, 52.5])).toBe(true);
});
it('returns false for location in officially-assigned subfeature, oustide EU, of officially-assigned country, in EU: Isle of Man, United Kingdom', () => {
expect(coder.isInEuropeanUnion([-4.5, 54.2])).toBe(false);
});
it('returns true for location in exceptionally-reserved subfeature, in EU: Paris, Metropolitan France', () => {
expect(coder.isInEuropeanUnion([2.35, 48.85])).toBe(true);
});
it('returns false for location in exceptionally-reserved subfeature of officially-assigned subfeature, outside EU, of officially-assigned country, in EU: Tristan da Cunha, SH, UK', () => {
expect(coder.isInEuropeanUnion([-12.3, -37.1])).toBe(false);
});
it('returns false for location in user-assigned, de facto country, in Europe, outside EU: Kosovo', () => {
expect(coder.isInEuropeanUnion([21, 42.6])).toBe(false);
});
it('returns true for GeoJSON point feature in Germany', () => {
let pointFeature = {
type: 'Feature',
properties: null,
geometry: {
type: 'Point',
coordinates: tuple(13.4, 52.5)
}
};
expect(coder.isInEuropeanUnion(pointFeature)).toBe(true);
});
it('returns true for GeoJSON point geometry in Germany', () => {
let pointGeometry = {
type: 'Point',
coordinates: tuple(13.4, 52.5)
};
expect(coder.isInEuropeanUnion(pointGeometry)).toBe(true);
});
});
describe('by code', () => {
it('returns true for European Union itself: EU', () => {
expect(coder.isInEuropeanUnion('EU')).toBe(true);
});
it('returns true for countries inside the EU', () => {
expect(coder.isInEuropeanUnion('SE')).toBe(true);
expect(coder.isInEuropeanUnion('DE')).toBe(true);
expect(coder.isInEuropeanUnion('FX')).toBe(true);
expect(coder.isInEuropeanUnion('CY')).toBe(true);
});
it('returns true for certain territories of EU countries that are inside the EU', () => {
// Outermost regions
expect(coder.isInEuropeanUnion('OMR')).toBe(true);
expect(coder.isInEuropeanUnion('Q2914565')).toBe(true);
expect(coder.isInEuropeanUnion('Azores')).toBe(true);
expect(coder.isInEuropeanUnion('Madeira')).toBe(true);
expect(coder.isInEuropeanUnion('IC')).toBe(true);
expect(coder.isInEuropeanUnion('GF')).toBe(true);
expect(coder.isInEuropeanUnion('GP')).toBe(true);
expect(coder.isInEuropeanUnion('MQ')).toBe(true);
expect(coder.isInEuropeanUnion('YT')).toBe(true);
expect(coder.isInEuropeanUnion('RE')).toBe(true);
expect(coder.isInEuropeanUnion('MF')).toBe(true);
// special cases
expect(coder.isInEuropeanUnion('EA')).toBe(true);
expect(coder.isInEuropeanUnion('Ceuta')).toBe(true);
expect(coder.isInEuropeanUnion('Melilla')).toBe(true);
expect(coder.isInEuropeanUnion('AX')).toBe(true);
});
it('returns false for certain territories of EU countries outside of the EU', () => {
// Overseas countries and territories
expect(coder.isInEuropeanUnion('OCT')).toBe(false);
expect(coder.isInEuropeanUnion('Greenland')).toBe(false);
expect(coder.isInEuropeanUnion('CW')).toBe(false);
expect(coder.isInEuropeanUnion('Aruba')).toBe(false);
expect(coder.isInEuropeanUnion('SX')).toBe(false);
expect(coder.isInEuropeanUnion('BQ')).toBe(false);
expect(coder.isInEuropeanUnion('Bonaire')).toBe(false);
expect(coder.isInEuropeanUnion('Sint Eustatius')).toBe(false);
expect(coder.isInEuropeanUnion('Saba')).toBe(false);
expect(coder.isInEuropeanUnion('PF')).toBe(false);
expect(coder.isInEuropeanUnion('NC')).toBe(false);
expect(coder.isInEuropeanUnion('WF')).toBe(false);
expect(coder.isInEuropeanUnion('BL')).toBe(false);
expect(coder.isInEuropeanUnion('TF')).toBe(false);
// special case
expect(coder.isInEuropeanUnion('FO')).toBe(false);
});
it('returns false for countries outside the EU', () => {
expect(coder.isInEuropeanUnion('US')).toBe(false);
expect(coder.isInEuropeanUnion('RU')).toBe(false);
expect(coder.isInEuropeanUnion('NO')).toBe(false);
expect(coder.isInEuropeanUnion('CH')).toBe(false);
expect(coder.isInEuropeanUnion('CN')).toBe(false);
expect(coder.isInEuropeanUnion('XK')).toBe(false);
});
it('returns false for territories outside the EU', () => {
expect(coder.isInEuropeanUnion('IM')).toBe(false);
expect(coder.isInEuropeanUnion('TA')).toBe(false);
expect(coder.isInEuropeanUnion('HK')).toBe(false);
expect(coder.isInEuropeanUnion('VI')).toBe(false);
});
it('returns false for M49 super-region code: 150', () => {
expect(coder.isInEuropeanUnion('150')).toBe(false);
});
it('returns false for "world"', () => {
expect(coder.isInEuropeanUnion('world')).toBe(false);
});
it('returns null for unassigned alpha-2 code: AB', () => {
expect(coder.isInEuropeanUnion('AB')).toBe(null);
});
it('returns null for empty string', () => {
expect(coder.isInEuropeanUnion('')).toBe(null);
});
});
});
describe('isInUnitedNations', () => {
describe('by location', () => {
it('returns for coordinate location:', () => {
expect(coder.isInUnitedNations([-74, 40.6])).toBe(true); // New York, United States
expect(coder.isInUnitedNations([6.1, 46.2])).toBe(true); // Geneva, Switzerland
expect(coder.isInUnitedNations([12.59, 55.68])).toBe(true); // Copenhagen, Denmark
expect(coder.isInUnitedNations([13.4, 52.5])).toBe(true); // Berlin, Germany
expect(coder.isInUnitedNations([-4.5, 54.2])).toBe(true); // Isle of Man, United Kingdom
expect(coder.isInUnitedNations([2.35, 48.85])).toBe(true); // Metropolitan France
expect(coder.isInUnitedNations([-12.3, -37.1])).toBe(true); // Tristan da Cunha, SH, UK
expect(coder.isInUnitedNations([21, 42.6])).toBe(false); // Kosovo
});
it('returns for GeoJSON point feature', () => {
let pointFeature = {
type: 'Feature',
properties: null,
geometry: {
type: 'Point',
coordinates: tuple(13.4, 52.5) // Berlin, Germany
}
};
expect(coder.isInUnitedNations(pointFeature)).toBe(true);
});
it('returns for GeoJSON point geometry', () => {
let pointGeometry = {
type: 'Point',
coordinates: tuple(13.4, 52.5) // Berlin, Germany
};
expect(coder.isInUnitedNations(pointGeometry)).toBe(true);
});
});
describe('by code', () => {
it('returns true for features in UN', () => {
expect(coder.isInUnitedNations('EU')).toBe(true);
expect(coder.isInUnitedNations('SE')).toBe(true);
expect(coder.isInUnitedNations('DE')).toBe(true);
expect(coder.isInUnitedNations('FX')).toBe(true);
expect(coder.isInUnitedNations('CY')).toBe(true);
expect(coder.isInUnitedNations('OMR')).toBe(true);
expect(coder.isInUnitedNations('Q2914565')).toBe(true);
expect(coder.isInUnitedNations('Azores')).toBe(true);
expect(coder.isInUnitedNations('Madeira')).toBe(true);
expect(coder.isInUnitedNations('IC')).toBe(true);
expect(coder.isInUnitedNations('GF')).toBe(true);
expect(coder.isInUnitedNations('GP')).toBe(true);
expect(coder.isInUnitedNations('MQ')).toBe(true);
expect(coder.isInUnitedNations('YT')).toBe(true);
expect(coder.isInUnitedNations('RE')).toBe(true);
expect(coder.isInUnitedNations('MF')).toBe(true);
expect(coder.isInUnitedNations('EA')).toBe(true);
expect(coder.isInUnitedNations('Ceuta')).toBe(true);
expect(coder.isInUnitedNations('Melilla')).toBe(true);
expect(coder.isInUnitedNations('AX')).toBe(true);
expect(coder.isInUnitedNations('OCT')).toBe(true);
expect(coder.isInUnitedNations('Greenland')).toBe(true);
expect(coder.isInUnitedNations('CW')).toBe(true);
expect(coder.isInUnitedNations('Aruba')).toBe(true);
expect(coder.isInUnitedNations('SX')).toBe(true);
expect(coder.isInUnitedNations('BQ')).toBe(true);
expect(coder.isInUnitedNations('Bonaire')).toBe(true);
expect(coder.isInUnitedNations('Sint Eustatius')).toBe(true);
expect(coder.isInUnitedNations('Saba')).toBe(true);
expect(coder.isInUnitedNations('PF')).toBe(true);
expect(coder.isInUnitedNations('NC')).toBe(true);
expect(coder.isInUnitedNations('WF')).toBe(true);
expect(coder.isInUnitedNations('BL')).toBe(true);
expect(coder.isInUnitedNations('TF')).toBe(true);
expect(coder.isInUnitedNations('FO')).toBe(true);
expect(coder.isInUnitedNations('US')).toBe(true);
expect(coder.isInUnitedNations('RU')).toBe(true);
expect(coder.isInUnitedNations('NO')).toBe(true);
expect(coder.isInUnitedNations('CH')).toBe(true);
expect(coder.isInUnitedNations('CN')).toBe(true);
expect(coder.isInUnitedNations('IM')).toBe(true);
expect(coder.isInUnitedNations('TA')).toBe(true);
expect(coder.isInUnitedNations('HK')).toBe(true);
expect(coder.isInUnitedNations('VI')).toBe(true);
});
it('returns false for features not in UN', () => {
expect(coder.isInUnitedNations('XK')).toBe(false);
expect(coder.isInUnitedNations('PS')).toBe(false);
expect(coder.isInUnitedNations('TW')).toBe(false);
expect(coder.isInUnitedNations('AQ')).toBe(false);
expect(coder.isInUnitedNations('VA')).toBe(false);
expect(coder.isInUnitedNations('Western Sahara')).toBe(false);
expect(coder.isInUnitedNations('Northern Cyprus')).toBe(false);
expect(coder.isInUnitedNations('Bir Tawil')).toBe(false);
expect(coder.isInUnitedNations('150')).toBe(false);
expect(coder.isInUnitedNations('world')).toBe(false);
});
it('returns null for invalid codes', () => {
expect(coder.isInUnitedNations('AB')).toBe(null);
expect(coder.isInUnitedNations('')).toBe(null);
});
});
});
describe('driveSide', () => {
it('finds feature using right by location', () => {
expect(coder.driveSide([-74, 40.6])).toBe('right');
});
it('finds feature using left by location', () => {
expect(coder.driveSide([-4.5, 54.2])).toBe('left');
});
it('finds feature using right by identifier', () => {
expect(coder.driveSide('DE')).toBe('right');
expect(coder.driveSide('CA')).toBe('right');
expect(coder.driveSide('IO')).toBe('right');
expect(coder.driveSide('PR')).toBe('right');
expect(coder.driveSide('GI')).toBe('right');
expect(coder.driveSide('ES')).toBe('right');
expect(coder.driveSide('FR')).toBe('right');
expect(coder.driveSide('Midway Atoll')).toBe('right');
expect(coder.driveSide('Hawaii')).toBe('right');
expect(coder.driveSide('CONUS')).toBe('right');
});
it('finds feature using left by identifier', () => {
expect(coder.driveSide('VI')).toBe('left');
expect(coder.driveSide('GB-SCT')).toBe('left');
expect(coder.driveSide('IM')).toBe('left');
expect(coder.driveSide('IE')).toBe('left');
expect(coder.driveSide('IN')).toBe('left');
expect(coder.driveSide('AU')).toBe('left');
expect(coder.driveSide('NZ')).toBe('left');
expect(coder.driveSide('SH')).toBe('left');
expect(coder.driveSide('TA')).toBe('left');
expect(coder.driveSide('HMD')).toBe('left');
expect(coder.driveSide('JP')).toBe('left');
expect(coder.driveSide('ZA')).toBe('left');
expect(coder.driveSide('Great Britain')).toBe('left');
});
it('finds null for EU', () => {
expect(coder.driveSide('EU')).toBeNull();
});
it('finds null for 001', () => {
expect(coder.driveSide('001')).toBeNull();
});
it('finds null for North Pole', () => {
expect(coder.driveSide([0, 90])).toBeNull();
});
});
describe('roadSpeedUnit', () => {
it('finds feature using km/h by location', () => {
expect(coder.roadSpeedUnit([2.35, 48.85])).toBe('km/h');
});
it('finds feature using mph by location', () => {
expect(coder.roadSpeedUnit([-74, 40.6])).toBe('mph');
});
it('finds feature using km/h by identifier', () => {
expect(coder.roadSpeedUnit('IO')).toBe('km/h');
expect(coder.roadSpeedUnit('IE')).toBe('km/h');
expect(coder.roadSpeedUnit('AU')).toBe('km/h');
expect(coder.roadSpeedUnit('NZ')).toBe('km/h');
expect(coder.roadSpeedUnit('ES')).toBe('km/h');
expect(coder.roadSpeedUnit('TK')).toBe('km/h');
expect(coder.roadSpeedUnit('GI')).toBe('km/h');
expect(coder.roadSpeedUnit('FR')).toBe('km/h');
});
it('finds feature using mph by identifier', () => {
expect(coder.roadSpeedUnit('US')).toBe('mph');
expect(coder.roadSpeedUnit('CONUS')).toBe('mph');
expect(coder.roadSpeedUnit('US-AK')).toBe('mph');
expect(coder.roadSpeedUnit('Midway Atoll')).toBe('mph');
expect(coder.roadSpeedUnit('VI')).toBe('mph');
expect(coder.roadSpeedUnit('VG')).toBe('mph');
expect(coder.roadSpeedUnit('IM')).toBe('mph');
expect(coder.roadSpeedUnit('GB-ENG')).toBe('mph');
expect(coder.roadSpeedUnit('Great Britain')).toBe('mph');
});
it('finds null for 001', () => {
expect(coder.roadSpeedUnit('001')).toBeNull();
});
it('finds null for location of North Pole', () => {
expect(coder.roadSpeedUnit([0, 90])).toBeNull();
});
});
describe('roadHeightUnit', () => {
it('finds feature using m by location', () => {
expect(coder.roadHeightUnit([2.35, 48.85])).toBe('m');
});
it('finds feature using ft by location', () => {
expect(coder.roadHeightUnit([-74, 40.6])).toBe('ft');
});
it('finds feature using m by identifier', () => {
expect(coder.roadHeightUnit('IO')).toBe('m');
expect(coder.roadHeightUnit('IE')).toBe('m');
expect(coder.roadHeightUnit('AU')).toBe('m');
expect(coder.roadHeightUnit('NZ')).toBe('m');
expect(coder.roadHeightUnit('ES')).toBe('m');
expect(coder.roadHeightUnit('TK')).toBe('m');
expect(coder.roadHeightUnit('GI')).toBe('m');
expect(coder.roadHeightUnit('FR')).toBe('m');
expect(coder.roadHeightUnit('PR')).toBe('m');
expect(coder.roadHeightUnit('US-PR')).toBe('m');
});
it('finds feature using ft by identifier', () => {
expect(coder.roadHeightUnit('CONUS')).toBe('ft');
expect(coder.roadHeightUnit('US-AK')).toBe('ft');
expect(coder.roadHeightUnit('Midway Atoll')).toBe('ft');
expect(coder.roadHeightUnit('VI')).toBe('ft');
expect(coder.roadHeightUnit('VG')).toBe('ft');
expect(coder.roadHeightUnit('IM')).toBe('ft');
expect(coder.roadHeightUnit('GB-ENG')).toBe('ft');
expect(coder.roadHeightUnit('Great Britain')).toBe('ft');
});
it('finds null for 001', () => {
expect(coder.roadHeightUnit('001')).toBeNull();
});
it('finds null for location of North Pole', () => {
expect(coder.roadHeightUnit([0, 90])).toBeNull();
});
it('finds null for United States due to variation in Puerto Rico', () => {
expect(coder.roadHeightUnit('US')).toBeNull();
});
});
describe('callingCodes', () => {
it('finds one prefix for feature with one', () => {
expect(coder.callingCodes([2.35, 48.85])).toStrictEqual(['33']);
expect(coder.callingCodes('ES-CE')).toStrictEqual(['34']);
});
it('finds multiple prefixes for feature with multiple', () => {
expect(coder.callingCodes('PR')).toStrictEqual(['1 787', '1 939']);
});
it('finds none for feature without data', () => {
expect(coder.callingCodes('Bir Tawil')).toStrictEqual([]);
});
it('finds none for location of North Pole', () => {
expect(coder.callingCodes([0, 90])).toStrictEqual([]);
});
});
}); | the_stack |
export const syncRes = {
SaleToPOIResponse: {
MessageHeader: {
MessageCategory: "Payment",
MessageClass: "Service",
MessageType: "Response",
POIID: process.env.ADYEN_TERMINAL_POIID,
ProtocolVersion: "3.0",
SaleID: "001",
ServiceID: "001",
},
PaymentResponse: {
POIData: {
POIReconciliationID: "1000",
POITransactionID: {
TimeStamp: "2019-04-29T00:00:00.000Z",
TransactionID: "4r7i001556529591000.8515565295894301",
},
},
PaymentReceipt: [
{
DocumentQualifier: "CashierReceipt",
OutputContent: {
OutputFormat: "Text",
OutputText: [
{
CharacterStyle: "Bold",
EndOfLineFlag: true,
Text: "key=header1",
},
{
CharacterStyle: "Bold",
EndOfLineFlag: true,
Text: "key=header2",
},
{
CharacterStyle: "Bold",
EndOfLineFlag: true,
Text: "name=MERCHANT%20COPY&key=merchantTitle",
},
{
EndOfLineFlag: true,
Text: "key=filler",
},
{
EndOfLineFlag: true,
Text: "name=Date&value=29%2f04%2f19&key=txdate",
},
{
EndOfLineFlag: true,
Text: "name=Time&value=10%3a19%3a51&key=txtime",
},
{
EndOfLineFlag: true,
Text: "key=filler",
},
{
EndOfLineFlag: true,
Text: "name=Card&value=%2a%2a%2a%2a%2a%2a%2a%2a%2a%2a%2a%2a3511&key=pan",
},
{
EndOfLineFlag: true,
Text: "name=Pref.%20name&value=MCC%20351%20v1%202&key=preferredName",
},
{
EndOfLineFlag: true,
Text: "name=Card%20type&value=mc&key=cardType",
},
{
EndOfLineFlag: true,
Text: "name=Payment%20method&value=mc&key=paymentMethod",
},
{
EndOfLineFlag: true,
Text: "name=Payment%20variant&value=mc&key=paymentMethodVariant",
},
{
EndOfLineFlag: true,
Text: "name=Entry%20mode&value=Contactless%20swipe&key=posEntryMode",
},
{
EndOfLineFlag: true,
Text: "key=filler",
},
{
EndOfLineFlag: true,
Text: "name=AID&value=A0000000041010&key=aid",
},
{
EndOfLineFlag: true,
Text: "name=MID&value=1000&key=mid",
},
{
EndOfLineFlag: true,
Text: "name=TID&value=P400Plus-275039202&key=tid",
},
{
EndOfLineFlag: true,
Text: "name=PTID&value=75039202&key=ptid",
},
{
EndOfLineFlag: true,
Text: "key=filler",
},
{
EndOfLineFlag: true,
Text: "name=Auth.%20code&value=123456&key=authCode",
},
{
EndOfLineFlag: true,
Text: "name=Tender&value=4r7i001556529591000&key=txRef",
},
{
EndOfLineFlag: true,
Text: "name=Reference&value=003&key=mref",
},
{
EndOfLineFlag: true,
Text: "key=filler",
},
{
EndOfLineFlag: true,
Text: "name=Type&value=GOODS_SERVICES&key=txtype",
},
{
CharacterStyle: "Bold",
EndOfLineFlag: true,
Text: "name=TOTAL&value=%e2%82%ac%c2%a01.00&key=totalAmount",
},
{
EndOfLineFlag: true,
Text: "key=filler",
},
{
CharacterStyle: "Bold",
EndOfLineFlag: true,
Text: "name=APPROVED&key=approved",
},
],
},
RequiredSignatureFlag: false,
},
{
DocumentQualifier: "CustomerReceipt",
OutputContent: {
OutputFormat: "Text",
OutputText: [
{
CharacterStyle: "Bold",
EndOfLineFlag: true,
Text: "key=header1",
},
{
CharacterStyle: "Bold",
EndOfLineFlag: true,
Text: "key=header2",
},
{
CharacterStyle: "Bold",
EndOfLineFlag: true,
Text: "name=CARDHOLDER%20COPY&key=cardholderHeader",
},
{
EndOfLineFlag: true,
Text: "key=filler",
},
{
EndOfLineFlag: true,
Text: "name=Date&value=29%2f04%2f19&key=txdate",
},
{
EndOfLineFlag: true,
Text: "name=Time&value=10%3a19%3a51&key=txtime",
},
{
EndOfLineFlag: true,
Text: "key=filler",
},
{
EndOfLineFlag: true,
Text: "name=Card&value=%2a%2a%2a%2a%2a%2a%2a%2a%2a%2a%2a%2a3511&key=pan",
},
{
EndOfLineFlag: true,
Text: "name=Pref.%20name&value=MCC%20351%20v1%202&key=preferredName",
},
{
EndOfLineFlag: true,
Text: "name=Card%20type&value=mc&key=cardType",
},
{
EndOfLineFlag: true,
Text: "name=Payment%20method&value=mc&key=paymentMethod",
},
{
EndOfLineFlag: true,
Text: "name=Payment%20variant&value=mc&key=paymentMethodVariant",
},
{
EndOfLineFlag: true,
Text: "name=Entry%20mode&value=Contactless%20swipe&key=posEntryMode",
},
{
EndOfLineFlag: true,
Text: "key=filler",
},
{
EndOfLineFlag: true,
Text: "name=AID&value=A0000000041010&key=aid",
},
{
EndOfLineFlag: true,
Text: "name=MID&value=1000&key=mid",
},
{
EndOfLineFlag: true,
Text: "name=TID&value=P400Plus-275039202&key=tid",
},
{
EndOfLineFlag: true,
Text: "name=PTID&value=75039202&key=ptid",
},
{
EndOfLineFlag: true,
Text: "key=filler",
},
{
EndOfLineFlag: true,
Text: "name=Auth.%20code&value=123456&key=authCode",
},
{
EndOfLineFlag: true,
Text: "name=Tender&value=4r7i001556529591000&key=txRef",
},
{
EndOfLineFlag: true,
Text: "name=Reference&value=003&key=mref",
},
{
EndOfLineFlag: true,
Text: "key=filler",
},
{
EndOfLineFlag: true,
Text: "name=Type&value=GOODS_SERVICES&key=txtype",
},
{
CharacterStyle: "Bold",
EndOfLineFlag: true,
Text: "name=TOTAL&value=%e2%82%ac%c2%a01.00&key=totalAmount",
},
{
EndOfLineFlag: true,
Text: "key=filler",
},
{
CharacterStyle: "Bold",
EndOfLineFlag: true,
Text: "name=APPROVED&key=approved",
},
{
EndOfLineFlag: true,
Text: "key=filler",
},
{
EndOfLineFlag: true,
Text: "name=Please%20retain%20for%20your%20records&key=retain",
},
{
EndOfLineFlag: true,
Text: "name=Thank%20you&key=thanks",
},
],
},
RequiredSignatureFlag: false,
},
],
PaymentResult: {
AmountsResp: {
AuthorizedAmount: 1,
Currency: "EUR",
},
OnlineFlag: true,
PaymentAcquirerData: {
AcquirerPOIID: "P400Plus-123456789",
AcquirerTransactionID: {
TimeStamp: "2019-04-29T09:19:51.000Z",
TransactionID: "8515565295894301",
},
ApprovalCode: "123456",
MerchantID: "TestMerchant",
},
PaymentInstrumentData: {
CardData: {
EntryMode: [
"Tapped",
],
MaskedPan: "411111 **** 1111",
PaymentBrand: "mc",
SensitiveCardData: {
ExpiryDate: "1225",
},
},
PaymentInstrumentType: "Card",
},
},
Response: {
AdditionalResponse: `tid=75039202&AID=A0000000041010&transactionType=GOODS_SERVICES&backendGiftcardIndi
cator=false&expiryYear=2025&acquirerAccountCode=TestPmmAcquirerAccount&alias=M900978995070104&posOrigin
alAmountCurrency=EUR&giftcardIndicator=false&authorisedAmountValue=100&pspReference=8515565295894301&pa
ymentMethodVariant=mc&cardHolderName=N%2fA&refusalReasonRaw=APPROVED&authorisationMid=1000&expiryDate=1
2%2f2025&applicationPreferredName=MCC%20351%20v1%202&acquirerCode=TestPmmAcquirer&txtime=10%3a19%3a51&i
so8601TxDate=2019-04-29T09%3a19%3a51.0000000%2b0000&cardType=mc&posOriginalAmountValue=100&offline=fals
e&aliasType=Default&txdate=29-04-2019&paymentMethod=mc&cvcResult=0%20Unknown&avsResult=0%20Unknown&mid=
1000&merchantReference=003&transactionReferenceNumber=8515565295894301&expiryMonth=12&cardSummary=3511&
posTotalAmountValue=100&posAuthAmountCurrency=EUR&cardHolderVerificationMethodResults=3F0300&authCode=1
23456&shopperCountry=NL&posEntryMode=CLESS_SWIPE&cardScheme=mc&cardBin=541333&posAuthAmountValue=100`,
Result: "Success",
},
SaleData: {
SaleTransactionID: {
TimeStamp: "2019-04-29T00:00:00.000Z",
TransactionID: "001",
},
},
},
},
};
export const syncRefund = {
SaleToPOIResponse: {
MessageHeader: {
MessageCategory: "Payment",
MessageClass: "Service",
MessageType: "Response",
POIID: process.env.ADYEN_TERMINAL_POIID,
ProtocolVersion: "3.0",
SaleID: "001",
ServiceID: "001",
},
ReversalResponse: {
Response: {
Result: "Success"
}
}
}
}; | the_stack |
import { TestBed } from '@angular/core/testing';
import { CxEvent, EventService } from '@spartacus/core';
import { defer, of, Subject } from 'rxjs';
import { take } from 'rxjs/operators';
import { Query, QueryService, QueryState } from './query.service';
class ReloadEvent extends CxEvent {
static readonly type = 'TestingEvent';
}
describe('QueryService', () => {
let service: QueryService;
let eventService: EventService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [EventService],
});
service = TestBed.inject(QueryService);
eventService = TestBed.inject(EventService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('create should return query', () => {
const query = service.create(() => of('value'));
expect(query.get).toBeDefined();
expect(query.getState).toBeDefined();
});
describe('query', () => {
let query: Query<string>;
let loadingStream$: Subject<string>;
let resetTrigger$: Subject<boolean>;
let loaderFactoryCalls: number;
beforeEach(() => {
resetTrigger$ = new Subject<boolean>();
loaderFactoryCalls = 0;
query = service.create(
() =>
defer(() => {
loaderFactoryCalls++;
return loadingStream$.pipe(take(1));
}),
{
reloadOn: [ReloadEvent],
resetOn: [resetTrigger$.asObservable()],
}
);
loadingStream$ = new Subject<string>();
});
it('should not load if not subscribed', () => {
const data = query.get();
expect(data).toBeDefined();
expect(loaderFactoryCalls).toBe(0);
});
it('should load on subscription', (done) => {
const state$ = query.getState();
const emissions: QueryState<string>[] = [];
state$.pipe(take(2)).subscribe((state) => {
emissions.push(state);
if (emissions.length === 2) {
expect(loaderFactoryCalls).toBe(1);
expect(emissions).toEqual([
// first emission should already present loading state
{
loading: true,
error: false,
data: undefined,
},
{
loading: false,
error: false,
data: 'value',
},
]);
done();
}
});
loadingStream$.next('value');
});
it('should return state from previous subscription after resubscription', (done) => {
const state$ = query.getState();
const emissions: QueryState<string>[] = [];
state$.pipe(take(2)).subscribe((state) => {
emissions.push(state);
});
loadingStream$.next('value');
state$.pipe(take(1)).subscribe((state) => {
emissions.push(state);
if (emissions.length === 3) {
expect(emissions).toEqual([
{
loading: true,
error: false,
data: undefined,
},
{
loading: false,
error: false,
data: 'value',
},
// unsubscribe happened (0 subscribers)
// subscribe happened once again
{
loading: false,
error: false,
data: 'value',
},
]);
done();
}
});
});
it('should load once again if it was cancelled by unsubscribe', (done) => {
const state$ = query.getState();
const emissions: QueryState<string>[] = [];
state$.pipe(take(1)).subscribe((state) => {
emissions.push(state);
});
loadingStream$.next('value');
state$.pipe(take(2)).subscribe((state) => {
emissions.push(state);
if (emissions.length === 3) {
expect(loaderFactoryCalls).toBe(2);
expect(emissions).toEqual([
{
loading: true,
error: false,
data: undefined,
},
// unsubscribe happened (0 subscribers)
// subscribe happened once again
{
loading: true,
error: false,
data: undefined,
},
{
loading: false,
error: false,
data: 'new-value',
},
]);
done();
}
});
loadingStream$.next('new-value');
});
it('should clear value on error', (done) => {
const state$ = query.getState();
const emissions: QueryState<string>[] = [];
state$.pipe(take(4)).subscribe((state) => {
emissions.push(state);
if (emissions.length === 4) {
expect(emissions).toEqual([
{
loading: true,
error: false,
data: undefined,
},
{
loading: false,
error: false,
data: 'value',
},
// reload trigger happened
{
loading: true,
error: false,
data: 'value',
},
// loaderFactory throws error
{
loading: false,
error: jasmine.any(Error),
data: undefined,
},
]);
done();
}
});
loadingStream$.next('value');
eventService.dispatch(new ReloadEvent());
loadingStream$.error(new Error('error'));
});
it('should clear error on successful emission', (done) => {
const state$ = query.getState();
const emissions: QueryState<string>[] = [];
state$.pipe(take(4)).subscribe((state) => {
emissions.push(state);
if (emissions.length === 4) {
expect(emissions).toEqual([
{
loading: true,
error: false,
data: undefined,
},
// loaderFactory throws error
{
loading: false,
error: jasmine.any(Error),
data: undefined,
},
// reload trigger happened
{
loading: true,
error: jasmine.any(Error),
data: undefined,
},
// loaderFactory returns value
{
loading: false,
error: false,
data: 'value',
},
]);
done();
}
});
loadingStream$.error(new Error('error'));
loadingStream$ = new Subject<string>();
eventService.dispatch(new ReloadEvent());
loadingStream$.next('value');
});
it('should not call multiple times loaderFactory on multiple subscriptions', () => {
const state$ = query.getState();
state$.pipe(take(2)).subscribe();
state$.pipe(take(2)).subscribe();
loadingStream$.next('test-value');
expect(loaderFactoryCalls).toEqual(1);
});
describe('get', () => {
it('should return value property from getState', (done) => {
const data$ = query.get();
const emissions: (string | undefined)[] = [];
data$.pipe(take(3)).subscribe((state) => {
emissions.push(state);
if (emissions.length === 3) {
// should not emit same values multiple times
expect(emissions).toEqual([undefined, 'value', 'different-value']);
done();
}
});
loadingStream$.next('value');
eventService.dispatch(new ReloadEvent());
loadingStream$.next('value');
eventService.dispatch(new ReloadEvent());
loadingStream$.next('different-value');
});
});
describe('reload trigger', () => {
it('should reload data immediately when there are active query subscriptions', (done) => {
const state$ = query.getState();
const emissions: QueryState<string>[] = [];
state$.pipe(take(4)).subscribe((state) => {
emissions.push(state);
if (emissions.length === 4) {
expect(loaderFactoryCalls).toBe(2);
expect(emissions).toEqual([
{
loading: true,
error: false,
data: undefined,
},
{
loading: false,
error: false,
data: 'value',
},
// reload trigger happened
{
loading: true,
error: false,
data: 'value', // value is not cleared on reload!
},
{
loading: false,
error: false,
data: 'new-value',
},
]);
done();
}
});
loadingStream$.next('value');
eventService.dispatch(new ReloadEvent());
loadingStream$.next('new-value');
});
it('should reload data after resubscription when there was 0 subscribers during emission', (done) => {
const state$ = query.getState();
const emissions: QueryState<string>[] = [];
state$.pipe(take(2)).subscribe((state) => {
emissions.push(state);
});
loadingStream$.next('value');
eventService.dispatch(new ReloadEvent());
state$.pipe(take(2)).subscribe((state) => {
emissions.push(state);
if (emissions.length === 4) {
expect(loaderFactoryCalls).toBe(2);
expect(emissions).toEqual([
{
loading: true,
error: false,
data: undefined,
},
{
loading: false,
error: false,
data: 'value',
},
// unsubscribe happened (0 subscribers)
// reload trigger happened
// subscribe happened once again
{
loading: true,
error: false,
data: 'value',
},
{
loading: false,
error: false,
data: 'new-value',
},
]);
done();
}
});
loadingStream$.next('new-value');
});
});
describe('reset trigger', () => {
it('should clear state and reload data immediately when there are active query subscriptions', (done) => {
const state$ = query.getState();
const emissions: QueryState<string>[] = [];
state$.pipe(take(4)).subscribe((state) => {
emissions.push(state);
if (emissions.length === 4) {
expect(loaderFactoryCalls).toBe(2);
expect(emissions).toEqual([
{
loading: true,
error: false,
data: undefined,
},
{
loading: false,
error: false,
data: 'value',
},
// reset trigger happened
{
loading: true,
error: false,
data: undefined, // value needs to be cleared on reset!
},
{
loading: false,
error: false,
data: 'new-value',
},
]);
done();
}
});
loadingStream$.next('value');
resetTrigger$.next(true);
loadingStream$.next('new-value');
});
it('should clear state instantly and reload data after resubscription when there was 0 subscribers during emission', (done) => {
const state$ = query.getState();
const emissions: QueryState<string>[] = [];
state$.pipe(take(2)).subscribe((state) => {
emissions.push(state);
});
loadingStream$.next('value');
resetTrigger$.next(true);
state$.pipe(take(2)).subscribe((state) => {
emissions.push(state);
if (emissions.length === 4) {
expect(loaderFactoryCalls).toBe(2);
expect(emissions).toEqual([
{
loading: true,
error: false,
data: undefined,
},
{
loading: false,
error: false,
data: 'value',
},
// unsubscribe happened (0 subscribers)
// reset trigger happened
// subscribe happened once again
{
loading: true,
error: false,
data: undefined,
},
{
loading: false,
error: false,
data: 'new-value',
},
]);
done();
}
});
loadingStream$.next('new-value');
});
});
});
}); | the_stack |
import { AffectedTaskOccurrence } from "../../../Enumerations/AffectedTaskOccurrence";
import { ConversationFlagStatus } from "../../../Enumerations/ConversationFlagStatus";
import { ConversationId } from "../../../ComplexProperties/ConversationId";
import { DateTime } from "../../../DateTime";
import { DeleteMode } from "../../../Enumerations/DeleteMode";
import { ExchangeService } from "../../ExchangeService";
import { ExchangeVersion } from "../../../Enumerations/ExchangeVersion";
import { ExtendedPropertyCollection } from "../../../ComplexProperties/ExtendedPropertyCollection";
import { Flag } from "../../../ComplexProperties/Flag";
import { FolderId } from "../../../ComplexProperties/FolderId";
import { Guid } from "../../../Guid";
import { IconIndex } from "../../../Enumerations/IconIndex";
import { Importance } from "../../../Enumerations/Importance";
import { IOutParam } from "../../../Interfaces/IOutParam";
import { ItemFlagStatus } from "../../../Enumerations/ItemFlagStatus";
import { ItemIdCollection } from "../../../ComplexProperties/ItemIdCollection";
import { KeyValuePair } from "../../../AltDictionary";
import { NotSupportedException } from "../../../Exceptions/NotSupportedException";
import { Promise } from "../../../Promise";
import { PropertyDefinition } from "../../../PropertyDefinitions/PropertyDefinition";
import { PropertySet } from "../../PropertySet";
import { RetentionType } from "../../../Enumerations/RetentionType";
import { Schemas } from "../Schemas/Schemas";
import { SendCancellationsMode } from "../../../Enumerations/SendCancellationsMode";
import { ServiceObjectSchema } from "../Schemas/ServiceObjectSchema";
import { StringHelper } from "../../../ExtensionMethods";
import { StringList } from "../../../ComplexProperties/StringList";
import { XmlElementNames } from "../../XmlElementNames";
import { ServiceObject } from "../ServiceObject";
/**
* Represents a collection of Conversation related properties.
* Properties available on this object are defined in the ConversationSchema class.
*/
export class Conversation extends ServiceObject {
/**
* Gets the Id of this Conversation.
*/
get Id(): ConversationId {
return <ConversationId>this.PropertyBag._getItem(this.GetIdPropertyDefinition());
}
/**
* Gets the topic of this Conversation.
*/
get Topic(): string {
var returnValue: IOutParam<string> = { outValue: StringHelper.Empty };
// This property need not be present hence the property bag may not contain it.
// Check for the presence of this property before accessing it.
if (this.PropertyBag.Contains(Schemas.ConversationSchema.Topic)) {
this.PropertyBag.TryGetPropertyAs<string>(Schemas.ConversationSchema.Topic, returnValue);
}
return returnValue.outValue;
}
/**
* Gets a list of all the people who have received messages in this conversation in the current folder only.
*/
get UniqueRecipients(): StringList {
return <StringList>this.PropertyBag._getItem(Schemas.ConversationSchema.UniqueRecipients);
}
/**
* Gets a list of all the people who have received messages in this conversation across all folders in the mailbox.
*/
get GlobalUniqueRecipients(): StringList {
return <StringList>this.PropertyBag._getItem(Schemas.ConversationSchema.GlobalUniqueRecipients);
}
/**
* Gets a list of all the people who have sent messages that are currently unread in this conversation in the current folder only.
*/
get UniqueUnreadSenders(): StringList {
var unreadSenders: IOutParam<StringList> = { outValue: null };
// This property need not be present hence the property bag may not contain it.
// Check for the presence of this property before accessing it.
if (this.PropertyBag.Contains(Schemas.ConversationSchema.UniqueUnreadSenders)) {
this.PropertyBag.TryGetPropertyAs<StringList>(Schemas.ConversationSchema.UniqueUnreadSenders, unreadSenders);
}
return unreadSenders.outValue;
}
/**
* Gets a list of all the people who have sent messages that are currently unread in this conversation across all folders in the mailbox.
*/
get GlobalUniqueUnreadSenders(): StringList {
var unreadSenders: IOutParam<StringList> = { outValue: null };
// This property need not be present hence the property bag may not contain it.
// Check for the presence of this property before accessing it.
if (this.PropertyBag.Contains(Schemas.ConversationSchema.GlobalUniqueUnreadSenders)) {
this.PropertyBag.TryGetPropertyAs<StringList>(Schemas.ConversationSchema.GlobalUniqueUnreadSenders, unreadSenders);
}
return unreadSenders.outValue;
}
/**
* Gets a list of all the people who have sent messages in this conversation in the current folder only.
*/
get UniqueSenders(): StringList {
return <StringList>this.PropertyBag._getItem(Schemas.ConversationSchema.UniqueSenders);
}
/**
* Gets a list of all the people who have sent messages in this conversation across all folders in the mailbox.
*/
get GlobalUniqueSenders(): StringList {
return <StringList>this.PropertyBag._getItem(Schemas.ConversationSchema.GlobalUniqueSenders);
}
/**
* Gets the delivery time of the message that was last received in this conversation in the current folder only.
*/
get LastDeliveryTime(): DateTime {
return <DateTime>this.PropertyBag._getItem(Schemas.ConversationSchema.LastDeliveryTime);
}
/**
* Gets the delivery time of the message that was last received in this conversation across all folders in the mailbox.
*/
get GlobalLastDeliveryTime(): DateTime {
return <DateTime>this.PropertyBag._getItem(Schemas.ConversationSchema.GlobalLastDeliveryTime);
}
/**
* Gets a list summarizing the categories stamped on messages in this conversation, in the current folder only.
*/
get Categories(): StringList {
var returnValue: IOutParam<StringList> = { outValue: null };
// This property need not be present hence the property bag may not contain it.
// Check for the presence of this property before accessing it.
if (this.PropertyBag.Contains(Schemas.ConversationSchema.Categories)) {
this.PropertyBag.TryGetPropertyAs<StringList>(Schemas.ConversationSchema.Categories, returnValue);
}
return returnValue.outValue;
}
/**
* Gets a list summarizing the categories stamped on messages in this conversation, across all folders in the mailbox.
*/
get GlobalCategories(): StringList {
var returnValue: IOutParam<StringList> = { outValue: null };
// This property need not be present hence the property bag may not contain it.
// Check for the presence of this property before accessing it.
if (this.PropertyBag.Contains(Schemas.ConversationSchema.GlobalCategories)) {
this.PropertyBag.TryGetPropertyAs<StringList>(Schemas.ConversationSchema.GlobalCategories, returnValue);
}
return returnValue.outValue;
}
/**
* Gets the flag status for this conversation, calculated by aggregating individual messages flag status in the current folder.
*/
get FlagStatus(): ConversationFlagStatus {
var returnValue: IOutParam<ConversationFlagStatus> = { outValue: null };
// This property need not be present hence the property bag may not contain it.
// Check for the presence of this property before accessing it.
if (this.PropertyBag.Contains(Schemas.ConversationSchema.FlagStatus)) {
this.PropertyBag.TryGetPropertyAs<ConversationFlagStatus>(Schemas.ConversationSchema.FlagStatus, returnValue);
}
return returnValue.outValue;
}
/**
* Gets the flag status for this conversation, calculated by aggregating individual messages flag status across all folders in the mailbox.
*/
get GlobalFlagStatus(): ConversationFlagStatus {
var returnValue: IOutParam<ConversationFlagStatus> = { outValue: null };
// This property need not be present hence the property bag may not contain it.
// Check for the presence of this property before accessing it.
if (this.PropertyBag.Contains(Schemas.ConversationSchema.GlobalFlagStatus)) {
this.PropertyBag.TryGetPropertyAs<ConversationFlagStatus>(Schemas.ConversationSchema.GlobalFlagStatus, returnValue);
}
return returnValue.outValue;
}
/**
* Gets a value indicating if at least one message in this conversation, in the current folder only, has an attachment.
*/
get HasAttachments(): boolean {
return <boolean>this.PropertyBag._getItem(Schemas.ConversationSchema.HasAttachments);
}
/**
* Gets a value indicating if at least one message in this conversation, across all folders in the mailbox, has an attachment.
*/
get GlobalHasAttachments(): boolean {
return <boolean>this.PropertyBag._getItem(Schemas.ConversationSchema.GlobalHasAttachments);
}
/**
* Gets the total number of messages in this conversation in the current folder only.
*/
get MessageCount(): number {
return <number>this.PropertyBag._getItem(Schemas.ConversationSchema.MessageCount);
}
/**
* Gets the total number of messages in this conversation across all folders in the mailbox.
*/
get GlobalMessageCount(): number {
return <number>this.PropertyBag._getItem(Schemas.ConversationSchema.GlobalMessageCount);
}
/**
* Gets the total number of unread messages in this conversation in the current folder only.
*/
get UnreadCount(): number {
var returnValue: IOutParam<number> = { outValue: 0 };
// This property need not be present hence the property bag may not contain it.
// Check for the presence of this property before accessing it.
if (this.PropertyBag.Contains(Schemas.ConversationSchema.UnreadCount)) {
this.PropertyBag.TryGetPropertyAs<number>(Schemas.ConversationSchema.UnreadCount, returnValue);
}
return returnValue.outValue;
}
/**
* Gets the total number of unread messages in this conversation across all folders in the mailbox.
*/
get GlobalUnreadCount(): number {
var returnValue: IOutParam<number> = { outValue: 0 };
// This property need not be present hence the property bag may not contain it.
// Check for the presence of this property before accessing it.
if (this.PropertyBag.Contains(Schemas.ConversationSchema.GlobalUnreadCount)) {
this.PropertyBag.TryGetPropertyAs<number>(Schemas.ConversationSchema.GlobalUnreadCount, returnValue);
}
return returnValue.outValue;
}
/**
* Gets the size of this conversation, calculated by adding the sizes of all messages in the conversation in the current folder only.
*/
get Size(): number {
return <number>this.PropertyBag._getItem(Schemas.ConversationSchema.Size);
}
/**
* Gets the size of this conversation, calculated by adding the sizes of all messages in the conversation across all folders in the mailbox.
*/
get GlobalSize(): number {
return <number>this.PropertyBag._getItem(Schemas.ConversationSchema.GlobalSize);
}
/**
* Gets a list summarizing the classes of the items in this conversation, in the current folder only.
*/
get ItemClasses(): StringList {
return <StringList>this.PropertyBag._getItem(Schemas.ConversationSchema.ItemClasses);
}
/**
* Gets a list summarizing the classes of the items in this conversation, across all folders in the mailbox.
*/
get GlobalItemClasses(): StringList {
return <StringList>this.PropertyBag._getItem(Schemas.ConversationSchema.GlobalItemClasses);
}
/**
* Gets the importance of this conversation, calculated by aggregating individual messages importance in the current folder only.
*/
get Importance(): Importance {
return <Importance>this.PropertyBag._getItem(Schemas.ConversationSchema.Importance);
}
/**
* Gets the importance of this conversation, calculated by aggregating individual messages importance across all folders in the mailbox.
*/
get GlobalImportance(): Importance {
return <Importance>this.PropertyBag._getItem(Schemas.ConversationSchema.GlobalImportance);
}
/**
* Gets the Ids of the messages in this conversation, in the current folder only.
*/
get ItemIds(): ItemIdCollection {
return <ItemIdCollection>this.PropertyBag._getItem(Schemas.ConversationSchema.ItemIds);
}
/**
* Gets the Ids of the messages in this conversation, across all folders in the mailbox.
*/
get GlobalItemIds(): ItemIdCollection {
return <ItemIdCollection>this.PropertyBag._getItem(Schemas.ConversationSchema.GlobalItemIds);
}
/**
* Gets the date and time this conversation was last modified.
*/
get LastModifiedTime(): DateTime {
return <DateTime>this.PropertyBag._getItem(Schemas.ConversationSchema.LastModifiedTime);
}
/**
* Gets the conversation instance key.
*/
get InstanceKey(): number[] {
return <number[]>this.PropertyBag._getItem(Schemas.ConversationSchema.InstanceKey);
}
/**
* Gets the conversation Preview.
*/
get Preview(): string {
return <string>this.PropertyBag._getItem(Schemas.ConversationSchema.Preview);
}
/**
* Gets the conversation IconIndex.
*/
get IconIndex(): IconIndex {
return <IconIndex>this.PropertyBag._getItem(Schemas.ConversationSchema.IconIndex);
}
/**
* Gets the conversation global IconIndex.
*/
get GlobalIconIndex(): IconIndex {
return <IconIndex>this.PropertyBag._getItem(Schemas.ConversationSchema.GlobalIconIndex);
}
/**
* Gets the draft item ids.
*/
get DraftItemIds(): ItemIdCollection {
return <ItemIdCollection>this.PropertyBag._getItem(Schemas.ConversationSchema.DraftItemIds);
}
/**
* Gets a value indicating if at least one message in this conversation, in the current folder only, is an IRM.
*/
get HasIrm(): boolean {
return <boolean>this.PropertyBag._getItem(Schemas.ConversationSchema.HasIrm);
}
/**
* Gets a value indicating if at least one message in this conversation, across all folders in the mailbox, is an IRM.
*/
get GlobalHasIrm(): boolean {
return <boolean>this.PropertyBag._getItem(Schemas.ConversationSchema.GlobalHasIrm);
}
/**
* @internal Initializes an unsaved local instance of **Conversation** class.
*
* @param {ExchangeService} service The ExchangeService object to which the item will be bound.
*/
constructor(service: ExchangeService) {
super(service);
}
/**
* Clear flags for conversation items. Calling this method results in a call to EWS.
*
* @param {FolderId} contextFolderId The Id of the folder items must belong to in order to be unflagged. If contextFolderId is null, flags for items in conversation across the entire mailbox are cleared.
* @return {Promise<void>} Promise
*/
ClearItemFlags(contextFolderId: FolderId): Promise<void> {
let flag: Flag = new Flag();
flag.FlagStatus = ItemFlagStatus.NotFlagged;
return this.Service.SetFlagStatusForItemsInConversations(
[{ key: this.Id, value: this.GlobalLastDeliveryTime }],
contextFolderId,
flag).then((responses) => {
responses.__thisIndexer(0).ThrowIfNecessary();
});
}
/**
* Copies items in the specified conversation to a specific folder. Calling this method results in a call to EWS.
*
* @param {FolderId} contextFolderId The Id of the folder items must belong to in order to be copied. If contextFolderId is null, items across the entire mailbox are copied.
* @param {FolderId} destinationFolderId The Id of the destination folder.
* @return {Promise<void>} Promise
*/
CopyItemsInConversation(contextFolderId: FolderId, destinationFolderId: FolderId): Promise<void> {
return this.Service.CopyItemsInConversations(
[{ key: this.Id, value: this.GlobalLastDeliveryTime }],
contextFolderId,
destinationFolderId).then((responses) => {
responses.__thisIndexer(0).ThrowIfNecessary();
});
}
/**
* Deletes items in the specified conversation.
* Calling this method results in a call to EWS.
*
* @param {FolderId} contextFolderId The Id of the folder items must belong to in order to be deleted. If contextFolderId is null, items across the entire mailbox are deleted.
* @param {DeleteMode} deleteMode The deletion mode.
* @return {Promise<void>} Promise
*/
DeleteItems(contextFolderId: FolderId, deleteMode: DeleteMode): Promise<void> {
return this.Service.DeleteItemsInConversations(
[{ key: this.Id, value: this.GlobalLastDeliveryTime }],
contextFolderId,
deleteMode).then((responses) => {
responses.__thisIndexer(0).ThrowIfNecessary();
});
}
/**
* Sets up a conversation so that any item received within that conversation is no longer categorized.
* Calling this method results in a call to EWS.
*
* @param {boolean} processSynchronously **<not used>**Indicates whether the method should return only once disabling this rule and removing the categories from existing items in the conversation is completely done. If processSynchronously is false, the method returns immediately.
* @return {Promise<void>} Promise
*/
DisableAlwaysCategorizeItems(processSynchronously: boolean): Promise<void> {
return this.Service.DisableAlwaysCategorizeItemsInConversations(
[this.Id],
processSynchronously).then((responses) => {
responses.__thisIndexer(0).ThrowIfNecessary();
});
}
/**
* Sets up a conversation so that any item received within that conversation is no longer moved to Deleted Items folder.
* Calling this method results in a call to EWS.
*
* @param {boolean} processSynchronously Indicates whether the method should return only once disabling this rule and restoring the items in the conversation is completely done. If processSynchronously is false, the method returns immediately.
* @return {Promise<void>} Promise
*/
DisableAlwaysDeleteItems(processSynchronously: boolean): Promise<void> {
return this.Service.DisableAlwaysDeleteItemsInConversations(
[this.Id],
processSynchronously).then((responses) => {
responses.__thisIndexer(0).ThrowIfNecessary();
});
}
/**
* Sets up a conversation so that any item received within that conversation is no longer moved to a specific folder.
* Calling this method results in a call to EWS.
*
* @param {boolean} processSynchronously Indicates whether the method should return only once disabling this rule is completely done. If processSynchronously is false, the method returns immediately.
* @return {Promise<void>} Promise
*/
DisableAlwaysMoveItemsInConversation(processSynchronously: boolean): Promise<void> {
return this.Service.DisableAlwaysMoveItemsInConversations(
[this.Id],
processSynchronously).then((responses) => {
responses.__thisIndexer(0).ThrowIfNecessary();
});
}
/**
* Sets up a conversation so that any item received within that conversation is always categorized.
* Calling this method results in a call to EWS.
*
* @param {string[]} categories The categories that should be stamped on items in the conversation.
* @param {boolean} processSynchronously Indicates whether the method should return only once enabling this rule and stamping existing items in the conversation is completely done. If processSynchronously is false, the method returns immediately.
* @return {Promise<void>} Promise
*/
EnableAlwaysCategorizeItems(categories: string[], processSynchronously: boolean): Promise<void> {
return this.Service.EnableAlwaysCategorizeItemsInConversations(
[this.Id],
categories,
processSynchronously).then((responses) => {
responses.__thisIndexer(0).ThrowIfNecessary();
});
}
/**
* Sets up a conversation so that any item received within that conversation is always moved to Deleted Items folder.
* Calling this method results in a call to EWS.
*
* @param {boolean} processSynchronously Indicates whether the method should return only once enabling this rule and deleting existing items in the conversation is completely done. If processSynchronously is false, the method returns immediately.
* @return {Promise<void>} Promise
*/
EnableAlwaysDeleteItems(processSynchronously: boolean): Promise<void> {
return this.Service.EnableAlwaysDeleteItemsInConversations(
[this.Id],
processSynchronously).then((responses) => {
responses.__thisIndexer(0).ThrowIfNecessary();
});
}
/**
* Sets up a conversation so that any item received within that conversation is always moved to a specific folder.
* Calling this method results in a call to EWS.
*
* @param {FolderId} destinationFolderId The Id of the folder to which conversation items should be moved.
* @param {boolean} processSynchronously Indicates whether the method should return only once enabling this rule and moving existing items in the conversation is completely done. If processSynchronously is false, the method returns immediately.
* @return {Promise<void>} Promise
*/
EnableAlwaysMoveItems(destinationFolderId: FolderId, processSynchronously: boolean): Promise<void> {
return this.Service.EnableAlwaysMoveItemsInConversations(
[this.Id],
destinationFolderId,
processSynchronously).then((responses) => {
responses.__thisIndexer(0).ThrowIfNecessary();
});
}
/**
* Flags conversation items. Calling this method results in a call to EWS.
*
* @param {FolderId} contextFolderId The Id of the folder items must belong to in order to be flagged. If contextFolderId is null, items in conversation across the entire mailbox are flagged.
* @param {DateTime} startDate The start date (can be null).
* @param {DateTime} dueDate The due date (can be null).
* @return {Promise<void>} Promise
*/
FlagItems(contextFolderId: FolderId, startDate: DateTime, dueDate: DateTime): Promise<void> {
let flag: Flag = new Flag();
flag.FlagStatus = ItemFlagStatus.Flagged;
if (startDate) {
flag.StartDate = startDate;
}
if (dueDate) {
flag.DueDate = dueDate;
}
return this.Service.SetFlagStatusForItemsInConversations(
[{ key: this.Id, value: this.GlobalLastDeliveryTime }],
contextFolderId,
flag).then((responses) => {
responses.__thisIndexer(0).ThrowIfNecessary();
});
}
/**
* Flag conversation items as complete. Calling this method results in a call to EWS.
*
* @param {FolderId} contextFolderId The Id of the folder items must belong to in order to be flagged as complete. If contextFolderId is null, items in conversation across the entire mailbox are marked as complete.
* @param {DateTime} completeDate The complete date (can be null).
* @return {Promise<void>} Promise
*/
FlagItemsComplete(contextFolderId: FolderId, completeDate: DateTime): Promise<void> {
let flag: Flag = new Flag();
flag.FlagStatus = ItemFlagStatus.Complete;
if (completeDate) {
flag.CompleteDate = completeDate;
}
return this.Service.SetFlagStatusForItemsInConversations(
[{ key: this.Id, value: this.GlobalLastDeliveryTime }],
contextFolderId,
flag).then((responses) => {
responses.__thisIndexer(0).ThrowIfNecessary();
});
}
/**
* @internal This method is not supported in this object.
* Gets the name of the change XML element.
*
* @return {string} XML element name,
*/
GetChangeXmlElementName(): string {
throw new NotSupportedException();
}
/**
* @internal This method is not supported in this object.
* Gets the name of the delete field XML element.
*
* @return {string} XML element name,
*/
GetDeleteFieldXmlElementName(): string {
throw new NotSupportedException();
}
/**
* The property definition for the Id of this object.
*
* @return {PropertyDefinition} A PropertyDefinition instance.
*/
GetIdPropertyDefinition(): PropertyDefinition {
return Schemas.ConversationSchema.Id;
}
/**
* @internal This method is not supported in this object.
* Gets a value indicating whether a time zone SOAP header should be emitted in a CreateItem or UpdateItem request so this item can be property saved or updated.
*
* @param {boolean} isUpdateOperation Indicates whether the operation being petrformed is an update operation.
* @return {boolean} true if a time zone SOAP header should be emitted; otherwise, false.
*/
GetIsTimeZoneHeaderRequired(isUpdateOperation: boolean): boolean {
throw new NotSupportedException();
}
/**
* @internal Gets the minimum required server version.
*
* @return {ExchangeVersion} Earliest Exchange version in which this service object type is supported.
*/
GetMinimumRequiredServerVersion(): ExchangeVersion {
return ExchangeVersion.Exchange2010_SP1;
}
/**
* @internal Internal method to return the schema associated with this type of object.
*
* @return {ServiceObjectSchema} The schema associated with this type of object.
*/
GetSchema(): ServiceObjectSchema {
return Schemas.ConversationSchema.Instance;
}
/**
* @internal This method is not supported in this object.
* Gets the name of the set field XML element.
*
* @return {string} XML element name,
*/
GetSetFieldXmlElementName(): string {
throw new NotSupportedException();
}
/**
* @internal Gets the element name of item in XML
*
* @return {string} name of elelment
*/
GetXmlElementName(): string {
return XmlElementNames.Conversation;
}
/**
* @internal This is not supported in this object.
* Deletes the object.
*
* @param {DeleteMode} deleteMode The deletion mode.
* @param {SendCancellationsMode} sendCancellationsMode Indicates whether meeting cancellation messages should be sent.
* @param {AffectedTaskOccurrence} affectedTaskOccurrences Indicate which occurrence of a recurring task should be deleted.
*/
InternalDelete(deleteMode: DeleteMode, sendCancellationsMode: SendCancellationsMode, affectedTaskOccurrences: AffectedTaskOccurrence): Promise<void> {
throw new NotSupportedException();
}
/**
* @internal This method is not supported in this object.
* Loads the specified set of properties on the object.
*
* @param {PropertySet} propertySet The properties to load.
*/
InternalLoad(propertySet: PropertySet): Promise<void> {
throw new NotSupportedException();
}
/**
* Moves items in the specified conversation to a specific folder.
* Calling this method results in a call to EWS.
*
* @param {FolderId} contextFolderId The Id of the folder items must belong to in order to be moved. If contextFolderId is null, items across the entire mailbox are moved.
* @param {FolderId} destinationFolderId The Id of the destination folder.
* @return {Promise<void>} Promise
*/
MoveItemsInConversation(contextFolderId: FolderId, destinationFolderId: FolderId): Promise<void> {
return this.Service.MoveItemsInConversations(
[{ key: this.Id, value: this.GlobalLastDeliveryTime }],
contextFolderId,
destinationFolderId).then((responses) => {
responses.__thisIndexer(0).ThrowIfNecessary();
});
}
/**
* Sets the read state of items in the specified conversation. Calling this method results in a call to EWS.
*
* @param {FolderId} contextFolderId The Id of the folder items must belong to in order for their read state to be set. If contextFolderId is null, the read states of items across the entire mailbox are set.
* @param {boolean} isRead if set to true, conversation items are marked as read; otherwise they are marked as unread.
* @return {Promise<void>} Promise
*/
SetReadStateForItemsInConversation(contextFolderId: FolderId, isRead: boolean): Promise<void>;
/**
* Sets the read state of items in the specified conversation. Calling this method results in a call to EWS.
*
* @param {FolderId} contextFolderId The Id of the folder items must belong to in order for their read state to be set. If contextFolderId is null, the read states of items across the entire mailbox are set.
* @param {boolean} isRead if set to true, conversation items are marked as read; otherwise they are marked as unread.
* @param {boolean} suppressReadReceipts if set to true read receipts are suppressed.
* @return {Promise<void>} Promise
*/
SetReadStateForItemsInConversation(contextFolderId: FolderId, isRead: boolean, suppressReadReceipts: boolean): Promise<void>;
SetReadStateForItemsInConversation(contextFolderId: FolderId, isRead: boolean, suppressReadReceipts: boolean = null): Promise<void> {
return this.Service.SetReadStateForItemsInConversations(
[{ key: this.Id, value: this.GlobalLastDeliveryTime }],
contextFolderId,
isRead,
suppressReadReceipts).then((responses) => {
responses.__thisIndexer(0).ThrowIfNecessary();
});
}
/**
* Sets the retention policy of items in the specified conversation. Calling this method results in a call to EWS.
*
* @param {FolderId} contextFolderId The Id of the folder items must belong to in order for their retention policy to be set. If contextFolderId is null, the retention policy of items across the entire mailbox are set.
* @param {RetentionType} retentionPolicyType Retention policy type.
* @param {Guid} retentionPolicyTagId Retention policy tag id. Null will clear the policy.
* @return {Promise<void>} Promise
*/
SetRetentionPolicyForItemsInConversation(contextFolderId: FolderId, retentionPolicyType: RetentionType, retentionPolicyTagId: Guid): Promise<void> {
return this.Service.SetRetentionPolicyForItemsInConversations(
[{ key: this.Id, value: this.GlobalLastDeliveryTime }],
contextFolderId,
retentionPolicyType,
retentionPolicyTagId).then((responses) => {
responses.__thisIndexer(0).ThrowIfNecessary();
});
}
} | the_stack |
import { expect } from 'chai';
import { promises as fs } from 'fs';
import * as path from 'path';
import { BalenaAPIMock } from '../nock/balena-api-mock';
import { BuilderMock, builderResponsePath } from '../nock/builder-mock';
import { expectStreamNoCRLF, testPushBuildStream } from '../docker-build';
import { cleanOutput, runCommand } from '../helpers';
import {
addRegSecretsEntries,
exists,
ExpectedTarStreamFiles,
getDockerignoreWarn1,
getDockerignoreWarn2,
getDockerignoreWarn3,
setupDockerignoreTestData,
} from '../projects';
const repoPath = path.normalize(path.join(__dirname, '..', '..'));
const projectsPath = path.join(repoPath, 'tests', 'test-data', 'projects');
const itNoWin = process.platform === 'win32' ? it.skip : it;
const commonResponseLines = {
'build-POST-v3.json': [
'[Info] Starting build for testApp, user gh_user',
'[Info] Dashboard link: https://dashboard.balena-cloud.com/apps/1301645/devices',
'[Info] Building on arm01',
'[Info] Pulling previous images for caching purposes...',
'[Success] Successfully pulled cache images',
'[main] Step 1/4 : FROM busybox',
'[main] ---> 76aea0766768',
'[main] Step 2/4 : COPY ./src/start.sh /start.sh',
'[main] ---> b563ad6a0801',
'[main] Step 3/4 : RUN chmod a+x /start.sh',
'[main] ---> Running in 10d4ddc40bfc',
'[main] Removing intermediate container 10d4ddc40bfc',
'[main] ---> 82e98871a32c',
'[main] Step 4/4 : CMD ["/start.sh"]',
'[main] ---> Running in 0682894e13eb',
'[main] Removing intermediate container 0682894e13eb',
'[main] ---> 889ccb6afc7c',
'[main] Successfully built 889ccb6afc7c',
'[Info] Uploading images',
'[Success] Successfully uploaded images',
'[Info] Built on arm01',
'[Success] Release successfully created!',
'[Info] Release: 05a24b5b034c9f95f25d4d74f0593bea (id: 1220245)',
'[Info] ┌─────────┬────────────┬────────────┐',
'[Info] │ Service │ Image Size │ Build Time │',
'[Info] ├─────────┼────────────┼────────────┤',
'[Info] │ main │ 1.32 MB │ 11 seconds │',
'[Info] └─────────┴────────────┴────────────┘',
],
};
const commonQueryParams = [
['slug', 'gh_user/testApp'],
['dockerfilePath', ''],
['emulated', 'false'],
['nocache', 'false'],
['headless', 'false'],
['isdraft', 'false'],
];
describe('balena push', function () {
let api: BalenaAPIMock;
let builder: BuilderMock;
const isWindows = process.platform === 'win32';
this.beforeEach(() => {
api = new BalenaAPIMock();
builder = new BuilderMock();
api.expectGetWhoAmI({ optional: true, persist: true });
api.expectGetMixpanel({ optional: true });
api.expectGetApplication();
});
this.afterEach(() => {
// Check all expected api calls have been made and clean up.
api.done();
builder.done();
});
this.beforeAll(async () => {
await setupDockerignoreTestData();
});
this.afterAll(async () => {
await setupDockerignoreTestData({ cleanup: true });
});
it('should create the expected tar stream (single container)', async () => {
const projectPath = path.join(projectsPath, 'no-docker-compose', 'basic');
const expectedFiles: ExpectedTarStreamFiles = {
'src/.dockerignore': { fileSize: 16, type: 'file' },
'src/start.sh': { fileSize: 89, type: 'file' },
'src/windows-crlf.sh': {
fileSize: isWindows ? 68 : 70,
testStream: isWindows ? expectStreamNoCRLF : undefined,
type: 'file',
},
Dockerfile: { fileSize: 88, type: 'file' },
'Dockerfile-alt': { fileSize: 30, type: 'file' },
};
const regSecretsPath = await addRegSecretsEntries(expectedFiles);
const responseFilename = 'build-POST-v3.json';
const responseBody = await fs.readFile(
path.join(builderResponsePath, responseFilename),
'utf8',
);
const expectedResponseLines = [
...commonResponseLines[responseFilename],
...getDockerignoreWarn1(
[path.join(projectPath, 'src', '.dockerignore')],
'push',
),
];
if (isWindows) {
const fname = path.join(projectPath, 'src', 'windows-crlf.sh');
expectedResponseLines.push(
`[Info] Converting line endings CRLF -> LF for file: ${fname}`,
);
}
await testPushBuildStream({
builderMock: builder,
commandLine: `push testApp --source ${projectPath} -R ${regSecretsPath}`,
expectedFiles,
expectedQueryParams: commonQueryParams,
expectedResponseLines,
projectPath,
responseBody,
responseCode: 200,
});
});
it('should create the expected tar stream (alternative Dockerfile)', async () => {
const projectPath = path.join(projectsPath, 'no-docker-compose', 'basic');
const expectedFiles: ExpectedTarStreamFiles = {
'src/.dockerignore': { fileSize: 16, type: 'file' },
'src/start.sh': { fileSize: 89, type: 'file' },
'src/windows-crlf.sh': { fileSize: 70, type: 'file' },
Dockerfile: { fileSize: 88, type: 'file' },
'Dockerfile-alt': { fileSize: 30, type: 'file' },
};
const regSecretsPath = await addRegSecretsEntries(expectedFiles);
const responseFilename = 'build-POST-v3.json';
const responseBody = await fs.readFile(
path.join(builderResponsePath, responseFilename),
'utf8',
);
const expectedResponseLines = [
...commonResponseLines[responseFilename],
...getDockerignoreWarn1(
[path.join(projectPath, 'src', '.dockerignore')],
'push',
),
];
const expectedQueryParams = commonQueryParams.map((i) =>
i[0] === 'dockerfilePath' ? ['dockerfilePath', 'Dockerfile-alt'] : i,
);
await testPushBuildStream({
builderMock: builder,
commandLine: `push testApp -s ${projectPath} -R ${regSecretsPath} --dockerfile Dockerfile-alt --noconvert-eol`,
expectedFiles,
expectedQueryParams,
expectedResponseLines,
projectPath,
responseBody,
responseCode: 200,
});
});
it('should create the expected tar stream (single container, --noconvert-eol)', async () => {
const projectPath = path.join(projectsPath, 'no-docker-compose', 'basic');
const expectedFiles: ExpectedTarStreamFiles = {
'src/.dockerignore': { fileSize: 16, type: 'file' },
'src/start.sh': { fileSize: 89, type: 'file' },
'src/windows-crlf.sh': {
fileSize: 70,
type: 'file',
},
Dockerfile: { fileSize: 88, type: 'file' },
'Dockerfile-alt': { fileSize: 30, type: 'file' },
};
const regSecretsPath = await addRegSecretsEntries(expectedFiles);
const responseFilename = 'build-POST-v3.json';
const responseBody = await fs.readFile(
path.join(builderResponsePath, responseFilename),
'utf8',
);
const expectedResponseLines = [
...commonResponseLines[responseFilename],
...getDockerignoreWarn1(
[path.join(projectPath, 'src', '.dockerignore')],
'push',
),
];
if (isWindows) {
const fname = path.join(projectPath, 'src', 'windows-crlf.sh');
expectedResponseLines.push(
`[Warn] CRLF (Windows) line endings detected in file: ${fname}`,
'[Warn] Windows-format line endings were detected in some files, but were not converted due to `--noconvert-eol` option.',
);
}
await testPushBuildStream({
builderMock: builder,
commandLine: `push testApp -s ${projectPath} -R ${regSecretsPath} --noconvert-eol`,
expectedFiles,
expectedQueryParams: commonQueryParams,
expectedResponseLines,
projectPath,
responseBody,
responseCode: 200,
});
});
it('should create the expected tar stream (single container, dockerignore1)', async () => {
const projectPath = path.join(
projectsPath,
'no-docker-compose',
'dockerignore1',
);
const expectedFiles: ExpectedTarStreamFiles = {
'.balena/balena.yml': { fileSize: 12, type: 'file' },
'.dockerignore': { fileSize: 438, type: 'file' },
'.gitignore': { fileSize: 20, type: 'file' },
'.git/foo.txt': { fileSize: 4, type: 'file' },
'a.txt': { fileSize: 1, type: 'file' },
'c.txt': { fileSize: 1, type: 'file' },
Dockerfile: { fileSize: 13, type: 'file' },
'src/.balena/balena.yml': { fileSize: 16, type: 'file' },
'src/.gitignore': { fileSize: 10, type: 'file' },
'src/src-a.txt': { fileSize: 5, type: 'file' },
'src/src-c.txt': { fileSize: 5, type: 'file' },
'vendor/.git/vendor-git-contents': { fileSize: 20, type: 'file' },
};
const regSecretsPath = await addRegSecretsEntries(expectedFiles);
const responseFilename = 'build-POST-v3.json';
const responseBody = await fs.readFile(
path.join(builderResponsePath, responseFilename),
'utf8',
);
await testPushBuildStream({
builderMock: builder,
commandLine: `push testApp -s ${projectPath} -R ${regSecretsPath}`,
expectedFiles,
expectedQueryParams: commonQueryParams,
expectedResponseLines: commonResponseLines[responseFilename],
projectPath,
responseBody,
responseCode: 200,
});
});
// NOTE: if this test or other tests involving symbolic links fail on Windows
// (with a mismatched fileSize 13 vs 5 for 'symlink-a.txt'), ensure that the
// `core.symlinks` property is set to `true` in the `.git/config` file. Ref:
// https://git-scm.com/docs/git-config#Documentation/git-config.txt-coresymlinks
it('should create the expected tar stream (single container, symbolic links)', async () => {
const projectPath = path.join(
projectsPath,
'no-docker-compose',
'dockerignore2',
);
const expectedFiles: ExpectedTarStreamFiles = {
'.dockerignore': { fileSize: 33, type: 'file' },
'b.txt': { fileSize: 1, type: 'file' },
Dockerfile: { fileSize: 13, type: 'file' },
'lib/.dockerignore': { fileSize: 10, type: 'file' },
'lib/src-b.txt': { fileSize: 5, type: 'file' },
'src/src-b.txt': { fileSize: 5, type: 'file' },
'symlink-a.txt': { fileSize: 5, type: 'file' },
};
const regSecretsPath = await addRegSecretsEntries(expectedFiles);
const responseFilename = 'build-POST-v3.json';
const responseBody = await fs.readFile(
path.join(builderResponsePath, responseFilename),
'utf8',
);
const expectedResponseLines = commonResponseLines[responseFilename];
await testPushBuildStream({
builderMock: builder,
commandLine: `push testApp -s ${projectPath} -R ${regSecretsPath}`,
expectedFiles,
expectedQueryParams: commonQueryParams,
expectedResponseLines,
projectPath,
responseBody,
responseCode: 200,
});
});
it('should create the expected tar stream (single container, --multi-dockerignore)', async () => {
const projectPath = path.join(
projectsPath,
'no-docker-compose',
'dockerignore2',
);
const expectedFiles: ExpectedTarStreamFiles = {
'.dockerignore': { fileSize: 33, type: 'file' },
'b.txt': { fileSize: 1, type: 'file' },
Dockerfile: { fileSize: 13, type: 'file' },
'lib/.dockerignore': { fileSize: 10, type: 'file' },
'lib/src-b.txt': { fileSize: 5, type: 'file' },
'src/src-b.txt': { fileSize: 5, type: 'file' },
'symlink-a.txt': { fileSize: 5, type: 'file' },
};
const regSecretsPath = await addRegSecretsEntries(expectedFiles);
const responseFilename = 'build-POST-v3.json';
const responseBody = await fs.readFile(
path.join(builderResponsePath, responseFilename),
'utf8',
);
const expectedResponseLines: string[] = [
...getDockerignoreWarn2(
[path.join(projectPath, 'lib', '.dockerignore')],
'push',
),
...commonResponseLines[responseFilename],
];
await testPushBuildStream({
builderMock: builder,
commandLine: `push testApp -s ${projectPath} -R ${regSecretsPath} -m`,
expectedFiles,
expectedQueryParams: commonQueryParams,
expectedResponseLines,
projectPath,
responseBody,
responseCode: 200,
});
});
it('should create the expected tar stream (docker-compose)', async () => {
const projectPath = path.join(projectsPath, 'docker-compose', 'basic');
const expectedFiles: ExpectedTarStreamFiles = {
'.balena/balena.yml': { fileSize: 197, type: 'file' },
'docker-compose.yml': { fileSize: 332, type: 'file' },
'service1/Dockerfile.template': { fileSize: 144, type: 'file' },
'service1/file1.sh': { fileSize: 12, type: 'file' },
'service2/Dockerfile-alt': { fileSize: 13, type: 'file' },
'service2/file2-crlf.sh': {
fileSize: isWindows ? 12 : 14,
testStream: isWindows ? expectStreamNoCRLF : undefined,
type: 'file',
},
'service2/src/file1.sh': { fileSize: 12, type: 'file' },
};
const regSecretsPath = await addRegSecretsEntries(expectedFiles);
const responseFilename = 'build-POST-v3.json';
const responseBody = await fs.readFile(
path.join(builderResponsePath, responseFilename),
'utf8',
);
const expectedResponseLines: string[] = [
...commonResponseLines[responseFilename],
...getDockerignoreWarn1(
[path.join(projectPath, 'service2', '.dockerignore')],
'push',
),
];
if (isWindows) {
expectedResponseLines.push(
`[Info] Converting line endings CRLF -> LF for file: ${path.join(
projectPath,
'service2',
'file2-crlf.sh',
)}`,
);
}
await testPushBuildStream({
builderMock: builder,
commandLine: `push testApp -s ${projectPath} -R ${regSecretsPath}`,
expectedFiles,
expectedQueryParams: commonQueryParams,
expectedResponseLines,
projectPath,
responseBody,
responseCode: 200,
});
});
it('should create the expected tar stream (docker-compose, --multi-dockerignore)', async () => {
const projectPath = path.join(projectsPath, 'docker-compose', 'basic');
const expectedFiles: ExpectedTarStreamFiles = {
'.balena/balena.yml': { fileSize: 197, type: 'file' },
'docker-compose.yml': { fileSize: 332, type: 'file' },
'service1/Dockerfile.template': { fileSize: 144, type: 'file' },
'service1/file1.sh': { fileSize: 12, type: 'file' },
'service1/test-ignore.txt': { fileSize: 12, type: 'file' },
'service2/Dockerfile-alt': { fileSize: 13, type: 'file' },
'service2/.dockerignore': { fileSize: 12, type: 'file' },
'service2/file2-crlf.sh': {
fileSize: isWindows ? 12 : 14,
testStream: isWindows ? expectStreamNoCRLF : undefined,
type: 'file',
},
};
const regSecretsPath = await addRegSecretsEntries(expectedFiles);
const responseFilename = 'build-POST-v3.json';
const responseBody = await fs.readFile(
path.join(builderResponsePath, responseFilename),
'utf8',
);
const expectedResponseLines: string[] = [
...commonResponseLines[responseFilename],
...getDockerignoreWarn3('push'),
];
if (isWindows) {
expectedResponseLines.push(
`[Info] Converting line endings CRLF -> LF for file: ${path.join(
projectPath,
'service2',
'file2-crlf.sh',
)}`,
);
}
await testPushBuildStream({
builderMock: builder,
commandLine: `push testApp -s ${projectPath} -R ${regSecretsPath} -m`,
expectedFiles,
expectedQueryParams: commonQueryParams,
expectedResponseLines,
projectPath,
responseBody,
responseCode: 200,
});
});
// Skip on Windows because this test uses Unix domain sockets
itNoWin('should create the expected tar stream (socket file)', async () => {
// This test creates project files dynamically in a temp dir, where
// a Unix domain socket file is created and listened on. A specific
// reason use use a temp dir is that Unix domain socket paths are
// limited in length to just over 100 characters, while the project
// paths in the test-data folder easily exceed that limit.
const tmp = await import('tmp');
tmp.setGracefulCleanup();
const projectPath = await new Promise<string>((resolve, reject) => {
const opts = { template: 'tmp-XXXXXX', unsafeCleanup: true };
tmp.dir(opts, (e, p) => (e ? reject(e) : resolve(p)));
});
console.error(`[debug] Temp project dir: ${projectPath}`);
// Create a Unix Domain Socket file that should not be included in the tar stream
const net = await import('net');
const server = net.createServer();
const socketPath = path.join(projectPath, 'socket');
await new Promise<void>((resolve, reject) => {
server.on('error', reject);
try {
server.listen(socketPath, resolve);
} catch (e) {
reject(e);
}
});
console.error(`[debug] Checking existence of socket at '${socketPath}'`);
expect(await exists(socketPath), 'Socket existence').to.be.true;
await fs.writeFile(path.join(projectPath, 'Dockerfile'), 'FROM busybox\n');
const expectedFiles: ExpectedTarStreamFiles = {
Dockerfile: { fileSize: 13, type: 'file' },
};
const responseFilename = 'build-POST-v3.json';
const responseBody = await fs.readFile(
path.join(builderResponsePath, responseFilename),
'utf8',
);
await testPushBuildStream({
builderMock: builder,
commandLine: `push testApp -s ${projectPath}`,
expectedFiles,
expectedQueryParams: commonQueryParams,
expectedResponseLines: commonResponseLines[responseFilename],
projectPath,
responseBody,
responseCode: 200,
});
// Terminate Unix Domain Socket server
await new Promise<void>((resolve, reject) => {
server.close((e) => (e ? reject(e) : resolve()));
});
expect(await exists(socketPath), 'Socket existence').to.be.false;
});
});
describe('balena push: project validation', function () {
let api: BalenaAPIMock;
this.beforeEach(() => {
api = new BalenaAPIMock();
api.expectGetMixpanel({ optional: true });
});
this.afterEach(() => {
// Check all expected api calls have been made and clean up.
api.done();
});
it('should raise ExpectedError if the project folder is not a directory', async () => {
const projectPath = path.join(
projectsPath,
'docker-compose',
'basic',
'docker-compose.yml',
);
const expectedErrorLines = [
`Could not access source folder: "${projectPath}"`,
];
const { out, err } = await runCommand(
`push testApp --source ${projectPath}`,
);
expect(cleanOutput(err, true)).to.include.members(expectedErrorLines);
expect(out).to.be.empty;
});
it('should raise ExpectedError if a Dockerfile cannot be found', async () => {
const projectPath = path.join(
projectsPath,
'docker-compose',
'basic',
'service2',
);
const expectedErrorLines = [
'Error: no "Dockerfile[.*]", "docker-compose.yml" or "package.json" file',
`found in source folder "${projectPath}"`,
];
const { out, err } = await runCommand(
`push testApp --source ${projectPath}`,
);
expect(cleanOutput(err, true)).to.include.members(expectedErrorLines);
expect(out).to.be.empty;
});
it('should log a warning if a docker-compose.yml exists in a parent folder', async () => {
const projectPath = path.join(
projectsPath,
'docker-compose',
'basic',
'service1',
);
const expectedErrorLines = [
'Error: "docker-compose.y[a]ml" file found in parent directory: please check that',
"the correct source folder was specified. (Suppress with '--noparent-check'.)",
];
const { out, err } = await runCommand(
`push testApp --source ${projectPath} --nolive`,
);
expect(cleanOutput(err, true)).to.include.members(expectedErrorLines);
expect(out).to.be.empty;
});
it('should suppress a parent folder check with --noparent-check', async () => {
const projectPath = path.join(
projectsPath,
'docker-compose',
'basic',
'service1',
);
const expectedErrorLines = [
'The --nolive flag is only valid when pushing to a local mode device',
];
const { out, err } = await runCommand(
`push testApp --source ${projectPath} --nolive --noparent-check`,
);
expect(cleanOutput(err, true)).to.include.members(expectedErrorLines);
expect(out).to.be.empty;
});
}); | the_stack |
module android.view {
import PixelFormat = android.graphics.PixelFormat;
import TextUtils = android.text.TextUtils;
import Log = android.util.Log;
import Integer = java.lang.Integer;
import StringBuilder = java.lang.StringBuilder;
import Gravity = android.view.Gravity;
import KeyEvent = android.view.KeyEvent;
import MotionEvent = android.view.MotionEvent;
import View = android.view.View;
import ViewGroup = android.view.ViewGroup;
import Window = android.view.Window;
import Context = android.content.Context;
import Animation = android.view.animation.Animation;
/**
* The interface that apps use to talk to the window manager.
* <p>
* Use <code>Context.getSystemService(Context.WINDOW_SERVICE)</code> to get one of these.
* </p><p>
* Each window manager instance is bound to a particular {@link Display}.
* To obtain a {@link WindowManager} for a different display, use
* {@link Context#createDisplayContext} to obtain a {@link Context} for that
* display, then use <code>Context.getSystemService(Context.WINDOW_SERVICE)</code>
* to get the WindowManager.
* </p><p>
* The simplest way to show a window on another display is to create a
* {@link Presentation}. The presentation will automatically obtain a
* {@link WindowManager} and {@link Context} for that display.
* </p>
*
* @see android.content.Context#getSystemService
* @see android.content.Context#WINDOW_SERVICE
*/
export class WindowManager {
private mWindowsLayout:WindowManager.Layout;
protected mActiveWindow:Window;
private static FocusViewRemember = Symbol();
constructor(context:Context) {
this.mWindowsLayout = new WindowManager.Layout(context, this);
let viewRootImpl = context.androidUI._viewRootImpl;
let fakeAttachInfo = new View.AttachInfo(viewRootImpl, viewRootImpl.mHandler);
fakeAttachInfo.mRootView = this.mWindowsLayout;
this.mWindowsLayout.dispatchAttachedToWindow(fakeAttachInfo, 0);
this.mWindowsLayout.mGroupFlags |= ViewGroup.FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW; // make attachInfo not handle when addWindow
this.mWindowsLayout.mGroupFlags |= ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE; // activity animation should use cache
}
getWindowsLayout():ViewGroup {
return this.mWindowsLayout;
}
addWindow(window:Window):void{
let wparams = window.getAttributes();
if(!wparams){
wparams = new WindowManager.LayoutParams();
}
if(!(wparams instanceof WindowManager.LayoutParams)){
throw Error('can\'t addWindow, params must be WindowManager.LayoutParams : '+wparams);
}
window.setContainer(this);
let decorView = window.getDecorView();
//TODO use type as z-index
let type = wparams.type;
let lastFocusWindowView = this.mWindowsLayout.getTopFocusableWindowView();
this.mWindowsLayout.addView(decorView, wparams);
decorView.dispatchAttachedToWindow(window.mAttachInfo, 0);
//window.mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(true);
if(wparams.isFocusable()){
decorView.dispatchWindowFocusChanged(true);
//clearLastWindowFocus
if(lastFocusWindowView && lastFocusWindowView.hasFocus()){
const focused = lastFocusWindowView.findFocus();
lastFocusWindowView[WindowManager.FocusViewRemember] = focused;
if (focused != null) {
focused.clearFocusInternal(true, false);
}
lastFocusWindowView.dispatchWindowFocusChanged(false);
//new window should be focused
decorView.addOnLayoutChangeListener({
onLayoutChange(v:View, left:number , top:number , right:number , bottom:number,
oldLeft:number , oldTop:number , oldRight:number , oldBottom:number){
decorView.removeOnLayoutChangeListener(this);
const newWindowFocused = FocusFinder.getInstance().findNextFocus(<ViewGroup>decorView, null, View.FOCUS_DOWN);
if (newWindowFocused != null) {
newWindowFocused.requestFocus(View.FOCUS_DOWN);
}
}
});
}
}
if(decorView instanceof ViewGroup){
decorView.setMotionEventSplittingEnabled(wparams.isSplitTouch());
}
let enterAnimation = window.getContext().androidUI.mActivityThread.getOverrideEnterAnimation();
if(enterAnimation === undefined) enterAnimation = wparams.enterAnimation;
if(enterAnimation) {
decorView.bindElement.style.visibility = 'hidden';
enterAnimation.setAnimationListener({
onAnimationStart(animation: Animation): void {
},
onAnimationEnd(animation: Animation): void {
decorView.bindElement.style.visibility = '';
},
onAnimationRepeat(animation: Animation): void {
}
});
decorView.startAnimation(enterAnimation);
}
}
updateWindowLayout(window:Window, params:ViewGroup.LayoutParams):void{
if(!(params instanceof WindowManager.LayoutParams)){
throw Error('can\'t updateWindowLayout, params must be WindowManager.LayoutParams');
}
window.getDecorView().setLayoutParams(params);
}
removeWindow(window:Window):void{
let decor = window.getDecorView();
if(decor.getParent()==null) return;//not add
if(decor.getParent() !== this.mWindowsLayout){
console.error('removeWindow fail, don\'t has the window, decor belong to ', decor.getParent());
return;
}
let wparams = <WindowManager.LayoutParams>decor.getLayoutParams();
let exitAnimation = window.getContext().androidUI.mActivityThread.getOverrideExitAnimation();
if(exitAnimation === undefined) exitAnimation = wparams.exitAnimation;
if(exitAnimation){
let t = this;
decor.startAnimation(exitAnimation);
decor.drawAnimation(this.mWindowsLayout, android.os.SystemClock.uptimeMillis(), exitAnimation);//init animation
this.mWindowsLayout.removeView(decor);
}else{
this.mWindowsLayout.removeView(decor);
}
if(wparams.isFocusable()) {
let resumeWindowView = this.mWindowsLayout.getTopFocusableWindowView();
if (resumeWindowView) {
resumeWindowView.dispatchWindowFocusChanged(true);
let resumeFocus = resumeWindowView[WindowManager.FocusViewRemember];
if(resumeFocus){
resumeFocus.requestFocus(View.FOCUS_DOWN);
}
}
}
}
}
export module WindowManager{
/**
* children ara windows decor view
*/
export class Layout extends android.widget.FrameLayout {
private mWindowManager:WindowManager;
constructor(context:android.content.Context, windowManager:WindowManager) {
super(context);
this.mWindowManager = windowManager;
}
getTopFocusableWindowView(findParent=true):ViewGroup {
const count:number = this.getChildCount();
for (let i:number = count-1; i >=0; i--) {
let child = this.getChildAt(i);
let wparams = <WindowManager.LayoutParams>child.getLayoutParams();
if(wparams.isFocusable()){
return <ViewGroup>child;
}
}
if(findParent){
let decor = this.getParent();
if(decor!=null){
let windowLayout = decor.getParent();
if(windowLayout instanceof Layout){
return windowLayout.getTopFocusableWindowView();
}
}
}
}
dispatchKeyEvent(event:android.view.KeyEvent):boolean {
let topFocusView = this.getTopFocusableWindowView(false);
if(topFocusView && topFocusView.dispatchKeyEvent(event)){
return true;
}
return super.dispatchKeyEvent(event);
}
protected isTransformedTouchPointInView(x:number, y:number, child:android.view.View, outLocalPoint:android.graphics.Point):boolean {
let wparams = <WindowManager.LayoutParams>child.getLayoutParams();
if(wparams.isFocusable() && wparams.isTouchable()){
//handle touch to window
return true;
}
return false;//super.isTransformedTouchPointInView(x, y, child, outLocalPoint);
}
onChildVisibilityChanged(child:android.view.View, oldVisibility:number, newVisibility:number):void {
super.onChildVisibilityChanged(child, oldVisibility, newVisibility);
let wparams = <WindowManager.LayoutParams>child.getLayoutParams();
if(newVisibility === View.VISIBLE){
let resumeAnimation = child.getContext().androidUI.mActivityThread.getOverrideResumeAnimation();
if(resumeAnimation === undefined) resumeAnimation = wparams.resumeAnimation;
if(resumeAnimation){
child.startAnimation(resumeAnimation);
}
}else{
let hideAnimation = child.getContext().androidUI.mActivityThread.getOverrideHideAnimation();
if(hideAnimation === undefined) hideAnimation = wparams.hideAnimation;
if(hideAnimation){
child.startAnimation(hideAnimation);
child.drawAnimation(this, android.os.SystemClock.uptimeMillis(), hideAnimation);//init animation
}
}
}
protected onLayout(changed: boolean, left: number, top: number, right: number, bottom: number): void {
this.layoutChildren(left, top, right, bottom, false /* no force left gravity */);
}
layoutChildren(left: number, top: number, right: number, bottom: number, forceLeftGravity: boolean): void {
const count = this.getChildCount();
const parentLeft = this.getPaddingLeftWithForeground();
const parentRight = right - left - this.getPaddingRightWithForeground();
const parentTop = this.getPaddingTopWithForeground();
const parentBottom = bottom - top - this.getPaddingBottomWithForeground();
this.mForegroundBoundsChanged = true;
for (let i = 0; i < count; i++) {
let child = this.getChildAt(i);
if (child.getVisibility() != View.GONE) {
const lp = <WindowManager.LayoutParams> child.getLayoutParams();
const width = child.getMeasuredWidth();
const height = child.getMeasuredHeight();
let childLeft;
let childTop;
let gravity = lp.gravity;
if (gravity == -1) {
gravity = Layout.DEFAULT_CHILD_GRAVITY;
}
//const layoutDirection = getLayoutDirection();
const absoluteGravity = gravity;//Gravity.getAbsoluteGravity(gravity, layoutDirection);
const verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;
switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
case Gravity.CENTER_HORIZONTAL:
childLeft = parentLeft + (parentRight - parentLeft - width) / 2 + lp.leftMargin - lp.rightMargin;
break;
case Gravity.RIGHT:
if (!forceLeftGravity) {
childLeft = parentRight - width - lp.rightMargin - lp.x;
break;
}
case Gravity.LEFT:
default:
childLeft = parentLeft + lp.leftMargin + lp.x;
}
switch (verticalGravity) {
case Gravity.TOP:
childTop = parentTop + lp.topMargin + lp.y;
break;
case Gravity.CENTER_VERTICAL:
childTop = parentTop + (parentBottom - parentTop - height) / 2 + lp.topMargin - lp.bottomMargin;
break;
case Gravity.BOTTOM:
childTop = parentBottom - height - lp.bottomMargin - lp.y;
break;
default:
childTop = parentTop + lp.topMargin;
}
child.layout(childLeft, childTop, childLeft + width, childTop + height);
}
}
}
tagName():string {
return 'windowsGroup';
}
}
export class LayoutParams extends android.widget.FrameLayout.LayoutParams {
/**
* X position for this window. With the default gravity it is ignored.
* When using {@link Gravity#LEFT} or {@link Gravity#START} or {@link Gravity#RIGHT} or
* {@link Gravity#END} it provides an offset from the given edge.
*/
x:number = 0;
/**
* Y position for this window. With the default gravity it is ignored.
* When using {@link Gravity#TOP} or {@link Gravity#BOTTOM} it provides
* an offset from the given edge.
*/
y:number = 0;
///**
// * Indicates how much of the extra space will be allocated horizontally
// * to the view associated with these LayoutParams. Specify 0 if the view
// * should not be stretched. Otherwise the extra pixels will be pro-rated
// * among all views whose weight is greater than 0.
// */
//horizontalWeight:number = 0;
//
///**
// * Indicates how much of the extra space will be allocated vertically
// * to the view associated with these LayoutParams. Specify 0 if the view
// * should not be stretched. Otherwise the extra pixels will be pro-rated
// * among all views whose weight is greater than 0.
// */
//verticalWeight:number = 0;
/**
* The general type of window. There are three main classes of
* window types:
* <ul>
* <li> <strong>Application windows</strong> (ranging from
* {@link #FIRST_APPLICATION_WINDOW} to
* {@link #LAST_APPLICATION_WINDOW}) are normal top-level application
* windows. For these types of windows, the {@link #token} must be
* set to the token of the activity they are a part of (this will
* normally be done for you if {@link #token} is null).
* <li> <strong>Sub-windows</strong> (ranging from
* {@link #FIRST_SUB_WINDOW} to
* {@link #LAST_SUB_WINDOW}) are associated with another top-level
* window. For these types of windows, the {@link #token} must be
* the token of the window it is attached to.
* <li> <strong>System windows</strong> (ranging from
* {@link #FIRST_SYSTEM_WINDOW} to
* {@link #LAST_SYSTEM_WINDOW}) are special types of windows for
* use by the system for specific purposes. They should not normally
* be used by applications, and a special permission is required
* to use them.
* </ul>
*
* @see #TYPE_BASE_APPLICATION
* @see #TYPE_APPLICATION
* @see #TYPE_APPLICATION_STARTING
* @see #TYPE_APPLICATION_PANEL
* @see #TYPE_APPLICATION_MEDIA
* @see #TYPE_APPLICATION_SUB_PANEL
* @see #TYPE_APPLICATION_ATTACHED_DIALOG
* @see #TYPE_STATUS_BAR
* @see #TYPE_SEARCH_BAR
* @see #TYPE_PHONE
* @see #TYPE_SYSTEM_ALERT
* @see #TYPE_KEYGUARD
* @see #TYPE_TOAST
* @see #TYPE_SYSTEM_OVERLAY
* @see #TYPE_PRIORITY_PHONE
* @see #TYPE_STATUS_BAR_PANEL
* @see #TYPE_SYSTEM_DIALOG
* @see #TYPE_KEYGUARD_DIALOG
* @see #TYPE_SYSTEM_ERROR
* @see #TYPE_INPUT_METHOD
* @see #TYPE_INPUT_METHOD_DIALOG
*/
type:number = 0;
/**
* Start of window types that represent normal application windows.
*/
static FIRST_APPLICATION_WINDOW:number = 1;
/**
* Window type: an application window that serves as the "base" window
* of the overall application; all other application windows will
* appear on top of it.
* In multiuser systems shows only on the owning user's window.
*/
static TYPE_BASE_APPLICATION:number = 1;
/**
* Window type: a normal application window. The {@link #token} must be
* an Activity token identifying who the window belongs to.
* In multiuser systems shows only on the owning user's window.
*/
static TYPE_APPLICATION:number = 2;
/**
* Window type: special application window that is displayed while the
* application is starting. Not for use by applications themselves;
* this is used by the system to display something until the
* application can show its own windows.
* In multiuser systems shows on all users' windows.
*/
static TYPE_APPLICATION_STARTING:number = 3;
/**
* End of types of application windows.
*/
static LAST_APPLICATION_WINDOW:number = 99;
/**
* Start of types of sub-windows. The {@link #token} of these windows
* must be set to the window they are attached to. These types of
* windows are kept next to their attached window in Z-order, and their
* coordinate space is relative to their attached window.
*/
static FIRST_SUB_WINDOW:number = 1000;
/**
* Window type: a panel on top of an application window. These windows
* appear on top of their attached window.
*/
static TYPE_APPLICATION_PANEL:number = LayoutParams.FIRST_SUB_WINDOW;
/**
* Window type: window for showing media (such as video). These windows
* are displayed behind their attached window.
*/
static TYPE_APPLICATION_MEDIA:number = LayoutParams.FIRST_SUB_WINDOW + 1;
/**
* Window type: a sub-panel on top of an application window. These
* windows are displayed on top their attached window and any
* {@link #TYPE_APPLICATION_PANEL} panels.
*/
static TYPE_APPLICATION_SUB_PANEL:number = LayoutParams.FIRST_SUB_WINDOW + 2;
/** Window type: like {@link #TYPE_APPLICATION_PANEL}, but layout
* of the window happens as that of a top-level window, <em>not</em>
* as a child of its container.
*/
static TYPE_APPLICATION_ATTACHED_DIALOG:number = LayoutParams.FIRST_SUB_WINDOW + 3;
/**
* Window type: window for showing overlays on top of media windows.
* These windows are displayed between TYPE_APPLICATION_MEDIA and the
* application window. They should be translucent to be useful. This
* is a big ugly hack so:
* @hide
*/
static TYPE_APPLICATION_MEDIA_OVERLAY:number = LayoutParams.FIRST_SUB_WINDOW + 4;
/**
* End of types of sub-windows.
*/
static LAST_SUB_WINDOW:number = 1999;
/**
* Start of system-specific window types. These are not normally
* created by applications.
*/
static FIRST_SYSTEM_WINDOW:number = 2000;
/**
* Window type: the status bar. There can be only one status bar
* window; it is placed at the top of the screen, and all other
* windows are shifted down so they are below it.
* In multiuser systems shows on all users' windows.
*/
static TYPE_STATUS_BAR:number = LayoutParams.FIRST_SYSTEM_WINDOW;
/**
* Window type: the search bar. There can be only one search bar
* window; it is placed at the top of the screen.
* In multiuser systems shows on all users' windows.
*/
static TYPE_SEARCH_BAR:number = LayoutParams.FIRST_SYSTEM_WINDOW + 1;
/**
* Window type: phone. These are non-application windows providing
* user interaction with the phone (in particular incoming calls).
* These windows are normally placed above all applications, but behind
* the status bar.
* In multiuser systems shows on all users' windows.
*/
static TYPE_PHONE:number = LayoutParams.FIRST_SYSTEM_WINDOW + 2;
/**
* Window type: system window, such as low power alert. These windows
* are always on top of application windows.
* In multiuser systems shows only on the owning user's window.
*/
static TYPE_SYSTEM_ALERT:number = LayoutParams.FIRST_SYSTEM_WINDOW + 3;
/**
* Window type: keyguard window.
* In multiuser systems shows on all users' windows.
*/
static TYPE_KEYGUARD:number = LayoutParams.FIRST_SYSTEM_WINDOW + 4;
/**
* Window type: transient notifications.
* In multiuser systems shows only on the owning user's window.
*/
static TYPE_TOAST:number = LayoutParams.FIRST_SYSTEM_WINDOW + 5;
/**
* Window type: system overlay windows, which need to be displayed
* on top of everything else. These windows must not take input
* focus, or they will interfere with the keyguard.
* In multiuser systems shows only on the owning user's window.
*/
static TYPE_SYSTEM_OVERLAY:number = LayoutParams.FIRST_SYSTEM_WINDOW + 6;
/**
* Window type: priority phone UI, which needs to be displayed even if
* the keyguard is active. These windows must not take input
* focus, or they will interfere with the keyguard.
* In multiuser systems shows on all users' windows.
*/
static TYPE_PRIORITY_PHONE:number = LayoutParams.FIRST_SYSTEM_WINDOW + 7;
/**
* Window type: panel that slides out from the status bar
* In multiuser systems shows on all users' windows.
*/
static TYPE_SYSTEM_DIALOG:number = LayoutParams.FIRST_SYSTEM_WINDOW + 8;
///**
// * Window type: dialogs that the keyguard shows
// * In multiuser systems shows on all users' windows.
// */
//static TYPE_KEYGUARD_DIALOG:number = LayoutParams.FIRST_SYSTEM_WINDOW + 9;
//
///**
// * Window type: internal system error windows, appear on top of
// * everything they can.
// * In multiuser systems shows only on the owning user's window.
// */
//static TYPE_SYSTEM_ERROR:number = LayoutParams.FIRST_SYSTEM_WINDOW + 10;
//
///**
// * Window type: internal input methods windows, which appear above
// * the normal UI. Application windows may be resized or panned to keep
// * the input focus visible while this window is displayed.
// * In multiuser systems shows only on the owning user's window.
// */
//static TYPE_INPUT_METHOD:number = LayoutParams.FIRST_SYSTEM_WINDOW + 11;
//
///**
// * Window type: internal input methods dialog windows, which appear above
// * the current input method window.
// * In multiuser systems shows only on the owning user's window.
// */
//static TYPE_INPUT_METHOD_DIALOG:number = LayoutParams.FIRST_SYSTEM_WINDOW + 12;
//
///**
// * Window type: wallpaper window, placed behind any window that wants
// * to sit on top of the wallpaper.
// * In multiuser systems shows only on the owning user's window.
// */
//static TYPE_WALLPAPER:number = LayoutParams.FIRST_SYSTEM_WINDOW + 13;
//
///**
// * Window type: panel that slides out from over the status bar
// * In multiuser systems shows on all users' windows.
// */
//static TYPE_STATUS_BAR_PANEL:number = LayoutParams.FIRST_SYSTEM_WINDOW + 14;
//
///**
// * Window type: secure system overlay windows, which need to be displayed
// * on top of everything else. These windows must not take input
// * focus, or they will interfere with the keyguard.
// *
// * This is exactly like {@link #TYPE_SYSTEM_OVERLAY} except that only the
// * system itself is allowed to create these overlays. Applications cannot
// * obtain permission to create secure system overlays.
// *
// * In multiuser systems shows only on the owning user's window.
// * @hide
// */
//static TYPE_SECURE_SYSTEM_OVERLAY:number = LayoutParams.FIRST_SYSTEM_WINDOW + 15;
//
///**
// * Window type: the drag-and-drop pseudowindow. There is only one
// * drag layer (at most), and it is placed on top of all other windows.
// * In multiuser systems shows only on the owning user's window.
// * @hide
// */
//static TYPE_DRAG:number = LayoutParams.FIRST_SYSTEM_WINDOW + 16;
//
///**
// * Window type: panel that slides out from under the status bar
// * In multiuser systems shows on all users' windows.
// * @hide
// */
//static TYPE_STATUS_BAR_SUB_PANEL:number = LayoutParams.FIRST_SYSTEM_WINDOW + 17;
//
///**
// * Window type: (mouse) pointer
// * In multiuser systems shows on all users' windows.
// * @hide
// */
//static TYPE_POINTER:number = LayoutParams.FIRST_SYSTEM_WINDOW + 18;
//
///**
// * Window type: Navigation bar (when distinct from status bar)
// * In multiuser systems shows on all users' windows.
// * @hide
// */
//static TYPE_NAVIGATION_BAR:number = LayoutParams.FIRST_SYSTEM_WINDOW + 19;
//
///**
// * Window type: The volume level overlay/dialog shown when the user
// * changes the system volume.
// * In multiuser systems shows on all users' windows.
// * @hide
// */
//static TYPE_VOLUME_OVERLAY:number = LayoutParams.FIRST_SYSTEM_WINDOW + 20;
//
///**
// * Window type: The boot progress dialog, goes on top of everything
// * in the world.
// * In multiuser systems shows on all users' windows.
// * @hide
// */
//static TYPE_BOOT_PROGRESS:number = LayoutParams.FIRST_SYSTEM_WINDOW + 21;
//
///**
// * Window type: Fake window to consume touch events when the navigation
// * bar is hidden.
// * In multiuser systems shows on all users' windows.
// * @hide
// */
//static TYPE_HIDDEN_NAV_CONSUMER:number = LayoutParams.FIRST_SYSTEM_WINDOW + 22;
//
///**
// * Window type: Dreams (screen saver) window, just above keyguard.
// * In multiuser systems shows only on the owning user's window.
// * @hide
// */
//static TYPE_DREAM:number = LayoutParams.FIRST_SYSTEM_WINDOW + 23;
//
///**
// * Window type: Navigation bar panel (when navigation bar is distinct from status bar)
// * In multiuser systems shows on all users' windows.
// * @hide
// */
//static TYPE_NAVIGATION_BAR_PANEL:number = LayoutParams.FIRST_SYSTEM_WINDOW + 24;
//
///**
// * Window type: Behind the universe of the real windows.
// * In multiuser systems shows on all users' windows.
// * @hide
// */
//static TYPE_UNIVERSE_BACKGROUND:number = LayoutParams.FIRST_SYSTEM_WINDOW + 25;
//
///**
// * Window type: Display overlay window. Used to simulate secondary display devices.
// * In multiuser systems shows on all users' windows.
// * @hide
// */
//static TYPE_DISPLAY_OVERLAY:number = LayoutParams.FIRST_SYSTEM_WINDOW + 26;
//
///**
// * Window type: Magnification overlay window. Used to highlight the magnified
// * portion of a display when accessibility magnification is enabled.
// * In multiuser systems shows on all users' windows.
// * @hide
// */
//static TYPE_MAGNIFICATION_OVERLAY:number = LayoutParams.FIRST_SYSTEM_WINDOW + 27;
//
///**
// * Window type: Recents. Same layer as {@link #TYPE_SYSTEM_DIALOG} but only appears on
// * one user's screen.
// * In multiuser systems shows on all users' windows.
// * @hide
// */
//static TYPE_RECENTS_OVERLAY:number = LayoutParams.FIRST_SYSTEM_WINDOW + 28;
//
///**
// * Window type: keyguard scrim window. Shows if keyguard needs to be restarted.
// * In multiuser systems shows on all users' windows.
// * @hide
// */
//static TYPE_KEYGUARD_SCRIM:number = LayoutParams.FIRST_SYSTEM_WINDOW + 29;
//
///**
// * Window type: Window for Presentation on top of private
// * virtual display.
// */
//static TYPE_PRIVATE_PRESENTATION:number = LayoutParams.FIRST_SYSTEM_WINDOW + 30;
/**
* End of types of system windows.
*/
static LAST_SYSTEM_WINDOW:number = 2999;
///** @deprecated this is ignored, this value is set automatically when needed. */
//static MEMORY_TYPE_NORMAL:number = 0;
//
///** @deprecated this is ignored, this value is set automatically when needed. */
//static MEMORY_TYPE_HARDWARE:number = 1;
//
///** @deprecated this is ignored, this value is set automatically when needed. */
//static MEMORY_TYPE_GPU:number = 2;
//
///** @deprecated this is ignored, this value is set automatically when needed. */
//static MEMORY_TYPE_PUSH_BUFFERS:number = 3;
//
///**
// * @deprecated this is ignored
// */
//memoryType:number = 0;
///** Window flag: as long as this window is visible to the user, allow
// * the lock screen to activate while the screen is on.
// * This can be used independently, or in combination with
// * {@link #FLAG_KEEP_SCREEN_ON} and/or {@link #FLAG_SHOW_WHEN_LOCKED} */
//static FLAG_ALLOW_LOCK_WHILE_SCREEN_ON:number = 0x00000001;
///** Window flag: everything behind this window will be dimmed.
// * Use {@link #dimAmount} to control the amount of dim. */
//static FLAG_DIM_BEHIND:number = 0x00000002;
///** Window flag: blur everything behind this window.
// * @deprecated Blurring is no longer supported. */
//static FLAG_BLUR_BEHIND:number = 0x00000004;
/** Window flag: this window won't ever get key input focus, so the
* user can not send key or other button events to it. Those will
* instead go to whatever focusable window is behind it. This flag
* will also enable {@link #FLAG_NOT_TOUCH_MODAL} whether or not that
* is explicitly set.
*
* <p>Setting this flag also implies that the window will not need to
* interact with
* a soft input method, so it will be Z-ordered and positioned
* independently of any active input method (typically this means it
* gets Z-ordered on top of the input method, so it can use the full
* screen for its content and cover the input method if needed. You
* can use {@link #FLAG_ALT_FOCUSABLE_IM} to modify this behavior. */
static FLAG_NOT_FOCUSABLE:number = 0x00000008;
/** Window flag: this window can never receive touch events. */
static FLAG_NOT_TOUCHABLE:number = 0x00000010;
/** Window flag: even when this window is focusable (its
* {@link #FLAG_NOT_FOCUSABLE} is not set), allow any pointer events
* outside of the window to be sent to the windows behind it. Otherwise
* it will consume all pointer events itself, regardless of whether they
* are inside of the window. */
static FLAG_NOT_TOUCH_MODAL:number = 0x00000020;
///** Window flag: when set, if the device is asleep when the touch
// * screen is pressed, you will receive this first touch event. Usually
// * the first touch event is consumed by the system since the user can
// * not see what they are pressing on.
// */
//static FLAG_TOUCHABLE_WHEN_WAKING:number = 0x00000040;
//
///** Window flag: as long as this window is visible to the user, keep
// * the device's screen turned on and bright. */
//static FLAG_KEEP_SCREEN_ON:number = 0x00000080;
//
///** Window flag: place the window within the entire screen, ignoring
// * decorations around the border (such as the status bar). The
// * window must correctly position its contents to take the screen
// * decoration into account. This flag is normally set for you
// * by Window as described in {@link Window#setFlags}. */
//static FLAG_LAYOUT_IN_SCREEN:number = 0x00000100;
//
///** Window flag: allow window to extend outside of the screen. */
//static FLAG_LAYOUT_NO_LIMITS:number = 0x00000200;
///**
// * Window flag: hide all screen decorations (such as the status bar) while
// * this window is displayed. This allows the window to use the entire
// * display space for itself -- the status bar will be hidden when
// * an app window with this flag set is on the top layer. A fullscreen window
// * will ignore a value of {@link #SOFT_INPUT_ADJUST_RESIZE} for the window's
// * {@link #softInputMode} field; the window will stay fullscreen
// * and will not resize.
// *
// * <p>This flag can be controlled in your theme through the
// * {@link android.R.attr#windowFullscreen} attribute; this attribute
// * is automatically set for you in the standard fullscreen themes
// * such as {@link android.R.style#Theme_NoTitleBar_Fullscreen},
// * {@link android.R.style#Theme_Black_NoTitleBar_Fullscreen},
// * {@link android.R.style#Theme_Light_NoTitleBar_Fullscreen},
// * {@link android.R.style#Theme_Holo_NoActionBar_Fullscreen},
// * {@link android.R.style#Theme_Holo_Light_NoActionBar_Fullscreen},
// * {@link android.R.style#Theme_DeviceDefault_NoActionBar_Fullscreen}, and
// * {@link android.R.style#Theme_DeviceDefault_Light_NoActionBar_Fullscreen}.</p>
// */
//static FLAG_FULLSCREEN:number = 0x00000400;
//
///** Window flag: override {@link #FLAG_FULLSCREEN} and force the
// * screen decorations (such as the status bar) to be shown. */
//static FLAG_FORCE_NOT_FULLSCREEN:number = 0x00000800;
//
///** Window flag: turn on dithering when compositing this window to
// * the screen.
// * @deprecated This flag is no longer used. */
//static FLAG_DITHER:number = 0x00001000;
//
///** Window flag: treat the content of the window as secure, preventing
// * it from appearing in screenshots or from being viewed on non-secure
// * displays.
// *
// * <p>See {@link android.view.Display#FLAG_SECURE} for more details about
// * secure surfaces and secure displays.
// */
//static FLAG_SECURE:number = 0x00002000;
//
///** Window flag: a special mode where the layout parameters are used
// * to perform scaling of the surface when it is composited to the
// * screen. */
//static FLAG_SCALED:number = 0x00004000;
//
///** Window flag: intended for windows that will often be used when the user is
// * holding the screen against their face, it will aggressively filter the event
// * stream to prevent unintended presses in this situation that may not be
// * desired for a particular window, when such an event stream is detected, the
// * application will receive a CANCEL motion event to indicate this so applications
// * can handle this accordingly by taking no action on the event
// * until the finger is released. */
//static FLAG_IGNORE_CHEEK_PRESSES:number = 0x00008000;
//
///** Window flag: a special option only for use in combination with
// * {@link #FLAG_LAYOUT_IN_SCREEN}. When requesting layout in the
// * screen your window may appear on top of or behind screen decorations
// * such as the status bar. By also including this flag, the window
// * manager will report the inset rectangle needed to ensure your
// * content is not covered by screen decorations. This flag is normally
// * set for you by Window as described in {@link Window#setFlags}.*/
//static FLAG_LAYOUT_INSET_DECOR:number = 0x00010000;
//
///** Window flag: invert the state of {@link #FLAG_NOT_FOCUSABLE} with
// * respect to how this window interacts with the current method. That
// * is, if FLAG_NOT_FOCUSABLE is set and this flag is set, then the
// * window will behave as if it needs to interact with the input method
// * and thus be placed behind/away from it; if FLAG_NOT_FOCUSABLE is
// * not set and this flag is set, then the window will behave as if it
// * doesn't need to interact with the input method and can be placed
// * to use more space and cover the input method.
// */
//static FLAG_ALT_FOCUSABLE_IM:number = 0x00020000;
//
/** Window flag: if you have set {@link #FLAG_NOT_TOUCH_MODAL}, you
* can set this flag to receive a single special MotionEvent with
* the action
* {@link MotionEvent#ACTION_OUTSIDE MotionEvent.ACTION_OUTSIDE} for
* touches that occur outside of your window. Note that you will not
* receive the full down/move/up gesture, only the location of the
* first down as an ACTION_OUTSIDE.
*/
static FLAG_WATCH_OUTSIDE_TOUCH:number = 0x00040000;
//
///** Window flag: special flag to let windows be shown when the screen
// * is locked. This will let application windows take precedence over
// * key guard or any other lock screens. Can be used with
// * {@link #FLAG_KEEP_SCREEN_ON} to turn screen on and display windows
// * directly before showing the key guard window. Can be used with
// * {@link #FLAG_DISMISS_KEYGUARD} to automatically fully dismisss
// * non-secure keyguards. This flag only applies to the top-most
// * full-screen window.
// */
//static FLAG_SHOW_WHEN_LOCKED:number = 0x00080000;
//
///** Window flag: ask that the system wallpaper be shown behind
// * your window. The window surface must be translucent to be able
// * to actually see the wallpaper behind it; this flag just ensures
// * that the wallpaper surface will be there if this window actually
// * has translucent regions.
// *
// * <p>This flag can be controlled in your theme through the
// * {@link android.R.attr#windowShowWallpaper} attribute; this attribute
// * is automatically set for you in the standard wallpaper themes
// * such as {@link android.R.style#Theme_Wallpaper},
// * {@link android.R.style#Theme_Wallpaper_NoTitleBar},
// * {@link android.R.style#Theme_Wallpaper_NoTitleBar_Fullscreen},
// * {@link android.R.style#Theme_Holo_Wallpaper},
// * {@link android.R.style#Theme_Holo_Wallpaper_NoTitleBar},
// * {@link android.R.style#Theme_DeviceDefault_Wallpaper}, and
// * {@link android.R.style#Theme_DeviceDefault_Wallpaper_NoTitleBar}.</p>
// */
//static FLAG_SHOW_WALLPAPER:number = 0x00100000;
//
///** Window flag: when set as a window is being added or made
// * visible, once the window has been shown then the system will
// * poke the power manager's user activity (as if the user had woken
// * up the device) to turn the screen on. */
//static FLAG_TURN_SCREEN_ON:number = 0x00200000;
//
///** Window flag: when set the window will cause the keyguard to
// * be dismissed, only if it is not a secure lock keyguard. Because such
// * a keyguard is not needed for security, it will never re-appear if
// * the user navigates to another window (in contrast to
// * {@link #FLAG_SHOW_WHEN_LOCKED}, which will only temporarily
// * hide both secure and non-secure keyguards but ensure they reappear
// * when the user moves to another UI that doesn't hide them).
// * If the keyguard is currently active and is secure (requires an
// * unlock pattern) than the user will still need to confirm it before
// * seeing this window, unless {@link #FLAG_SHOW_WHEN_LOCKED} has
// * also been set.
// */
//static FLAG_DISMISS_KEYGUARD:number = 0x00400000;
/** Window flag: when set the window will accept for touch events
* outside of its bounds to be sent to other windows that also
* support split touch. When this flag is not set, the first pointer
* that goes down determines the window to which all subsequent touches
* go until all pointers go up. When this flag is set, each pointer
* (not necessarily the first) that goes down determines the window
* to which all subsequent touches of that pointer will go until that
* pointer goes up thereby enabling touches with multiple pointers
* to be split across multiple windows.
*/
static FLAG_SPLIT_TOUCH:number = 0x00800000;
///**
// * <p>Indicates whether this window should be hardware accelerated.
// * Requesting hardware acceleration does not guarantee it will happen.</p>
// *
// * <p>This flag can be controlled programmatically <em>only</em> to enable
// * hardware acceleration. To enable hardware acceleration for a given
// * window programmatically, do the following:</p>
// *
// * <pre>
// * Window w = activity.getWindow(); // in Activity's onCreate() for instance
// * w.setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
// * WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
// * </pre>
// *
// * <p>It is important to remember that this flag <strong>must</strong>
// * be set before setting the content view of your activity or dialog.</p>
// *
// * <p>This flag cannot be used to disable hardware acceleration after it
// * was enabled in your manifest using
// * {@link android.R.attr#hardwareAccelerated}. If you need to selectively
// * and programmatically disable hardware acceleration (for automated testing
// * for instance), make sure it is turned off in your manifest and enable it
// * on your activity or dialog when you need it instead, using the method
// * described above.</p>
// *
// * <p>This flag is automatically set by the system if the
// * {@link android.R.attr#hardwareAccelerated android:hardwareAccelerated}
// * XML attribute is set to true on an activity or on the application.</p>
// */
//static FLAG_HARDWARE_ACCELERATED:number = 0x01000000;
//
///**
// * Window flag: allow window contents to extend in to the screen's
// * overscan area, if there is one. The window should still correctly
// * position its contents to take the overscan area into account.
// *
// * <p>This flag can be controlled in your theme through the
// * {@link android.R.attr#windowOverscan} attribute; this attribute
// * is automatically set for you in the standard overscan themes
// * such as
// * {@link android.R.style#Theme_Holo_NoActionBar_Overscan},
// * {@link android.R.style#Theme_Holo_Light_NoActionBar_Overscan},
// * {@link android.R.style#Theme_DeviceDefault_NoActionBar_Overscan}, and
// * {@link android.R.style#Theme_DeviceDefault_Light_NoActionBar_Overscan}.</p>
// *
// * <p>When this flag is enabled for a window, its normal content may be obscured
// * to some degree by the overscan region of the display. To ensure key parts of
// * that content are visible to the user, you can use
// * {@link View#setFitsSystemWindows(boolean) View.setFitsSystemWindows(boolean)}
// * to set the point in the view hierarchy where the appropriate offsets should
// * be applied. (This can be done either by directly calling this function, using
// * the {@link android.R.attr#fitsSystemWindows} attribute in your view hierarchy,
// * or implementing you own {@link View#fitSystemWindows(android.graphics.Rect)
// * View.fitSystemWindows(Rect)} method).</p>
// *
// * <p>This mechanism for positioning content elements is identical to its equivalent
// * use with layout and {@link View#setSystemUiVisibility(int)
// * View.setSystemUiVisibility(int)}; here is an example layout that will correctly
// * position its UI elements with this overscan flag is set:</p>
// *
// * {@sample development/samples/ApiDemos/res/layout/overscan_activity.xml complete}
// */
//static FLAG_LAYOUT_IN_OVERSCAN:number = 0x02000000;
//
///**
// * Window flag: request a translucent status bar with minimal system-provided
// * background protection.
// *
// * <p>This flag can be controlled in your theme through the
// * {@link android.R.attr#windowTranslucentStatus} attribute; this attribute
// * is automatically set for you in the standard translucent decor themes
// * such as
// * {@link android.R.style#Theme_Holo_NoActionBar_TranslucentDecor},
// * {@link android.R.style#Theme_Holo_Light_NoActionBar_TranslucentDecor},
// * {@link android.R.style#Theme_DeviceDefault_NoActionBar_TranslucentDecor}, and
// * {@link android.R.style#Theme_DeviceDefault_Light_NoActionBar_TranslucentDecor}.</p>
// *
// * <p>When this flag is enabled for a window, it automatically sets
// * the system UI visibility flags {@link View#SYSTEM_UI_FLAG_LAYOUT_STABLE} and
// * {@link View#SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.</p>
// */
//static FLAG_TRANSLUCENT_STATUS:number = 0x04000000;
//
///**
// * Window flag: request a translucent navigation bar with minimal system-provided
// * background protection.
// *
// * <p>This flag can be controlled in your theme through the
// * {@link android.R.attr#windowTranslucentNavigation} attribute; this attribute
// * is automatically set for you in the standard translucent decor themes
// * such as
// * {@link android.R.style#Theme_Holo_NoActionBar_TranslucentDecor},
// * {@link android.R.style#Theme_Holo_Light_NoActionBar_TranslucentDecor},
// * {@link android.R.style#Theme_DeviceDefault_NoActionBar_TranslucentDecor}, and
// * {@link android.R.style#Theme_DeviceDefault_Light_NoActionBar_TranslucentDecor}.</p>
// *
// * <p>When this flag is enabled for a window, it automatically sets
// * the system UI visibility flags {@link View#SYSTEM_UI_FLAG_LAYOUT_STABLE} and
// * {@link View#SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}.</p>
// */
//static FLAG_TRANSLUCENT_NAVIGATION:number = 0x08000000;
// ----- HIDDEN FLAGS.
// These start at the high bit and go down.
///**
// * Flag for a window in local focus mode.
// * Window in local focus mode can control focus independent of window manager using
// * {@link Window#setLocalFocus(boolean, boolean)}.
// * Usually window in this mode will not get touch/key events from window manager, but will
// * get events only via local injection using {@link Window#injectInputEvent(InputEvent)}.
// */
//static FLAG_LOCAL_FOCUS_MODE:number = 0x10000000;
//
///** Window flag: Enable touches to slide out of a window into neighboring
// * windows in mid-gesture instead of being captured for the duration of
// * the gesture.
// *
// * This flag changes the behavior of touch focus for this window only.
// * Touches can slide out of the window but they cannot necessarily slide
// * back in (unless the other window with touch focus permits it).
// *
// * {@hide}
// */
//static FLAG_SLIPPERY:number = 0x20000000;
//
///**
// * Flag for a window belonging to an activity that responds to {@link KeyEvent#KEYCODE_MENU}
// * and therefore needs a Menu key. For devices where Menu is a physical button this flag is
// * ignored, but on devices where the Menu key is drawn in software it may be hidden unless
// * this flag is set.
// *
// * (Note that Action Bars, when available, are the preferred way to offer additional
// * functions otherwise accessed via an options menu.)
// *
// * {@hide}
// */
//static FLAG_NEEDS_MENU_KEY:number = 0x40000000;
/**
* is window floating
* @type {number}
*/
static FLAG_FLOATING:number = 0x40000000;
/**
* Various behavioral options/flags. Default is none.
*
* @see #FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
* @see #FLAG_DIM_BEHIND
* @see #FLAG_NOT_FOCUSABLE
* @see #FLAG_NOT_TOUCHABLE
* @see #FLAG_NOT_TOUCH_MODAL
* @see #FLAG_TOUCHABLE_WHEN_WAKING
* @see #FLAG_KEEP_SCREEN_ON
* @see #FLAG_LAYOUT_IN_SCREEN
* @see #FLAG_LAYOUT_NO_LIMITS
* @see #FLAG_FULLSCREEN
* @see #FLAG_FORCE_NOT_FULLSCREEN
* @see #FLAG_SECURE
* @see #FLAG_SCALED
* @see #FLAG_IGNORE_CHEEK_PRESSES
* @see #FLAG_LAYOUT_INSET_DECOR
* @see #FLAG_ALT_FOCUSABLE_IM
* @see #FLAG_WATCH_OUTSIDE_TOUCH
* @see #FLAG_SHOW_WHEN_LOCKED
* @see #FLAG_SHOW_WALLPAPER
* @see #FLAG_TURN_SCREEN_ON
* @see #FLAG_DISMISS_KEYGUARD
* @see #FLAG_SPLIT_TOUCH
* @see #FLAG_HARDWARE_ACCELERATED
* @see #FLAG_LOCAL_FOCUS_MODE
* @see #FLAG_FLOATING
*/
flags:number = 0;
///**
// * If the window has requested hardware acceleration, but this is not
// * allowed in the process it is in, then still render it as if it is
// * hardware accelerated. This is used for the starting preview windows
// * in the system process, which don't need to have the overhead of
// * hardware acceleration (they are just a static rendering), but should
// * be rendered as such to match the actual window of the app even if it
// * is hardware accelerated.
// * Even if the window isn't hardware accelerated, still do its rendering
// * as if it was.
// * Like {@link #FLAG_HARDWARE_ACCELERATED} except for trusted system windows
// * that need hardware acceleration (e.g. LockScreen), where hardware acceleration
// * is generally disabled. This flag must be specified in addition to
// * {@link #FLAG_HARDWARE_ACCELERATED} to enable hardware acceleration for system
// * windows.
// *
// * @hide
// */
//static PRIVATE_FLAG_FAKE_HARDWARE_ACCELERATED:number = 0x00000001;
//
///**
// * In the system process, we globally do not use hardware acceleration
// * because there are many threads doing UI there and they conflict.
// * If certain parts of the UI that really do want to use hardware
// * acceleration, this flag can be set to force it. This is basically
// * for the lock screen. Anyone else using it, you are probably wrong.
// *
// * @hide
// */
//static PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED:number = 0x00000002;
//
///**
// * By default, wallpapers are sent new offsets when the wallpaper is scrolled. Wallpapers
// * may elect to skip these notifications if they are not doing anything productive with
// * them (they do not affect the wallpaper scrolling operation) by calling
// * {@link
// * android.service.wallpaper.WallpaperService.Engine#setOffsetNotificationsEnabled(boolean)}.
// *
// * @hide
// */
//static PRIVATE_FLAG_WANTS_OFFSET_NOTIFICATIONS:number = 0x00000004;
//
///**
// * This is set for a window that has explicitly specified its
// * FLAG_NEEDS_MENU_KEY, so we know the value on this window is the
// * appropriate one to use. If this is not set, we should look at
// * windows behind it to determine the appropriate value.
// *
// * @hide
// */
//static PRIVATE_FLAG_SET_NEEDS_MENU_KEY:number = 0x00000008;
//
///** In a multiuser system if this flag is set and the owner is a system process then this
// * window will appear on all user screens. This overrides the default behavior of window
// * types that normally only appear on the owning user's screen. Refer to each window type
// * to determine its default behavior.
// *
// * {@hide} */
//static PRIVATE_FLAG_SHOW_FOR_ALL_USERS:number = 0x00000010;
//
///**
// * Special flag for the volume overlay: force the window manager out of "hide nav bar"
// * mode while the window is on screen.
// *
// * {@hide} */
//static PRIVATE_FLAG_FORCE_SHOW_NAV_BAR:number = 0x00000020;
//
///**
// * Never animate position changes of the window.
// *
// * {@hide} */
//static PRIVATE_FLAG_NO_MOVE_ANIMATION:number = 0x00000040;
//
///** Window flag: special flag to limit the size of the window to be
// * original size ([320x480] x density). Used to create window for applications
// * running under compatibility mode.
// *
// * {@hide} */
//static PRIVATE_FLAG_COMPATIBLE_WINDOW:number = 0x00000080;
//
///** Window flag: a special option intended for system dialogs. When
// * this flag is set, the window will demand focus unconditionally when
// * it is created.
// * {@hide} */
//static PRIVATE_FLAG_SYSTEM_ERROR:number = 0x00000100;
//
///** Window flag: maintain the previous translucent decor state when this window
// * becomes top-most.
// * {@hide} */
//static PRIVATE_FLAG_INHERIT_TRANSLUCENT_DECOR:number = 0x00000200;
//
///**
// * Control flags that are private to the platform.
// * @hide
// */
//privateFlags:number = 0;
//
///**
// * Given a particular set of window manager flags, determine whether
// * such a window may be a target for an input method when it has
// * focus. In particular, this checks the
// * {@link #FLAG_NOT_FOCUSABLE} and {@link #FLAG_ALT_FOCUSABLE_IM}
// * flags and returns true if the combination of the two corresponds
// * to a window that needs to be behind the input method so that the
// * user can type into it.
// *
// * @param flags The current window manager flags.
// *
// * @return Returns true if such a window should be behind/interact
// * with an input method, false if not.
// */
//static mayUseInputMethod(flags:number):boolean {
// switch(flags & (LayoutParams.FLAG_NOT_FOCUSABLE | LayoutParams.FLAG_ALT_FOCUSABLE_IM)) {
// case 0:
// case LayoutParams.FLAG_NOT_FOCUSABLE | LayoutParams.FLAG_ALT_FOCUSABLE_IM:
// return true;
// }
// return false;
//}
//
///**
// * Mask for {@link #softInputMode} of the bits that determine the
// * desired visibility state of the soft input area for this window.
// */
//static SOFT_INPUT_MASK_STATE:number = 0x0f;
//
///**
// * Visibility state for {@link #softInputMode}: no state has been specified.
// */
//static SOFT_INPUT_STATE_UNSPECIFIED:number = 0;
//
///**
// * Visibility state for {@link #softInputMode}: please don't change the state of
// * the soft input area.
// */
//static SOFT_INPUT_STATE_UNCHANGED:number = 1;
//
///**
// * Visibility state for {@link #softInputMode}: please hide any soft input
// * area when normally appropriate (when the user is navigating
// * forward to your window).
// */
//static SOFT_INPUT_STATE_HIDDEN:number = 2;
//
///**
// * Visibility state for {@link #softInputMode}: please always hide any
// * soft input area when this window receives focus.
// */
//static SOFT_INPUT_STATE_ALWAYS_HIDDEN:number = 3;
//
///**
// * Visibility state for {@link #softInputMode}: please show the soft
// * input area when normally appropriate (when the user is navigating
// * forward to your window).
// */
//static SOFT_INPUT_STATE_VISIBLE:number = 4;
//
///**
// * Visibility state for {@link #softInputMode}: please always make the
// * soft input area visible when this window receives input focus.
// */
//static SOFT_INPUT_STATE_ALWAYS_VISIBLE:number = 5;
//
///**
// * Mask for {@link #softInputMode} of the bits that determine the
// * way that the window should be adjusted to accommodate the soft
// * input window.
// */
//static SOFT_INPUT_MASK_ADJUST:number = 0xf0;
//
///** Adjustment option for {@link #softInputMode}: nothing specified.
// * The system will try to pick one or
// * the other depending on the contents of the window.
// */
//static SOFT_INPUT_ADJUST_UNSPECIFIED:number = 0x00;
//
///** Adjustment option for {@link #softInputMode}: set to allow the
// * window to be resized when an input
// * method is shown, so that its contents are not covered by the input
// * method. This can <em>not</em> be combined with
// * {@link #SOFT_INPUT_ADJUST_PAN}; if
// * neither of these are set, then the system will try to pick one or
// * the other depending on the contents of the window. If the window's
// * layout parameter flags include {@link #FLAG_FULLSCREEN}, this
// * value for {@link #softInputMode} will be ignored; the window will
// * not resize, but will stay fullscreen.
// */
//static SOFT_INPUT_ADJUST_RESIZE:number = 0x10;
//
///** Adjustment option for {@link #softInputMode}: set to have a window
// * pan when an input method is
// * shown, so it doesn't need to deal with resizing but just panned
// * by the framework to ensure the current input focus is visible. This
// * can <em>not</em> be combined with {@link #SOFT_INPUT_ADJUST_RESIZE}; if
// * neither of these are set, then the system will try to pick one or
// * the other depending on the contents of the window.
// */
//static SOFT_INPUT_ADJUST_PAN:number = 0x20;
//
///** Adjustment option for {@link #softInputMode}: set to have a window
// * not adjust for a shown input method. The window will not be resized,
// * and it will not be panned to make its focus visible.
// */
//static SOFT_INPUT_ADJUST_NOTHING:number = 0x30;
//
///**
// * Bit for {@link #softInputMode}: set when the user has navigated
// * forward to the window. This is normally set automatically for
// * you by the system, though you may want to set it in certain cases
// * when you are displaying a window yourself. This flag will always
// * be cleared automatically after the window is displayed.
// */
//static SOFT_INPUT_IS_FORWARD_NAVIGATION:number = 0x100;
//
///**
// * Desired operating mode for any soft input area. May be any combination
// * of:
// *
// * <ul>
// * <li> One of the visibility states
// * {@link #SOFT_INPUT_STATE_UNSPECIFIED}, {@link #SOFT_INPUT_STATE_UNCHANGED},
// * {@link #SOFT_INPUT_STATE_HIDDEN}, {@link #SOFT_INPUT_STATE_ALWAYS_VISIBLE}, or
// * {@link #SOFT_INPUT_STATE_VISIBLE}.
// * <li> One of the adjustment options
// * {@link #SOFT_INPUT_ADJUST_UNSPECIFIED},
// * {@link #SOFT_INPUT_ADJUST_RESIZE}, or
// * {@link #SOFT_INPUT_ADJUST_PAN}.
// * </ul>
// *
// *
// * <p>This flag can be controlled in your theme through the
// * {@link android.R.attr#windowSoftInputMode} attribute.</p>
// */
//softInputMode:number = 0;
//
///**
// * Placement of window within the screen as per {@link Gravity}. Both
// * {@link Gravity#apply(int, int, int, android.graphics.Rect, int, int,
// * android.graphics.Rect) Gravity.apply} and
// * {@link Gravity#applyDisplay(int, android.graphics.Rect, android.graphics.Rect)
// * Gravity.applyDisplay} are used during window layout, with this value
// * given as the desired gravity. For example you can specify
// * {@link Gravity#DISPLAY_CLIP_HORIZONTAL Gravity.DISPLAY_CLIP_HORIZONTAL} and
// * {@link Gravity#DISPLAY_CLIP_VERTICAL Gravity.DISPLAY_CLIP_VERTICAL} here
// * to control the behavior of
// * {@link Gravity#applyDisplay(int, android.graphics.Rect, android.graphics.Rect)
// * Gravity.applyDisplay}.
// *
// * @see Gravity
// */
//gravity:number = 0;
//
///**
// * The horizontal margin, as a percentage of the container's width,
// * between the container and the widget. See
// * {@link Gravity#apply(int, int, int, android.graphics.Rect, int, int,
// * android.graphics.Rect) Gravity.apply} for how this is used. This
// * field is added with {@link #x} to supply the <var>xAdj</var> parameter.
// */
//horizontalMargin:number = 0;
//
///**
// * The vertical margin, as a percentage of the container's height,
// * between the container and the widget. See
// * {@link Gravity#apply(int, int, int, android.graphics.Rect, int, int,
// * android.graphics.Rect) Gravity.apply} for how this is used. This
// * field is added with {@link #y} to supply the <var>yAdj</var> parameter.
// */
//verticalMargin:number = 0;
//
///**
// * The desired bitmap format. May be one of the constants in
// * {@link android.graphics.PixelFormat}. Default is OPAQUE.
// */
//format:number = 0;
//
///**
// * A style resource defining the animations to use for this window.
// * This must be a system resource; it can not be an application resource
// * because the window manager does not have access to applications.
// */
//windowAnimations:number = 0;
exitAnimation:Animation = android.R.anim.activity_close_exit;
enterAnimation:Animation = android.R.anim.activity_open_enter;
resumeAnimation:Animation = android.R.anim.activity_close_enter;
hideAnimation:Animation = android.R.anim.activity_open_exit;
//
///**
// * An alpha value to apply to this entire window.
// * An alpha of 1.0 means fully opaque and 0.0 means fully transparent
// */
//alpha:number = 1.0;
/**
* When {@link #FLAG_DIM_BEHIND} is set, this is the amount of dimming
* to apply. Range is from 1.0 for completely opaque to 0.0 for no
* dim.
*/
dimAmount:number = 0;
///**
// * Default value for {@link #screenBrightness} and {@link #buttonBrightness}
// * indicating that the brightness value is not overridden for this window
// * and normal brightness policy should be used.
// */
//static BRIGHTNESS_OVERRIDE_NONE:number = -1.0;
//
///**
// * Value for {@link #screenBrightness} and {@link #buttonBrightness}
// * indicating that the screen or button backlight brightness should be set
// * to the lowest value when this window is in front.
// */
//static BRIGHTNESS_OVERRIDE_OFF:number = 0.0;
//
///**
// * Value for {@link #screenBrightness} and {@link #buttonBrightness}
// * indicating that the screen or button backlight brightness should be set
// * to the hightest value when this window is in front.
// */
//static BRIGHTNESS_OVERRIDE_FULL:number = 1.0;
///**
// * This can be used to override the user's preferred brightness of
// * the screen. A value of less than 0, the default, means to use the
// * preferred screen brightness. 0 to 1 adjusts the brightness from
// * dark to full bright.
// */
//screenBrightness:number = LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
//
///**
// * This can be used to override the standard behavior of the button and
// * keyboard backlights. A value of less than 0, the default, means to
// * use the standard backlight behavior. 0 to 1 adjusts the brightness
// * from dark to full bright.
// */
//buttonBrightness:number = LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
///**
// * Value for {@link #rotationAnimation} to define the animation used to
// * specify that this window will rotate in or out following a rotation.
// */
//static ROTATION_ANIMATION_ROTATE:number = 0;
//
///**
// * Value for {@link #rotationAnimation} to define the animation used to
// * specify that this window will fade in or out following a rotation.
// */
//static ROTATION_ANIMATION_CROSSFADE:number = 1;
//
///**
// * Value for {@link #rotationAnimation} to define the animation used to
// * specify that this window will immediately disappear or appear following
// * a rotation.
// */
//static ROTATION_ANIMATION_JUMPCUT:number = 2;
//
///**
// * Define the exit and entry animations used on this window when the device is rotated.
// * This only has an affect if the incoming and outgoing topmost
// * opaque windows have the #FLAG_FULLSCREEN bit set and are not covered
// * by other windows. All other situations default to the
// * {@link #ROTATION_ANIMATION_ROTATE} behavior.
// *
// * @see #ROTATION_ANIMATION_ROTATE
// * @see #ROTATION_ANIMATION_CROSSFADE
// * @see #ROTATION_ANIMATION_JUMPCUT
// */
//rotationAnimation:number = LayoutParams.ROTATION_ANIMATION_ROTATE;
///**
// * Identifier for this window. This will usually be filled in for
// * you.
// */
//token:IBinder = null;
///**
// * Name of the package owning this window.
// */
//packageName:string = null;
//
///**
// * Specific orientation value for a window.
// * May be any of the same values allowed
// * for {@link android.content.pm.ActivityInfo#screenOrientation}.
// * If not set, a default value of
// * {@link android.content.pm.ActivityInfo#SCREEN_ORIENTATION_UNSPECIFIED}
// * will be used.
// */
//screenOrientation:number = -1;//ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
//
///**
// * Control the visibility of the status bar.
// *
// * @see View#STATUS_BAR_VISIBLE
// * @see View#STATUS_BAR_HIDDEN
// */
//systemUiVisibility:number = 0;
//
///**
// * @hide
// * The ui visibility as requested by the views in this hierarchy.
// * the combined value should be systemUiVisibility | subtreeSystemUiVisibility.
// */
//subtreeSystemUiVisibility:number = 0;
//
///**
// * Get callbacks about the system ui visibility changing.
// *
// * TODO: Maybe there should be a bitfield of optional callbacks that we need.
// *
// * @hide
// */
//hasSystemUiListeners:boolean;
///**
// * When this window has focus, disable touch pad pointer gesture processing.
// * The window will receive raw position updates from the touch pad instead
// * of pointer movements and synthetic touch events.
// *
// * @hide
// */
//static INPUT_FEATURE_DISABLE_POINTER_GESTURES:number = 0x00000001;
//
///**
// * Does not construct an input channel for this window. The channel will therefore
// * be incapable of receiving input.
// *
// * @hide
// */
//static INPUT_FEATURE_NO_INPUT_CHANNEL:number = 0x00000002;
//
///**
// * When this window has focus, does not call user activity for all input events so
// * the application will have to do it itself. Should only be used by
// * the keyguard and phone app.
// * <p>
// * Should only be used by the keyguard and phone app.
// * </p>
// *
// * @hide
// */
//static INPUT_FEATURE_DISABLE_USER_ACTIVITY:number = 0x00000004;
//
///**
// * Control special features of the input subsystem.
// *
// * @see #INPUT_FEATURE_DISABLE_POINTER_GESTURES
// * @see #INPUT_FEATURE_NO_INPUT_CHANNEL
// * @see #INPUT_FEATURE_DISABLE_USER_ACTIVITY
// * @hide
// */
//inputFeatures:number = 0;
///**
// * Sets the number of milliseconds before the user activity timeout occurs
// * when this window has focus. A value of -1 uses the standard timeout.
// * A value of 0 uses the minimum support display timeout.
// * <p>
// * This property can only be used to reduce the user specified display timeout;
// * it can never make the timeout longer than it normally would be.
// * </p><p>
// * Should only be used by the keyguard and phone app.
// * </p>
// *
// * @hide
// */
//userActivityTimeout:number = -1;
//constructor( ) {
// super(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
// this.type = LayoutParams.TYPE_APPLICATION;
// this.format = PixelFormat.OPAQUE;
//}
constructor(_type=LayoutParams.TYPE_APPLICATION) {
super(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
this.type = _type;
//this.format = PixelFormat.OPAQUE;
}
//constructor( _type:number, _flags:number) {
// super(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
// this.type = _type;
// flags = _flags;
// this.format = PixelFormat.OPAQUE;
//}
//
//constructor( _type:number, _flags:number, _format:number) {
// super(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
// this.type = _type;
// flags = _flags;
// this.format = _format;
//}
//
//constructor( w:number, h:number, _type:number, _flags:number, _format:number) {
// super(w, h);
// this.type = _type;
// flags = _flags;
// this.format = _format;
//}
//constructor( w:number, h:number, xpos:number, ypos:number, _type:number, _flags:number, _format:number) {
// super(w, h);
// this.x = xpos;
// this.y = ypos;
// this.type = _type;
// flags = _flags;
// this.format = _format;
//}
setTitle(title:string):void {
if (null == title) title = "";
this.mTitle = title;//TextUtils.stringOrSpannedString(title);
}
getTitle():string {
return this.mTitle;
}
static LAYOUT_CHANGED:number = 1 << 0;
static TYPE_CHANGED:number = 1 << 1;
static FLAGS_CHANGED:number = 1 << 2;
static FORMAT_CHANGED:number = 1 << 3;
static ANIMATION_CHANGED:number = 1 << 4;
static DIM_AMOUNT_CHANGED:number = 1 << 5;
static TITLE_CHANGED:number = 1 << 6;
static ALPHA_CHANGED:number = 1 << 7;
//
//static MEMORY_TYPE_CHANGED:number = 1 << 8;
//
//static SOFT_INPUT_MODE_CHANGED:number = 1 << 9;
//
//static SCREEN_ORIENTATION_CHANGED:number = 1 << 10;
//
//static SCREEN_BRIGHTNESS_CHANGED:number = 1 << 11;
//
//static ROTATION_ANIMATION_CHANGED:number = 1 << 12;
//
///** {@hide} */
//static BUTTON_BRIGHTNESS_CHANGED:number = 1 << 13;
//
///** {@hide} */
//static SYSTEM_UI_VISIBILITY_CHANGED:number = 1 << 14;
//
///** {@hide} */
//static SYSTEM_UI_LISTENER_CHANGED:number = 1 << 15;
//
///** {@hide} */
//static INPUT_FEATURES_CHANGED:number = 1 << 16;
//
///** {@hide} */
//static PRIVATE_FLAGS_CHANGED:number = 1 << 17;
//
///** {@hide} */
//static USER_ACTIVITY_TIMEOUT_CHANGED:number = 1 << 18;
//
///** {@hide} */
//static TRANSLUCENT_FLAGS_CHANGED:number = 1 << 19;
//
///** {@hide} */
//static EVERYTHING_CHANGED:number = 0xffffffff;
//
//// internal buffer to backup/restore parameters under compatibility mode.
//private mCompatibilityParamsBackup:number[] = null;
copyFrom(o:LayoutParams):number {
let changes:number = 0;
if (this.width != o.width) {
this.width = o.width;
changes |= LayoutParams.LAYOUT_CHANGED;
}
if (this.height != o.height) {
this.height = o.height;
changes |= LayoutParams.LAYOUT_CHANGED;
}
if (this.x != o.x) {
this.x = o.x;
changes |= LayoutParams.LAYOUT_CHANGED;
}
if (this.y != o.y) {
this.y = o.y;
changes |= LayoutParams.LAYOUT_CHANGED;
}
//if (this.horizontalWeight != o.horizontalWeight) {
// this.horizontalWeight = o.horizontalWeight;
// changes |= LayoutParams.LAYOUT_CHANGED;
//}
//if (this.verticalWeight != o.verticalWeight) {
// this.verticalWeight = o.verticalWeight;
// changes |= LayoutParams.LAYOUT_CHANGED;
//}
//if (this.horizontalMargin != o.horizontalMargin) {
// this.horizontalMargin = o.horizontalMargin;
// changes |= LayoutParams.LAYOUT_CHANGED;
//}
//if (this.verticalMargin != o.verticalMargin) {
// this.verticalMargin = o.verticalMargin;
// changes |= LayoutParams.LAYOUT_CHANGED;
//}
if (this.type != o.type) {
this.type = o.type;
changes |= LayoutParams.TYPE_CHANGED;
}
if (this.flags != o.flags) {
const diff:number = this.flags ^ o.flags;
//if ((diff & (LayoutParams.FLAG_TRANSLUCENT_STATUS | LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)) != 0) {
// changes |= LayoutParams.TRANSLUCENT_FLAGS_CHANGED;
//}
this.flags = o.flags;
changes |= LayoutParams.FLAGS_CHANGED;
}
//if (this.privateFlags != o.privateFlags) {
// this.privateFlags = o.privateFlags;
// changes |= LayoutParams.PRIVATE_FLAGS_CHANGED;
//}
//if (this.softInputMode != o.softInputMode) {
// this.softInputMode = o.softInputMode;
// changes |= LayoutParams.SOFT_INPUT_MODE_CHANGED;
//}
if (this.gravity != o.gravity) {
this.gravity = o.gravity;
changes |= LayoutParams.LAYOUT_CHANGED;
}
//if (this.format != o.format) {
// this.format = o.format;
// changes |= LayoutParams.FORMAT_CHANGED;
//}
//if (this.windowAnimations != o.windowAnimations) {
// this.windowAnimations = o.windowAnimations;
// changes |= LayoutParams.ANIMATION_CHANGED;
//}
//if (this.token == null) {
// // NOTE: token only copied if the recipient doesn't
// // already have one.
// this.token = o.token;
//}
//if (this.packageName == null) {
// // NOTE: packageName only copied if the recipient doesn't
// // already have one.
// this.packageName = o.packageName;
//}
if (this.mTitle != (o.mTitle)) {
this.mTitle = o.mTitle;
changes |= LayoutParams.TITLE_CHANGED;
}
//if (this.alpha != o.alpha) {
// this.alpha = o.alpha;
// changes |= LayoutParams.ALPHA_CHANGED;
//}
if (this.dimAmount != o.dimAmount) {
this.dimAmount = o.dimAmount;
changes |= LayoutParams.DIM_AMOUNT_CHANGED;
}
//if (this.screenBrightness != o.screenBrightness) {
// this.screenBrightness = o.screenBrightness;
// changes |= LayoutParams.SCREEN_BRIGHTNESS_CHANGED;
//}
//if (this.buttonBrightness != o.buttonBrightness) {
// this.buttonBrightness = o.buttonBrightness;
// changes |= LayoutParams.BUTTON_BRIGHTNESS_CHANGED;
//}
//if (this.rotationAnimation != o.rotationAnimation) {
// this.rotationAnimation = o.rotationAnimation;
// changes |= LayoutParams.ROTATION_ANIMATION_CHANGED;
//}
//if (this.screenOrientation != o.screenOrientation) {
// this.screenOrientation = o.screenOrientation;
// changes |= LayoutParams.SCREEN_ORIENTATION_CHANGED;
//}
//if (this.systemUiVisibility != o.systemUiVisibility || this.subtreeSystemUiVisibility != o.subtreeSystemUiVisibility) {
// this.systemUiVisibility = o.systemUiVisibility;
// this.subtreeSystemUiVisibility = o.subtreeSystemUiVisibility;
// changes |= LayoutParams.SYSTEM_UI_VISIBILITY_CHANGED;
//}
//if (this.hasSystemUiListeners != o.hasSystemUiListeners) {
// this.hasSystemUiListeners = o.hasSystemUiListeners;
// changes |= LayoutParams.SYSTEM_UI_LISTENER_CHANGED;
//}
//if (this.inputFeatures != o.inputFeatures) {
// this.inputFeatures = o.inputFeatures;
// changes |= LayoutParams.INPUT_FEATURES_CHANGED;
//}
//if (this.userActivityTimeout != o.userActivityTimeout) {
// this.userActivityTimeout = o.userActivityTimeout;
// changes |= LayoutParams.USER_ACTIVITY_TIMEOUT_CHANGED;
//}
return changes;
}
//debug(output:string):string {
// output += "Contents of " + this + ":";
// Log.d("Debug", output);
// output = super.debug("");
// Log.d("Debug", output);
// Log.d("Debug", "");
// Log.d("Debug", "WindowManager.LayoutParams={title=" + this.mTitle + "}");
// return "";
//}
//
//toString():string {
// let sb:StringBuilder = new StringBuilder(256);
// sb.append("WM.LayoutParams{");
// sb.append("(");
// sb.append(this.x);
// sb.append(',');
// sb.append(this.y);
// sb.append(")(");
// sb.append((this.width == LayoutParams.MATCH_PARENT ? "fill" : (this.width == LayoutParams.WRAP_CONTENT ? "wrap" : this.width)));
// sb.append('x');
// sb.append((this.height == LayoutParams.MATCH_PARENT ? "fill" : (this.height == LayoutParams.WRAP_CONTENT ? "wrap" : this.height)));
// sb.append(")");
// if (this.horizontalMargin != 0) {
// sb.append(" hm=");
// sb.append(this.horizontalMargin);
// }
// if (this.verticalMargin != 0) {
// sb.append(" vm=");
// sb.append(this.verticalMargin);
// }
// if (this.gravity != 0) {
// sb.append(" gr=#");
// sb.append(Integer.toHexString(this.gravity));
// }
// if (this.softInputMode != 0) {
// sb.append(" sim=#");
// sb.append(Integer.toHexString(this.softInputMode));
// }
// sb.append(" ty=");
// sb.append(this.type);
// sb.append(" fl=#");
// sb.append(Integer.toHexString(this.flags));
// if (this.privateFlags != 0) {
// if ((this.privateFlags & LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW) != 0) {
// sb.append(" compatible=true");
// }
// sb.append(" pfl=0x").append(Integer.toHexString(this.privateFlags));
// }
// if (this.format != PixelFormat.OPAQUE) {
// sb.append(" fmt=");
// sb.append(this.format);
// }
// if (this.windowAnimations != 0) {
// sb.append(" wanim=0x");
// sb.append(Integer.toHexString(this.windowAnimations));
// }
// if (this.screenOrientation != -1){//ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) {
// sb.append(" or=");
// sb.append(this.screenOrientation);
// }
// if (this.alpha != 1.0) {
// sb.append(" alpha=");
// sb.append(this.alpha);
// }
// if (this.screenBrightness != LayoutParams.BRIGHTNESS_OVERRIDE_NONE) {
// sb.append(" sbrt=");
// sb.append(this.screenBrightness);
// }
// if (this.buttonBrightness != LayoutParams.BRIGHTNESS_OVERRIDE_NONE) {
// sb.append(" bbrt=");
// sb.append(this.buttonBrightness);
// }
// if (this.rotationAnimation != LayoutParams.ROTATION_ANIMATION_ROTATE) {
// sb.append(" rotAnim=");
// sb.append(this.rotationAnimation);
// }
// if (this.systemUiVisibility != 0) {
// sb.append(" sysui=0x");
// sb.append(Integer.toHexString(this.systemUiVisibility));
// }
// if (this.subtreeSystemUiVisibility != 0) {
// sb.append(" vsysui=0x");
// sb.append(Integer.toHexString(this.subtreeSystemUiVisibility));
// }
// if (this.hasSystemUiListeners) {
// sb.append(" sysuil=");
// sb.append(this.hasSystemUiListeners);
// }
// if (this.inputFeatures != 0) {
// sb.append(" if=0x").append(Integer.toHexString(this.inputFeatures));
// }
// if (this.userActivityTimeout >= 0) {
// sb.append(" userActivityTimeout=").append(this.userActivityTimeout);
// }
// sb.append('}');
// return sb.toString();
//}
//
///**
// * Scale the layout params' coordinates and size.
// * @hide
// */
//scale(scale:number):void {
// this.x = Math.floor((this.x * scale + 0.5));
// this.y = Math.floor((this.y * scale + 0.5));
// if (this.width > 0) {
// this.width = Math.floor((this.width * scale + 0.5));
// }
// if (this.height > 0) {
// this.height = Math.floor((this.height * scale + 0.5));
// }
//}
///**
// * Backup the layout parameters used in compatibility mode.
// * @see LayoutParams#restore()
// */
//backup():void {
// let backup:number[] = this.mCompatibilityParamsBackup;
// if (backup == null) {
// // we backup 4 elements, x, y, width, height
// backup = this.mCompatibilityParamsBackup = androidui.util.ArrayCreator.newNumberArray(4);
// }
// backup[0] = this.x;
// backup[1] = this.y;
// backup[2] = this.width;
// backup[3] = this.height;
//}
//
///**
// * Restore the layout params' coordinates, size and gravity
// * @see LayoutParams#backup()
// */
//restore():void {
// let backup:number[] = this.mCompatibilityParamsBackup;
// if (backup != null) {
// this.x = backup[0];
// this.y = backup[1];
// this.width = backup[2];
// this.height = backup[3];
// }
//}
private mTitle:string = "";
private isFocusable():boolean {
return (this.flags & LayoutParams.FLAG_NOT_FOCUSABLE) == 0;
}
private isTouchable():boolean {
return (this.flags & LayoutParams.FLAG_NOT_TOUCHABLE) == 0;
}
private isTouchModal():boolean {
return (this.flags & LayoutParams.FLAG_NOT_TOUCH_MODAL) == 0;
}
private isFloating():boolean {
return (this.flags & LayoutParams.FLAG_FLOATING) != 0;
}
private isSplitTouch():boolean {
return (this.flags & LayoutParams.FLAG_SPLIT_TOUCH) != 0;
}
private isWatchTouchOutside():boolean {
return (this.flags & LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH) != 0;
}
}
}
} | the_stack |
import * as d3 from "d3";
import { assert } from "chai";
import * as Plottable from "../../src";
import * as TestMethods from "../testMethods";
describe("Plots", () => {
describe("SegmentPlot", () => {
describe("rendering", () => {
let div: d3.Selection<HTMLDivElement, any, any, any>;
let xScale: Plottable.Scales.Linear;
let yScale: Plottable.Scales.Linear;
let plot: Plottable.Plots.Segment<number, number>;
beforeEach(() => {
plot = new Plottable.Plots.Segment<number, number>();
div = TestMethods.generateDiv();
xScale = new Plottable.Scales.Linear();
yScale = new Plottable.Scales.Linear();
const data = [
{ x: 1, y: 1, x2: 4, y2: 4 },
{ x: 2, y: 2, x2: 3, y2: 5 },
{ x: 3, y: 3, x2: 5, y2: 2 },
];
plot.addDataset(new Plottable.Dataset(data));
plot.x((d) => d.x, xScale);
plot.y((d) => d.y, yScale);
});
it("renders a line properly", () => {
plot.x2((d) => d.x2);
plot.y2((d) => d.y2);
plot.renderTo(div);
const lines = plot.content().selectAll<Element, any>("line");
assert.strictEqual(lines.size(), plot.datasets()[0].data().length, "line for each datum");
lines.each(function(d, i) {
const line = d3.select(this);
assert.closeTo(TestMethods.numAttr(line, "x1"), xScale.scale(d.x),
window.Pixel_CloseTo_Requirement, `x1 for line ${i}`);
assert.closeTo(TestMethods.numAttr(line, "x2"), xScale.scale(d.x2),
window.Pixel_CloseTo_Requirement, `x2 for line ${i}`);
assert.closeTo(TestMethods.numAttr(line, "y1"), yScale.scale(d.y),
window.Pixel_CloseTo_Requirement, `y1 for line ${i}`);
assert.closeTo(TestMethods.numAttr(line, "y2"), yScale.scale(d.y2),
window.Pixel_CloseTo_Requirement, `y2 for line ${i}`);
});
div.remove();
});
it("renders vertical lines when x2 is not set", () => {
plot.y2((d) => d.y2);
plot.renderTo(div);
const lines = plot.content().selectAll<Element, any>("line");
assert.strictEqual(lines.size(), plot.datasets()[0].data().length, "line for each datum");
lines.each(function(d, i) {
const line = d3.select(this);
assert.strictEqual(TestMethods.numAttr(line, "x1"), TestMethods.numAttr(line, "x2"), `same x for line ${i}`);
});
div.remove();
});
it("renders horizontal lines when y2 is not set", () => {
plot.x2((d) => d.x2);
plot.renderTo(div);
const lines = plot.content().selectAll<Element, any>("line");
assert.strictEqual(lines.size(), plot.datasets()[0].data().length, "line for each datum");
lines.each(function(d, i) {
const line = d3.select(this);
assert.strictEqual(TestMethods.numAttr(line, "y1"), TestMethods.numAttr(line, "y2"), `same y for line ${i}`);
});
div.remove();
});
});
describe("autoranging", () => {
let div: d3.Selection<HTMLDivElement, any, any, any>;
let xScale: Plottable.Scales.Linear;
let yScale: Plottable.Scales.Linear;
let plot: Plottable.Plots.Segment<number, number>;
beforeEach(() => {
div = TestMethods.generateDiv();
plot = new Plottable.Plots.Segment<number, number>();
xScale = new Plottable.Scales.Linear();
yScale = new Plottable.Scales.Linear();
xScale.padProportion(0);
yScale.padProportion(0);
});
it("adjusts the xScale domain with respect to the yScale domain when autorangeMode is set to x", () => {
const staggeredData = [
{ y: 0, x: 0, x2: 1 },
{ y: 1, x: 1, x2: 2 },
];
plot.x((d) => d.x, xScale);
plot.x2((d) => d.x2);
plot.y((d) => d.y, yScale);
plot.addDataset(new Plottable.Dataset(staggeredData));
plot.autorangeMode("x");
plot.renderTo(div);
assert.deepEqual(xScale.domain(), [0, 2], "x domain includes both visible segments");
yScale.domain([-0.5, 0.5]);
assert.deepEqual(xScale.domain(), [0, 1], "x domain includes only the visible segment (first)");
yScale.domain([0.5, 1.5]);
assert.deepEqual(xScale.domain(), [1, 2], "x domain includes only the visible segment (second)");
div.remove();
});
it("adjusts the yScale domain with respect to the xScale domain when autorangeMode is set to y", () => {
const staggeredData = [
{ x: 0, y: 0, y2: 1 },
{ x: 1, y: 1, y2: 2 },
];
plot.x((d) => d.x, xScale);
plot.y((d) => d.y, yScale);
plot.y2((d) => d.y2);
plot.addDataset(new Plottable.Dataset(staggeredData));
plot.autorangeMode("y");
plot.renderTo(div);
assert.deepEqual(yScale.domain(), [0, 2], "y domain includes both visible segments");
xScale.domain([-0.5, 0.5]);
assert.deepEqual(yScale.domain(), [0, 1], "y domain includes only the visible segment (first)");
xScale.domain([0.5, 1.5]);
assert.deepEqual(yScale.domain(), [1, 2], "y domain includes only the visible segment (second)");
div.remove();
});
});
describe("retrieving the entities in a specified area", () => {
let div: d3.Selection<HTMLDivElement, any, any, any>;
let xScale: Plottable.Scales.Linear;
let yScale: Plottable.Scales.Linear;
let plot: Plottable.Plots.Segment<number, number>;
beforeEach(() => {
div = TestMethods.generateDiv();
xScale = new Plottable.Scales.Linear();
yScale = new Plottable.Scales.Linear();
plot = new Plottable.Plots.Segment<number, number>()
.x((d) => d.x, xScale).x2((d) => d.x2)
.y((d) => d.y, yScale).y2((d) => d.y2);
const data = [
{ x: 1, x2: 1, y: 1, y2: 4 },
{ x: 2, x2: 3, y: 4, y2: 3 },
{ x: 4, x2: 5, y: 2, y2: 4 },
{ x: 2, x2: 4, y: 1, y2: 1 },
];
plot.addDataset(new Plottable.Dataset(data)).renderTo(div);
});
it("retrieves the entities that intersect with the bounding box", () => {
const entities = plot.entitiesIn({
topLeft: { x: xScale.scale(0), y: yScale.scale(4.5) },
bottomRight: { x: xScale.scale(2.5), y: yScale.scale(3) },
});
assert.lengthOf(entities, 2, "retrieved 2 entities intersect with the box");
assert.strictEqual(entities[0].index, 0, "the entity of index 0 is retrieved");
assert.strictEqual(entities[1].index, 1, "the entity of index 1 is retrieved");
div.remove();
});
it("retrieves the entities that intersect with given ranges", () => {
const entities = plot.entitiesIn(
{ min: xScale.scale(2.5), max: xScale.scale(4.5) },
{ min: yScale.scale(4.5), max: yScale.scale(2.5) },
);
assert.lengthOf(entities, 2, "retrieved 2 entities intersect with the ranges");
assert.strictEqual(entities[0].index, 1, "the entity of index 1 is retrieved");
assert.strictEqual(entities[1].index, 2, "the entity of index 2 is retrieved");
div.remove();
});
it("retrieves the entity if exactly one of its endpoints is in the ranges", () => {
// vertial segment
checkEntitiesInRange(0, 0.5, 1.5, 1.5, 0.5);
checkEntitiesInRange(0, 0.5, 1.5, 4.5, 3.5);
// diagonal segment with negative slope
checkEntitiesInRange(1, 1.5, 2.5, 4.5, 3.5);
checkEntitiesInRange(1, 2.5, 3.5, 3.5, 2.5);
// diagonal segment with positive slope
checkEntitiesInRange(2, 4.5, 5.5, 4.5, 3.5);
checkEntitiesInRange(2, 3.5, 4.5, 2.5, 1.5);
// horizontal segment
checkEntitiesInRange(3, 1.5, 2.5, 1.5, 0.5);
checkEntitiesInRange(3, 3.5, 4.5, 1.5, 0.5);
div.remove();
});
it("retrieves the entity if both of its endpoints are in the ranges", () => {
// vertial segment
checkEntitiesInRange(0, 0.5, 1.5, 4.5, 0.5);
// diagonal segment with negative slope
checkEntitiesInRange(1, 1.5, 3.5, 4.5, 2.5);
// diagonal segment with positive slope
checkEntitiesInRange(2, 3.5, 5.5, 4.5, 1.5);
// horizontal segment
checkEntitiesInRange(3, 1.5, 4.5, 1.5, 0.5);
div.remove();
});
it("retrieves the entity if it intersects with the ranges with no endpoints inside", () => {
// vertial segment
checkEntitiesInRange(0, 0.5, 1.5, 3.5, 1.5);
// diagonal segment with negative slope
checkEntitiesInRange(1, 2.4, 2.6, 3.6, 3.4);
// diagonal segment with positive slope
checkEntitiesInRange(2, 4.4, 4.6, 3.5, 2.5);
// horizontal segment
checkEntitiesInRange(3, 2.5, 3.5, 1.5, 0.5);
div.remove();
});
it("returns empty array when no entities intersect with the ranges", () => {
const entities = plot.entitiesIn(
{ min: xScale.scale(1.5), max: xScale.scale(2.5) },
{ min: yScale.scale(2.5), max: yScale.scale(1.5) },
);
assert.lengthOf(entities, 0, "no entities intersects with the ranges");
div.remove();
});
it("retrieves undefined from entityNearest when no entities are rendered", () => {
plot.datasets([new Plottable.Dataset([])]);
plot.renderTo(div);
const closest = plot.entityNearest({
x: plot.width() / 2,
y: plot.height() / 2,
});
assert.strictEqual(closest, undefined, "no datum has been retrieved");
div.remove();
});
function checkEntitiesInRange(index: number, x1: number, x2: number, y1: number, y2: number) {
const entities = plot.entitiesIn(
{ min: xScale.scale(x1), max: xScale.scale(x2) },
{ min: yScale.scale(y1), max: yScale.scale(y2) },
);
assert.lengthOf(entities, 1, "retrieved 1 entity that intersects with the box");
assert.strictEqual(entities[0].index, index, `the entity of index ${index} is retrieved`);
}
});
});
}); | the_stack |
import {IHaikuComponent, IRenderer, MountLayout} from '../../api';
import HaikuBase, {GLOBAL_LISTENER_KEY} from '../../HaikuBase';
import {getNodeCompositeId} from '../../HaikuComponent';
import assign from '../../vendor/assign';
import applyLayout from './applyLayout';
import assignAttributes from './assignAttributes';
import createRightClickMenu from './createRightClickMenu';
import createSvgElement from './createSvgElement';
import createTextNode from './createTextNode';
import getElementSize from './getElementSize';
import getLocalDomEventPosition from './getLocalDomEventPosition';
import getTypeAsString from './getTypeAsString';
import isBlankString from './isBlankString';
import isTextNode from './isTextNode';
import normalizeName from './normalizeName';
import removeElement from './removeElement';
import replaceElementWithText from './replaceElementWithText';
const isNil = (v) => {
return v === undefined || v === null;
};
const connectTarget = (virtualNode, domElement) => {
if (virtualNode && typeof virtualNode === 'object') {
// This normally happens in HaikuComponent.hydrateNode, but we might be operating
// as a thin-renderer where no hydration has occurred; so do the bootstrapping here.
if (!virtualNode.__memory) {
virtualNode.__memory = {};
}
// A virtual node can have multiple targets in the DOM due to an implementation
// detail in the Haiku editing environment; FIXME
if (!virtualNode.__memory.targets) {
virtualNode.__memory.targets = [];
}
if (virtualNode.__memory.targets.indexOf(domElement) === -1) {
virtualNode.__memory.targets.push(domElement);
}
}
};
// tslint:disable:variable-name
export default class HaikuDOMRenderer extends HaikuBase implements IRenderer {
mount;
config;
user;
shouldCreateContainer;
constructor (mount, config) {
super();
this.mount = mount;
this.user = {
mouse: {
x: 0,
y: 0,
down: 0,
buttons: [0, 0, 0], // Assume most mouses have 3 buttons?
},
keys: {},
touches: [], // [{ x: 'number', y: 'number' }]
mouches: [], // [{ x: 'number', y: 'number' }] - Both touches and mouse cursor info
};
this.config = config;
this.shouldCreateContainer = true;
// Ensure we don't conflict with existing content in the mount
this.clear();
}
clear () {
if (this.mount) {
while (this.mount.firstChild) {
this.mount.removeChild(this.mount.firstChild);
}
}
}
getMountForComponent (component: IHaikuComponent) {
// The component without a host is the root component, and uses this node.
if (!component.host) {
return this.mount;
}
return component.target && component.target.parentNode;
}
render (virtualContainer, virtualTree, component) {
return HaikuDOMRenderer.renderTree(
// The injected mount is for the case that the caller wants to render into a node
// other than the root node of the context, for example calling render on a subcomponent
this.getMountForComponent(component),
virtualContainer,
[virtualTree],
component,
false, // isPatchOperation
false, // doSkipChildren
);
}
patch (component, deltas) {
// The component upstream may use an empty value to indicate a no-op
if (!deltas || Object.keys(deltas).length < 1) {
return;
}
for (const compositeId in deltas) {
const virtualElement = deltas[compositeId];
const parentVirtualElement = virtualElement.__memory && virtualElement.__memory.parent;
const domTargets = virtualElement.__memory && virtualElement.__memory.targets;
if (!domTargets) {
continue;
}
for (let i = 0; i < domTargets.length; i++) {
const domTarget = domTargets[i];
if (!domTarget.parentNode) {
continue;
}
HaikuDOMRenderer.updateElement(
domTarget, // DOM node
virtualElement, // mana node
domTarget.parentNode, // DOM node
parentVirtualElement, // mana node
component,
true, // isPatchOperation
);
}
}
}
menuize (component) {
return createRightClickMenu(this.mount, component);
}
mixpanel (mixpanelToken, component) {
return mixpanelInit(mixpanelToken, component);
}
hasSizing () {
return this.config && this.config.sizing && this.config.sizing !== 'normal';
}
getZoom () {
return ((this.config && this.config.zoom) || 1.0);
}
getPan () {
return {
x: (this.config && this.config.pan && this.config.pan.x) || 0,
y: (this.config && this.config.pan && this.config.pan.y) || 0,
};
}
createContainer (out: MountLayout = {}): MountLayout {
let size;
if (this.mount) {
size = getElementSize(this.mount);
} else {
console.warn('[haiku dom renderer] mount empty; using fallback size');
size = {x: 1, y: 1};
}
out.layout = {
computed: {
size,
},
};
if (!this.hasSizing() || !this.config.alwaysComputeSizing) {
this.shouldCreateContainer = false;
}
return out;
}
getDocument () {
return this.mount.ownerDocument;
}
getWindow () {
const doc = this.getDocument();
return doc.defaultView || doc.parentWindow;
}
initialize () {
const user = this.user;
const setMouse = (mouseEvent) => {
// Since the mount itself might be subject to sizing styles that we cannot
// use to calculate appropriately, use the top element i.e. the 'artboard'
const topElement = this.mount.childNodes[0];
if (topElement) {
const pos = getLocalDomEventPosition(mouseEvent, topElement);
user.mouse.x = pos.x;
user.mouse.y = pos.y;
}
};
const setTouches = (touchEvent) => {
user.touches.splice(0);
// Since the mount itself might be subject to sizing styles that we cannot
// use to calculate appropriately, use the top element i.e. the 'artboard'
const topElement = this.mount.childNodes[0];
if (topElement) {
for (let i = 0; i < touchEvent.touches.length; i++) {
const touch = touchEvent.touches[i];
const pos = getLocalDomEventPosition(touch, topElement);
user.touches.push(pos);
}
}
};
const setMouches = () => {
user.mouches.splice(0);
// Only treat a mouse like a touch if it is down.
if (user.mouse.down) {
user.mouches.push(user.mouse);
}
user.mouches.push.apply(user.mouches, user.touches);
};
const clearKey = () => {
for (const which in user.keys) {
user.keys[which] = 0;
}
};
const clearMouse = () => {
user.mouse.down = 0;
user.touches.splice(0);
for (let i = 0; i < user.mouse.buttons.length; i++) {
user.mouse.buttons[i] = 0;
}
};
const clearMouch = () => {
user.mouches.splice(0);
};
const clearTouch = () => {
user.touches.splice(0);
};
const doc = this.getDocument();
const win = this.getWindow();
this.mount.addEventListener('mousedown', (mouseEvent) => {
++user.mouse.down;
++user.mouse.buttons[mouseEvent.button];
setMouse(mouseEvent);
setMouches();
});
this.mount.addEventListener('mouseup', (mouseEvent) => {
clearMouse();
clearMouch();
setMouches();
});
let lastMoveTarget;
// NOTE: if there are perf or interop issues that arise from
// attaching event listeners directly to host window,
// could expose a haikuOption for reverting to "attach to mount" behavior
win.addEventListener('mousemove', (mouseEvent) => {
setMouse(mouseEvent);
setMouches();
if (lastMoveTarget !== mouseEvent.target) {
lastMoveTarget = mouseEvent.target;
let moveElement;
// If the move has taken us outside of our component, use the mount
if (this.mount.contains(mouseEvent.target)) {
moveElement = this.getHaikuElementFromTarget(mouseEvent.target);
} else {
moveElement = this.getHaikuElementFromTarget(this.mount);
}
if (moveElement) {
moveElement.triggerHover(mouseEvent);
}
}
});
win.addEventListener('mouseenter', (mouseEvent) => {
clearMouse();
clearMouch();
});
win.addEventListener('mouseleave', (mouseEvent) => {
clearMouse();
clearMouch();
});
this.mount.addEventListener(
'wheel',
(mouseEvent) => {
setMouse(mouseEvent);
setMouches();
},
{
passive: true, // Avoid perf warnings. TODO: Make configurable
},
);
doc.addEventListener('keydown', (keyEvent) => {
if (user.keys[keyEvent.which] === undefined) {
user.keys[keyEvent.which] = 0;
}
++user.keys[keyEvent.which];
});
doc.addEventListener('keyup', (keyEvent) => {
if (user.keys[keyEvent.which] === undefined) {
user.keys[keyEvent.which] = 0;
}
// Known Mac "feature" where keyup never fires while meta key (91) is down
// When right-click menu is toggled we don't get all mouseup events
if (keyEvent.which === 91 || keyEvent.which === 17) {
clearKey();
}
user.keys[keyEvent.which] = 0;
});
// If there's any sizing mode that requires computation of container size
// and alwaysComputeSizing is *disabled*, make an "overriding" assumption
// that we probably want to recompute the container when media queries change.
if (this.hasSizing() && !this.config.alwaysComputeSizing) {
win.addEventListener('resize', () => {
this.shouldCreateContainer = true;
});
win.addEventListener('orientationchange', () => {
this.shouldCreateContainer = true;
});
}
win.addEventListener('blur', (blurEvent) => {
clearKey();
clearMouse();
clearTouch();
clearMouch();
});
win.addEventListener('focus', (blurEvent) => {
clearKey();
clearMouse();
clearTouch();
clearMouch();
});
win.addEventListener(
'touchstart',
(touchEvent) => {
setTouches(touchEvent);
setMouches();
},
{
passive: true, // Avoid perf warnings. TODO: Make configurable
},
);
win.addEventListener('touchend', (touchEvent) => {
clearTouch();
clearMouch();
});
win.addEventListener(
'touchmove',
(touchEvent) => {
setTouches(touchEvent);
setMouches();
},
{
passive: true, // Avoid perf warnings. TODO: Make configurable
},
);
win.addEventListener('touchenter', (touchEvent) => {
clearTouch();
clearMouch();
});
win.addEventListener('touchleave', (touchEvent) => {
clearTouch();
clearMouch();
});
}
decideMountElement (component: IHaikuComponent, selector: string, name: string) {
// For keyboard events, if subscribed to the component, and if the component is the runtime root,
// we automatically attach its handler to window, as this is the 98%-case desired behavior
if (name === 'keyup' || name === 'keydown' || name === 'keypress') {
if (!component.host && `haiku:${component.getComponentId()}` === selector) {
const win = this.getWindow();
return win;
}
}
// Otherwise, fallthrough and assume we want to listen to our own mount element
return this.mount;
}
mountEventListener (component: IHaikuComponent, selector: string, name: string, listener: Function) {
let rewritten = name;
if (name === 'mouseenter') {
rewritten = 'mouseover';
} else if (name === 'mouseleave') {
rewritten = 'mouseout';
}
// Convert haiku:* selectors into proper attribute selectors
let query = selector;
if (selector.slice(0, 6) === 'haiku:') {
query = `[haiku-id="${selector.slice(6)}"]`;
}
const mount = this.decideMountElement(component, selector, name);
// Since elements inside out tree may be added or removed at will, event listener
// management (i.e. cleanup and re-registration) becomes a problem. Rather than solve
// that tangle, we register listeners on our mount element, which is assumed to
// remain through the lifespan of the component, and then delegate the events as
// appropriate per their respective specifications.
mount.addEventListener(rewritten, (domEvent) => {
// If no explicit selector/target for the event, just fire the listener
if (
!selector || selector === GLOBAL_LISTENER_KEY ||
!domEvent || !domEvent.target
) {
listener(null, this.wrapEvent(name, domEvent, null, component));
return;
}
// If no queryable node has been rendered, we can't perform a match
if (!component.target || !component.target.parentNode) {
return;
}
// If the event originated from the element or its descendants
const match = (component.target.parentNode as Element).querySelector(query);
if (match) {
if (this.shouldListenerReceiveEvent(name, rewritten, domEvent, match, mount)) {
listener(
this.getHaikuElementFromTarget(match),
domEvent.target,
this.wrapEvent(name, domEvent, match, component),
);
return;
}
}
});
}
getHaikuElementFromTarget (target) {
return (
target &&
target.haiku &&
target.haiku.element &&
target.haiku.element.__memory &&
target.haiku.element.__memory.element
);
}
shouldListenerReceiveEvent = (name: string, rewritten: string, event, match: Element, mount): boolean => {
if (name === 'hover' || name === 'unhover') {
return event.target === match;
}
if (name === 'keyup' || name === 'keydown' || name === 'keypress') {
// See not about keyboard handling in HaikuDOMRenderer#decideMountElement
if (mount === this.getWindow()) {
return true;
}
}
// Since we subscribe to events from the root element, we rewrite these as 'mouseover' and 'mouseout'
// so we can adequately capture "bubbled" enters/leaves to meet the 99% expectation of users. Then
// we mimic the bubbling logic here so the semantics align with normal DOM semantics
if (name === 'mouseenter' || name === 'mouseleave') {
return (
match === event.target &&
( // Don't fire if the user's mouse went from inside the child into the target
!match.contains ||
!match.contains(event.relatedTarget)
)
);
}
return (
match === event.target ||
(match.contains && match.contains(event.target))
);
};
/**
* @description An opportunity to return an event aligned with our own API semantics.
* Keep in mind that the three elements involved here may be different:
* this.mount - the host node for the component, the node we actually attach listeners to.
* event.target - the element on which the event actually originated
* elementListenedTo - the element that the user is listening to the event on
*/
wrapEvent (eventName: string, nativeEvent, elementListenedTo, hostComponent: IHaikuComponent) {
return nativeEvent;
}
getUser () {
const zoom = this.getZoom();
const pan = this.getPan();
return {
zoom,
pan,
mouse: {
x: (this.user.mouse.x) / zoom,
y: (this.user.mouse.y) / zoom,
z: 0,
down: this.user.mouse.down,
buttons: [...this.user.mouse.buttons],
},
keys: {...this.user.keys},
touches: [...this.user.touches],
mouches: [...this.user.mouches],
};
}
static createTagNode (
domElement,
virtualElement,
parentVirtualElement,
component,
) {
const tagName = normalizeName(getTypeAsString(virtualElement));
const compositeId = getNodeCompositeId(virtualElement);
let newDomElement;
if (SVG_ELEMENT_NAMES[tagName]) {
// SVG
newDomElement = createSvgElement(domElement, tagName);
} else {
// Normal DOM
newDomElement = domElement.ownerDocument.createElement(tagName);
}
// This didn't happen in renderTree because the element didn't exist yet.
if (!newDomElement.haiku) {
newDomElement.haiku = {
// This is used to detect whether the element's host component has changed.
// Don't remove this without understanding the effect on Haiku.app.
component,
explicitStyles: {},
};
}
component.subcacheEnsure(compositeId);
const incomingKey =
virtualElement.key ||
(virtualElement.attributes && virtualElement.attributes.key);
if (incomingKey !== undefined && incomingKey !== null) {
newDomElement.haiku.key = incomingKey;
}
// updateElement recurses down into setAttributes, etc.
HaikuDOMRenderer.updateElement(newDomElement, virtualElement, domElement, parentVirtualElement, component, null);
return newDomElement;
}
static appendChild (
alreadyChildElement,
virtualElement,
parentDomElement,
parentVirtualElement,
component,
) {
const domElementToInsert = isTextNode(virtualElement)
? createTextNode(parentDomElement, virtualElement)
: HaikuDOMRenderer.createTagNode(parentDomElement, virtualElement, parentVirtualElement, component);
applyLayout(domElementToInsert, virtualElement, component);
parentDomElement.appendChild(domElementToInsert);
return domElementToInsert;
}
static replaceElement (
domElement,
virtualElement,
parentDomNode,
parentVirtualElement,
component,
) {
const compositeId = getNodeCompositeId(virtualElement);
component.subcacheClear(compositeId);
const newElement = isTextNode(virtualElement)
? createTextNode(domElement, virtualElement)
: HaikuDOMRenderer.createTagNode(domElement, virtualElement, parentVirtualElement, component);
applyLayout(newElement, virtualElement, component);
parentDomNode.replaceChild(newElement, domElement);
return newElement;
}
static updateElement (
domElement,
virtualElement,
parentNode,
parentVirtualElement,
component,
isPatchOperation,
) {
const compositeId = getNodeCompositeId(virtualElement);
// If a text node, go straight to 'replace' since we don't know the tag name
if (isTextNode(virtualElement)) {
replaceElementWithText(domElement, virtualElement, component);
return virtualElement;
}
if (!domElement.haiku) {
domElement.haiku = {
// This is used to detect whether the element's host component has changed.
// Don't remove this without understanding the effect on Haiku.app.
component,
explicitStyles: {},
};
}
component.subcacheEnsure(compositeId);
if (!domElement.haiku.element) {
// Must clone so we get a correct picture of differences in attributes between runs, e.g. for detecting attribute
// removals
domElement.haiku.element = HaikuDOMRenderer.cloneVirtualElement(virtualElement);
}
const domTagName = domElement.tagName.toLowerCase().trim();
const elName = normalizeName(getTypeAsString(virtualElement));
const virtualElementTagName = elName.toLowerCase().trim();
const incomingKey = virtualElement.key || (virtualElement.attributes && virtualElement.attributes.key);
const existingKey = domElement.haiku && domElement.haiku.key;
const isKeyDifferent = incomingKey !== null && incomingKey !== undefined && incomingKey !== existingKey;
// For so-called 'horizon' elements, we assume that we've ceded control to another renderer,
// so the most we want to do is update the attributes and layout properties, but leave the rest alone
if (!component.isHorizonElement(virtualElement)) {
if (domTagName !== virtualElementTagName) {
return HaikuDOMRenderer.replaceElement(domElement, virtualElement, parentNode, parentVirtualElement, component);
}
if (isKeyDifferent) {
return HaikuDOMRenderer.replaceElement(domElement, virtualElement, parentNode, parentVirtualElement, component);
}
}
if (virtualElement.attributes && typeof virtualElement.attributes === 'object') {
assignAttributes(domElement, virtualElement, component, isPatchOperation);
}
applyLayout(
domElement,
virtualElement,
component,
);
if (incomingKey !== undefined && incomingKey !== null) {
domElement.haiku.key = incomingKey;
}
const instance = (
virtualElement &&
virtualElement.__memory &&
virtualElement.__memory.instance
) || component;
const children = (virtualElement.__memory && virtualElement.__memory.children) || virtualElement.children;
if (Array.isArray(children)) {
// For performance, we don't render children during a patch operation, except in the case
// that we have some text content, which we (hack) need to always assume needs an update.
// TODO: Fix this hack and make smarter
const doSkipChildren = (
isPatchOperation &&
children[0] instanceof Object
);
HaikuDOMRenderer.renderTree(
domElement,
virtualElement,
children,
instance,
isPatchOperation,
doSkipChildren,
);
} else if (!children) {
// In case of falsy virtual children, we still need to remove elements that were already there
HaikuDOMRenderer.renderTree(
domElement,
virtualElement,
[],
instance,
isPatchOperation,
null,
);
}
return domElement;
}
static renderTree (
domElement,
virtualElement,
virtualChildren,
component,
isPatchOperation,
doSkipChildren,
) {
connectTarget(virtualElement, domElement);
const compositeId = getNodeCompositeId(virtualElement);
if (!domElement.haiku) {
domElement.haiku = {
// This is used to detect whether the element's host component has changed.
// Don't remove this without understanding the effect on Haiku.app.
component,
explicitStyles: {},
};
}
domElement.haiku.virtual = virtualElement;
// Must clone so we get a correct picture of differences in attributes
// between runs, e.g. for detecting attribute removals
domElement.haiku.element = HaikuDOMRenderer.cloneVirtualElement(virtualElement);
component.subcacheEnsure(compositeId);
if (!Array.isArray(virtualChildren)) {
return domElement;
}
// For so-called 'horizon' elements, we assume that we've ceded control to another renderer,
// so the most we want to do is update the attributes and layout properties, but leave the rest alone
if (component.isHorizonElement(virtualElement)) {
return domElement;
}
// During patch renders we don't want to drill down and update children as
// we're just going to end up doing a lot of unnecessary DOM writes
if (doSkipChildren) {
return domElement;
}
while (virtualChildren.length > 0 && isBlankString(virtualChildren[0])) {
virtualChildren.shift();
}
// Store a copy of the array here, otherwise we can hit a race where as we remove
// elements from the DOM, the childNodes array gets shifted and the indices get offset, leading
// to removals not occurring properly
const domChildNodes = [];
for (let k = 0; k < domElement.childNodes.length; k++) {
domChildNodes[k] = domElement.childNodes[k];
}
let max = virtualChildren.length;
if (max < domChildNodes.length) {
max = domChildNodes.length;
}
for (let i = 0; i < max; i++) {
const virtualChild = virtualChildren[i];
const domChild = domChildNodes[i];
if (isNil(virtualChild) && !domChild) {
// empty
} else if (isNil(virtualChild) && domChild) {
removeElement(domChild, compositeId, component);
} else {
if (!domChild) {
const insertedElement = HaikuDOMRenderer.appendChild(
null,
virtualChild,
domElement,
virtualElement,
component,
);
connectTarget(virtualChild, insertedElement);
} else {
// Circumstances in which we want to completely *replace* the element:
// - We see that our cached target element is not the one at this location
// - We see that the DOM id doesn't match the incoming one
// - we see that the haiku-id doesn't match the incoming one.
// If we now have an element that is different, we need to trigger a full re-render
// of itself and all of its children, because e.g. url(#...) references will retain pointers to
// old elements and this is the only way to clear the DOM to get a correct render.
const shouldReplace = HaikuDOMRenderer.shouldElementBeReplaced(domChild, virtualChild, component);
if (shouldReplace) {
const newElement = HaikuDOMRenderer.replaceElement(
domChild,
virtualChild,
domElement,
virtualElement,
component,
);
connectTarget(virtualChild, newElement);
} else {
HaikuDOMRenderer.updateElement(
domChild,
virtualChild,
domElement,
virtualElement,
component,
isPatchOperation,
);
connectTarget(virtualChild, domChild);
}
}
}
}
return domElement;
}
static shouldElementBeReplaced (domElement, virtualElement, component) {
if (domElement.haiku) {
const compositeIdNew = getNodeCompositeId(virtualElement);
const compositeIdOld = getNodeCompositeId(domElement.haiku.element);
if (compositeIdNew !== compositeIdOld) {
return true;
}
if (domElement.haiku.component) {
// If the element carried at this node has a different host component,
// we should do a full replacement, since the cache of the two instances
// are different and may result in different (cached) rendering output
if (domElement.haiku.component !== component) {
return true;
}
}
}
return false;
}
static cloneAttributes (attributes) {
if (!attributes) {
return {};
}
const clone = {};
for (const key in attributes) {
clone[key] = attributes[key];
}
return clone;
}
static cloneVirtualElement (virtualElement) {
return {
elementName: virtualElement.elementName,
attributes: HaikuDOMRenderer.cloneAttributes(virtualElement.attributes),
children: (virtualElement.__memory && virtualElement.__memory.children) || virtualElement.children,
__memory: virtualElement.__memory,
};
}
static __name__ = 'HaikuDOMRenderer';
}
const SVG_ELEMENT_NAMES = {
a: true,
altGlyph: true,
altGlyphDef: true,
altGlyphItem: true,
animate: true,
animateColor: true,
animateMotion: true,
animateTransform: true,
circle: true,
clipPath: true,
'color-profile': true,
cursor: true,
defs: true,
desc: true,
discard: true,
ellipse: true,
feBlend: true,
feColorMatrix: true,
feComponentTransfer: true,
feComposite: true,
feConvolveMatrix: true,
feDiffuseLighting: true,
feDisplacementMap: true,
feDistantLight: true,
feFlood: true,
feFuncA: true,
feFuncB: true,
feFuncG: true,
feFuncR: true,
feGaussianBlur: true,
feImage: true,
feMerge: true,
feMergeNode: true,
feMorphology: true,
feOffset: true,
fePointLight: true,
feSpecularLighting: true,
feSpotLight: true,
feTile: true,
feTurbulence: true,
filter: true,
font: true,
'font-face': true,
'font-face-format': true,
'font-face-name': true,
'font-face-src': true,
'font-face-uri': true,
foreignObject: true,
g: true,
glyph: true,
glyphRef: true,
hkern: true,
image: true,
line: true,
linearGradient: true,
marker: true,
mask: true,
metadata: true,
'missing-glyph': true,
mpath: true,
path: true,
pattern: true,
polygon: true,
polyline: true,
radialGradient: true,
rect: true,
script: true,
set: true,
stop: true,
style: true,
svg: true,
switch: true,
symbol: true,
text: true,
textPath: true,
title: true,
tref: true,
tspan: true,
use: true,
view: true,
vkern: true,
};
/* tslint:disable */
const mixpanelSnippetInjector = new Function(`
(function(e,a){if(!a.__SV){var b=window;try{var c,l,i,j=b.location,g=j.hash;c=function(a,b){return(l=a.match(RegExp(b+"=([^&]*)")))?l[1]:null};g&&c(g,"state")&&(i=JSON.parse(decodeURIComponent(c(g,"state"))),"mpeditor"===i.action&&(b.sessionStorage.setItem("_mpcehash",g),history.replaceState(i.desiredHash||"",e.title,j.pathname+j.search)))}catch(m){}var k,h;window['mixpanel']=a;a._i=[];a.init=function(b,c,f){function e(b,a){var c=a.split(".");2==c.length&&(b=b[c[0]],a=c[1]);b[a]=function(){b.push([a].concat(Array.prototype.slice.call(arguments,
0)))}}var d=a;"undefined"!==typeof f?d=a[f]=[]:f="mixpanel";d.people=d.people||[];d.toString=function(b){var a="mixpanel";"mixpanel"!==f&&(a+="."+f);b||(a+=" (stub)");return a};d.people.toString=function(){return d.toString(1)+".people (stub)"};k="disable time_event track track_pageview track_links track_forms register register_once alias unregister identify name_tag set_config reset people.set people.set_once people.unset people.increment people.append people.union people.track_charge people.clear_charges people.delete_user".split(" ");
for(h=0;h<k.length;h++)e(d,k[h]);a._i.push([b,c,f])};a.__SV=1.2;}})(document,window.mixpanel||[]);
`);
/* tslint:enable */
declare var window: any;
const mixpanelInit = (mixpanelToken, component) => {
// Only initialize Mixpanel if we're running in the browser
if (typeof window !== 'undefined') {
// Don't initialize multiple times if multiple components are on the page
if (!window.mixpanel) {
mixpanelSnippetInjector();
const head = document.getElementsByTagName('head')[0];
const script = document.createElement('script');
script.async = true;
script.type = 'text/javascript';
script.src = 'https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js';
head.appendChild(script);
window.mixpanel.init(mixpanelToken, {ip: false});
}
const metadata = (component.bytecode && component.bytecode.metadata) || {};
window.mixpanel.track(
'component:initialize',
assign(
{
platform: 'dom',
},
metadata,
),
);
}
}; | the_stack |
* steganography.js v1.0.3 2017-09-22
*
* Copyright (C) 2012 Peter Eigenschink (http://www.peter-eigenschink.at/)
* Dual-licensed under MIT and Beerware license.
*/
const Cover = function Cover() {};
var util = {
isPrime(n) {
if (isNaN(n) || !isFinite(n) || n % 1 || n < 2) {
return false;
}
if (n % 2 === 0) {
return n === 2;
}
if (n % 3 === 0) {
return n === 3;
}
const m = Math.sqrt(n);
for (let i = 5; i <= m; i += 6) {
if (n % i === 0) {
return false;
}
if (n % (i + 2) === 0) {
return false;
}
}
return true;
},
findNextPrime(n) {
for (let i = n; true; i += 1) {
if (util.isPrime(i)) {
return i;
}
}
},
sum(func, end, options) {
let sum = 0;
options = options || {};
for (let i = options.start || 0; i < end; i += options.inc || 1) {
sum += func(i) || 0;
}
return sum === 0 && options.defValue ? options.defValue : sum;
},
product(func, end, options) {
let prod = 1;
options = options || {};
for (let i = options.start || 0; i < end; i += options.inc || 1) {
prod *= func(i) || 1;
}
return prod === 1 && options.defValue ? options.defValue : prod;
},
createArrayFromArgs(args, index, threshold) {
const ret = new Array(threshold - 1);
for (let i = 0; i < threshold; i += 1) {
ret[i] = args(i >= index ? i + 1 : i);
}
return ret;
},
loadImg(url) {
const image = new Image();
image.src = url;
return image;
},
};
Cover.prototype.config = {
t: 3,
threshold: 1,
codeUnitSize: 16,
args(i) {
return i + 1;
},
messageDelimiter(modMessage, threshold) {
const delimiter = new Array(threshold * 3);
for (let i = 0; i < delimiter.length; i += 1) {
delimiter[i] = 255;
}
return delimiter;
},
messageCompleted(data, i, threshold) {
let done = true;
for (let j = 0; j < 16 && done; j += 1) {
done = done && data[i + j * 4] === 255;
}
return done;
},
};
Cover.prototype.getHidingCapacity = function (image, options) {
options = options || {};
const config = this.config;
const width = options.width || image.width;
const height = options.height || image.height;
const t = options.t || config.t;
const codeUnitSize = options.codeUnitSize || config.codeUnitSize;
return ((t * width * height) / codeUnitSize) >> 0;
};
Cover.prototype.encode = function (message, image, options) {
// Handle image url
if (image.length) {
image = util.loadImg(image);
} else if (image.src) {
image = util.loadImg(image.src);
} else if (!(image instanceof HTMLImageElement)) {
throw new Error(
'IllegalInput: The input image is neither an URL string nor an image.',
);
}
options = options || {};
const config = this.config;
const t = options.t || config.t;
const threshold = options.threshold || config.threshold;
const codeUnitSize = options.codeUnitSize || config.codeUnitSize;
const prime = util.findNextPrime(Math.pow(2, t));
const args = options.args || config.args;
const messageDelimiter =
options.messageDelimiter || config.messageDelimiter;
if (!t || t < 1 || t > 7) {
throw new Error(
'IllegalOptions: Parameter t = " + t + " is not valid: 0 < t < 8',
);
}
const shadowCanvas = document.createElement('canvas');
const shadowCtx = shadowCanvas.getContext('2d');
if (shadowCtx == null) {
throw new Error(
'Canvas does not have 2d context',
);;
}
shadowCanvas.style.display = 'none';
shadowCanvas.width = options.width || image.width;
shadowCanvas.height = options.height || image.height;
if (options.height && options.width) {
shadowCtx.drawImage(image, 0, 0, options.width, options.height);
} else {
shadowCtx.drawImage(image, 0, 0);
}
const imageData = shadowCtx.getImageData(
0,
0,
shadowCanvas.width,
shadowCanvas.height,
);
const data = imageData.data;
// bundlesPerChar ... Count of full t-bit-sized bundles per Character
// overlapping ... Count of bits of the currently handled character which are not handled during each run
// dec ... UTF-16 Unicode of the i-th character of the message
// curOverlapping ... The count of the bits of the previous character not handled in the previous run
// mask ... The raw initial bitmask, will be changed every run and if bits are overlapping
const bundlesPerChar = (codeUnitSize / t) >> 0;
const overlapping = codeUnitSize % t;
const modMessage: Array<number> = [];
let decM;
let oldDec;
let oldMask;
let left;
let right;
let dec;
let curOverlapping;
let mask;
let i;
let j;
for (i = 0; i <= message.length; i += 1) {
dec = message.charCodeAt(i) || 0;
curOverlapping = (overlapping * i) % t;
if (curOverlapping > 0 && oldDec) {
// Mask for the new character, shifted with the count of overlapping bits
mask = Math.pow(2, t - curOverlapping) - 1;
// Mask for the old character, i.e. the t-curOverlapping bits on the right
// of that character
oldMask =
Math.pow(2, codeUnitSize) * (1 - Math.pow(2, -curOverlapping));
left = (dec & mask) << curOverlapping;
right = (oldDec & oldMask) >> (codeUnitSize - curOverlapping);
modMessage.push(left + right);
if (i < message.length) {
mask = Math.pow(2, 2 * t - curOverlapping) * (1 - Math.pow(2, -t));
for (j = 1; j < bundlesPerChar; j += 1) {
decM = dec & mask;
modMessage.push(decM >> ((j - 1) * t + (t - curOverlapping)));
mask <<= t;
}
if ((overlapping * (i + 1)) % t === 0) {
mask = Math.pow(2, codeUnitSize) * (1 - Math.pow(2, -t));
decM = dec & mask;
modMessage.push(decM >> (codeUnitSize - t));
} else if (
((overlapping * (i + 1)) % t) + (t - curOverlapping) <=
t
) {
decM = dec & mask;
modMessage.push(
decM >> ((bundlesPerChar - 1) * t + (t - curOverlapping)),
);
}
}
} else if (i < message.length) {
mask = Math.pow(2, t) - 1;
for (j = 0; j < bundlesPerChar; j += 1) {
decM = dec & mask;
modMessage.push(decM >> (j * t));
mask <<= t;
}
}
oldDec = dec;
}
// Write Data
let offset;
let index;
let subOffset;
const delimiter = messageDelimiter(modMessage, threshold);
let q;
let qS;
for (
offset = 0;
(offset + threshold) * 4 <= data.length &&
offset + threshold <= modMessage.length;
offset += threshold
) {
qS = [];
for (i = 0; i < threshold && i + offset < modMessage.length; i += 1) {
q = 0;
for (
j = offset;
j < threshold + offset && j < modMessage.length;
j += 1
) {
q += modMessage[j] * Math.pow(args(i), j - offset);
}
qS[i] = 255 - prime + 1 + (q % prime);
}
for (
i = offset * 4;
i < (offset + qS.length) * 4 && i < data.length;
i += 4
) {
data[i + 3] = qS[(i / 4) % threshold];
}
subOffset = qS.length;
}
// Write message-delimiter
for (
index = offset + subOffset;
index - (offset + subOffset) < delimiter.length &&
(offset + delimiter.length) * 4 < data.length;
index += 1
) {
data[index * 4 + 3] = delimiter[index - (offset + subOffset)];
}
// Clear remaining data
for (i = (index + 1) * 4 + 3; i < data.length; i += 4) {
data[i] = 255;
}
shadowCtx.putImageData(imageData, 0, 0);
return shadowCanvas.toDataURL();
};
Cover.prototype.decode = function (image, options) {
// Handle image url
if (image.length) {
image = util.loadImg(image);
} else if (image.src) {
image = util.loadImg(image.src);
} else if (!(image instanceof HTMLImageElement)) {
throw new Error(
'IllegalInput: The input image is neither an URL string nor an image.',
);
}
options = options || {};
const config = this.config;
const t = options.t || config.t;
const threshold = options.threshold || config.threshold;
const codeUnitSize = options.codeUnitSize || config.codeUnitSize;
const prime = util.findNextPrime(Math.pow(2, t));
const args = options.args || config.args;
const messageCompleted =
options.messageCompleted || config.messageCompleted;
if (!t || t < 1 || t > 7) {
throw new Error(
'IllegalOptions: Parameter t = " + t + " is not valid: 0 < t < 8',
);
}
const shadowCanvas = document.createElement('canvas');
const shadowCtx = shadowCanvas.getContext('2d');
if (shadowCtx == null) {
throw new Error(
'Canvas does not have 2d context',
);;
}
shadowCanvas.style.display = 'none';
shadowCanvas.width = options.width || image.width;
shadowCanvas.height = options.width || image.height;
if (options.height && options.width) {
shadowCtx.drawImage(image, 0, 0, options.width, options.height);
} else {
shadowCtx.drawImage(image, 0, 0);
}
const imageData = shadowCtx.getImageData(
0,
0,
shadowCanvas.width,
shadowCanvas.height,
);
const data = imageData.data;
const modMessage: Array<number> = [];
let q;
let i;
let k;
let done;
if (threshold === 1) {
for (i = 3, done = false; !done && i < data.length && !done; i += 4) {
done = messageCompleted(data, i, threshold);
if (!done) {
modMessage.push(data[i] - (255 - prime + 1));
}
}
} else {
/* for(k = 0, done=false; !done; k+=1) {
q = [];
for(i=(k*threshold*4)+3; i<(k+1)*threshold*4 && i<data.length && !done; i+=4) {
done = messageCompleted(data,i,threshold);
if(!done) q.push(data[i]-(255-prime+1)); // at Array index (i-((k*threshold*4)+3))/4
}
if(q.length === 0) continue;
// Calculate the coefficients which are the same for any order of the variable, but different for each argument
// i.e. for args[0] coeff=q[0]*(args[1]-args[2])*(args[1]-args[3])*...(args[1]-args[threshold-1])*...*(args[threshold-1]-args[1])*...*(args[threshold-1]-args[threshold-2])
var variableCoefficients = (function(i) {
if(i >= q.length) return [];
return [q[i]*
util.product(function(j) {
if(j !== i) {
return util.product(function(l) {
if(l !== j) return (args(j) - args(l));
}, q.length);
}
}, q.length)].concat(arguments.callee(i+1));
}(0));
// Calculate the coefficients which are different for each order of the variable and for each argument
// i.e. for order=0 and args[0] coeff=args[1]*args[2]*...*args[threshold-1]
var orderVariableCoefficients = function(order, varIndex) {
var workingArgs = util.createArrayFromArgs(args,varIndex,q.length), maxRec = q.length - (order+1);
return (function(startIndex, endIndex, recDepth) {
var recall = arguments.callee;
return util.sum(function(i) {
if(recDepth < maxRec)
return workingArgs[i]*recall(i+1,startIndex+order+2,recDepth+1);
}, endIndex, {"start": startIndex, "defValue": 1});
}(0,order+1,0));
};
// Calculate the common denominator of the whole term
var commonDenominator = util.product(function(i) {
return util.product(function(j) {
if(j !== i) return (args(i) - args(j));
}, q.length);
}, q.length);
for(i = 0; i < q.length; i+=1) {
modMessage.push((((Math.pow(-1,q.length-(i+1))*util.sum(function(j) {
return orderVariableCoefficients(i,j)*
variableCoefficients[j];
}, q.length))%prime)+prime)%prime); // ?divide by commonDenominator?
}
}
*/
}
let message = '';
let charCode = 0;
let bitCount = 0;
const mask = Math.pow(2, codeUnitSize) - 1;
for (i = 0; i < modMessage.length; i += 1) {
charCode += modMessage[i] << bitCount;
bitCount += t;
if (bitCount >= codeUnitSize) {
message += String.fromCharCode(charCode & mask);
bitCount %= codeUnitSize;
charCode = modMessage[i] >> (t - bitCount);
}
}
if (charCode !== 0) {
message += String.fromCharCode(charCode & mask);
}
return message;
};
var cover = new Cover();
export default cover; | the_stack |
module VORLON {
declare var BABYLON;
class DataGenerator {
//ATTRIBUTES
//CONSTRUCTOR
/**
* Constructor.
* Does nothing.
*/
constructor() {
}
//REQUESTS
/**
* Generate data about scenes
* @returns {Array}
* @private
*/
public generateScenesData(scenes) {
var data = [];
scenes.forEach(scene => {
var sceneData = {
activeCameraData: this._generateCameraData(scene.activeCamera),
meshesData: this._generateMeshesData(scene),
//texturesData: this._generateTexturesData(scene),
camerasData: this._generateCamerasData(scene),
lightsData : this._generateLightsData(scene)
//beforeRenderCallbacksData : scene._onBeforeRenderCallbacks.length > 0 ? this._generateBeforeRenderData(scene) : undefined,
//afterRenderCallbacksData : scene._onAfterRenderCallbacks.length > 0 ? this._generateAfterRenderData(scene) : undefined
};
data.push(sceneData);
});
return data;
}
//TOOLS
/**
* Converts a Color3 into a hex string
* @param color
*/
private _color3ToHex = function (color) {
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
return "#" + componentToHex(color.r * 255) + componentToHex(color.g * 255) + componentToHex(color.b * 255);
}
/**
* Round a number with afterComa numbers after the coma.
* @param nbr
* @param afterComa
* @returns {number}
* @private
*/
private _roundNumber(nbr : number, afterComa : number) : number {
var pow = Math.pow(10, afterComa);
return Math.round(pow * nbr) / pow;
}
/**
* Round each x, y and y components of a Vector3
* @param vec
* @param afterComa
* @returns {any}
* @private
*/
private _roundVector3(vec, afterComa : number) {
var result = new BABYLON.Vector3(this._roundNumber(vec.x, 2),
this._roundNumber(vec.y, 2),
this._roundNumber(vec.z, 2)
)
return result;
}
/**
* Generate data object for a material object.
* Result contains name, color, texture.
* @param mat
* @returns {{name: any, ambientColor: string, diffuseColor: string, emissiveColor: string, specularColor: string}}
*/
private _generateMaterialData(mat) {
var data;
data = {
name: mat.name,
ambientColor: mat.ambientColor ? this._color3ToHex(mat.ambientColor) : undefined,
diffuseColor: mat.diffuseColor ? this._color3ToHex(mat.diffuseColor) : undefined,
emissiveColor: mat.emissiveColor ? this._color3ToHex(mat.emissiveColor) : undefined,
specularColor: mat.specularColor ? this._color3ToHex(mat.specularColor) : undefined,
diffuseTexture : mat.diffuseTexture ? this._generateTextureData (mat.diffuseTexture) : undefined
}
return data;
}
/**
* Generate data object for a multi-material object.
* Result contains name, color, texture.
* @param mat
*/
private _generateMultiMaterialData(multimat) {
var subMaterials = [];
multimat.subMaterials.forEach(mat => {
subMaterials.push(this._generateMaterialData(mat));
});
var data = {
name : multimat.name,
subMaterials : subMaterials
};
return data;
}
/**
* Generate data about meshes
* @param scene
* @returns {Array}
* @private
*/
private _generateMeshesData(scene) {
var data = [];
scene.meshes.forEach(mesh => {
data.push({
name: mesh.name,
isVisible : mesh.isVisible,
position: this._roundVector3(mesh.position, 2),
rotation: this._roundVector3(mesh.rotation, 2),
scaling: this._roundVector3(mesh.scaling, 2),
boundingBoxCenter : this._roundVector3(mesh.getBoundingInfo().boundingBox.center, 2),
material : mesh.material && !mesh.material.subMaterials ? this._generateMaterialData(mesh.material) : undefined,
multiMaterial : mesh.material && mesh.material.subMaterials ? this._generateMultiMaterialData(mesh.material) : undefined,
animations : this._generateAnimationData(mesh.animations)
});
});
return data;
}
/**
* Generate data object for a texture object.
* Result contains name, url.
* @param txtr
* @returns {{name: any, url: any}}
* @private
*/
private _generateTextureData(txtr) {
var data = {
name: txtr.name,
url: txtr.url
};
return data;
}
/**
* Generate data about textures of one scene.
* @param scene
* @returns {Array}
* @private
*/
private _generateTexturesData(scene) {
var data = [];
scene.textures.forEach(txtr => {
data.push(this._generateTextureData(txtr));
});
return data;
}
/**
* Generate data about animations of an object
* @param scene
* @returns {Array}
* @private
*/
private _generateAnimationData(animations) {
var data = [];
animations.forEach(anim => {
var keys = anim.getKeys();
data.push({
name : anim.name,
targetProperty : anim.targetProperty,
framePerSecond : anim.framePerSecond,
stopped : anim._stopped,
beginFrame : keys[0].frame,
endFrame : keys[keys.length - 1].frame
});
});
return data;
}
/**
* Generate data for one camera.
* @param cam
* @returns {{name: any, type: (string|string|string), position: any, animations: Array, speed: (any|number), rotation: any, alpha: number, beta: number, radius: number}}
* @private
*/
private _generateCameraData(cam) {
function getCameraType (cam) {
if (cam instanceof BABYLON.FreeCamera) {
return "FreeCamera";
} else if (cam instanceof BABYLON.ArcRotateCamera) {
return "ArcRotateCamera";
} else {
return "Camera";
}
}
var camType = getCameraType(cam);
var camData = {
name : cam.name,
type : camType,
mode : cam.mode == 0 ? 'perspective' : 'orthographic',
layerMask : cam.layerMask.toString(2),
position : this._roundVector3(cam.position,2),
animations : this._generateAnimationData(cam.animations),
speed : camType == "FreeCamera" ? cam.speed : undefined,
rotation : camType == "FreeCamera" ? this._roundVector3(cam.rotation, 2) : undefined,
alpha : camType == "ArcRotateCamera" ? this._roundNumber(cam.alpha, 2) : undefined,
beta : camType == "ArcRotateCamera" ? this._roundNumber(cam.beta, 2) : undefined,
radius : camType == "ArcRotateCamera" ? this._roundNumber(cam.radius, 2) : undefined
}
return camData;
}
/**
* Generate data about cameras of one scene.
* @param scene
* @returns {Array}
* @private
*/
private _generateCamerasData(scene) {
var data = [];
scene.cameras.forEach(cam => {
var camData = this._generateCameraData(cam);
data.push(camData);
});
return data;
}
/**
* Generate data about lights of one scene.
* @param scene
* @returns {Array}
* @private
*/
private _generateLightsData(scene) {
function getLightType (light) {
if (light instanceof BABYLON.PointLight) {
return "PointLight";
} else if (light instanceof BABYLON.HemisphericLight) {
return "HemisphericLight";
} else if (light instanceof BABYLON.SpotLight) {
return "SpotLight";
} else if (light instanceof BABYLON.DirectionalLight) {
return "DirectionalLight";
} else {
return "None";
}
}
var data = [];
scene.lights.forEach(light => {
var lightType = getLightType(light);
data.push({
name : light.name,
position : lightType != 'HemisphericLight' ? this._roundVector3(light.position, 2) : undefined,
diffuse : this._color3ToHex(light.diffuse),
specular : this._color3ToHex(light.specular),
intensity : light.intensity,
type : lightType,
direction : lightType == 'HemisphericLight' ? this._roundVector3(light.direction, 2) : undefined,
groundColor : lightType == 'HemisphericLight' ? this._color3ToHex(light.groundColor) : undefined,
isEnabled : light._isEnabled
});
});
return data;
}
/**
* Generate data about register before render functions of one scene.
* @param scene
* @returns {Array}
* @private
*/
private _generateBeforeRenderData(scene) {
var data = [];
scene._onBeforeRenderCallbacks.forEach(fct => {
data.push({
body : fct.toString(2)
});
});
return data;
}
/**
* Generate data about register after render functions of one scene.
* @param scene
* @returns {Array}
* @private
*/
private _generateAfterRenderData(scene) {
var data = [];
scene._onAfterRenderCallbacks.forEach(fct => {
data.push({
body : fct.toString(2)
});
});
return data;
}
}
/**
* Class for queries sent by dashboard.
* For each new query type, extend this class and
* override findTarget() and execute() function.
*/
class Query {
client;
target;
targetName : string;
sceneID : number;
queryType : QueryTypes;
data;
constructor(client, queryObject) {
this.client = client;
this.queryType = queryObject.queryType;
this.data = queryObject.data;
this.target = null;
this.targetName = null;
this.sceneID = this.data.sceneID;
}
/**
* Execute the query (performs a specific action depending on the type
* of query).
*/
public execute() : void {
}
/**
* Find the object target of the query thanks to its name (targetName)
* and the id of the scene it belongs in (sceneID).
*/
public findTarget() : void {
}
}
/**
* For spotting or unspotting mesh.
* The target is the mesh in question.
*/
class SpotMeshQuery extends Query {
static spottedMeshes : Array <any> = [];
static spottedMeshesMaterials : Array <any> = [];
constructor(client, queryObject) {
super(client, queryObject);
this.targetName = this.data.meshName;
this.findTarget();
}
public execute() : void {
switch (this.queryType) {
case QueryTypes.SPOT_MESH :
this._spotMesh(this.target);
break;
case QueryTypes.UNSPOT_MESH :
this._unspotMesh(this.target);
break;
default :
// not supposed to happen
break;
}
}
public findTarget() : void {
var scene = this.client.scenes[this.sceneID];
this.target = scene.getMeshByName(this.targetName);
}
/**
* Spot a mesh on the scene by (changing its material ? making it blink ? (that'd be nice))
* @param meshName
* @param sceneID
* @private
*/
private _spotMesh(mesh) {
var index = SpotMeshQuery.spottedMeshes.indexOf(mesh);
if (index >= 0) {
return;
}
SpotMeshQuery.spottedMeshes.push(mesh);
SpotMeshQuery.spottedMeshesMaterials.push(mesh.material);
var spotMaterial = new BABYLON.StandardMaterial("spotMaterial", mesh._scene);
spotMaterial.emissiveColor = new BABYLON.Color3(1,0,0);
mesh.material = spotMaterial;
}
/**
* Set initial material on mesh if it was spotted.
* @param mesh
* @private
*/
private _unspotMesh(mesh) {
var index = SpotMeshQuery.spottedMeshes.indexOf(mesh);
if (index < 0) {
return;
}
mesh.material = SpotMeshQuery.spottedMeshesMaterials[index];
SpotMeshQuery.spottedMeshes.splice(index, 1);
SpotMeshQuery.spottedMeshesMaterials.splice(index, 1);
}
}
/**
* Query to turn a light on or off.
*/
class SwitchLightQuery extends Query {
constructor(client, queryObject) {
super(client, queryObject);
this.targetName = queryObject.data.lightName;
this.findTarget();
}
public execute() : void {
switch (this.queryType) {
case QueryTypes.TURN_OFF_LIGHT :
this._turnOffLight(this.target);
break;
case QueryTypes.TURN_ON_LIGHT :
this._turnOnLight(this.target);
break;
default :
// not supposed to happen
break;
}
}
public findTarget() : void {
var scene = this.client.scenes[this.sceneID];
this.target = scene.getLightByName(this.targetName);
}
private _turnOnLight(light) {
light._isEnabled = true;
}
private _turnOffLight(light) {
light._isEnabled = false;
}
}
/**
* Query to hide or display a mesh.
*/
class ToggleMeshVisibilityQuery extends Query {
constructor(client, queryObject) {
super(client, queryObject);
this.targetName = queryObject.data.meshName;
this.findTarget();
}
public execute() : void {
switch (this.queryType) {
case QueryTypes.HIDE_MESH :
this._hideMesh(this.target);
break;
case QueryTypes.DISPLAY_MESH :
this._displayMesh(this.target);
break;
default :
// not supposed to happen
break;
}
}
public findTarget() : void {
var scene = this.client.scenes[this.sceneID];
this.target = scene.getMeshByName(this.targetName);
}
private _hideMesh(mesh) {
mesh.isVisible = false;
}
private _displayMesh(mesh) {
mesh.isVisible = true;
}
}
/**
* Query to display or hide axis of a mesh
*/
class GizmoOnMeshQuery extends Query {
gizmos : Array<any>;
constructor(client, queryObject) {
super(client, queryObject);
this.targetName = queryObject.data.meshName;
this.findTarget();
this.gizmos = [];
}
public execute() : void {
switch (this.queryType) {
case QueryTypes.HIDE_MESH_GIZMO :
this._hideMeshGizmos();
break;
case QueryTypes.DISPLAY_MESH_GIZMO :
this._displayMeshGizmos();
break;
default :
// not supposed to happen
break;
}
}
public findTarget() : void {
var scene = this.client.scenes[this.sceneID];
this.target = scene.getMeshByName(this.targetName);
}
/**
* Build tubes that will be the mesh's axis.
* If the mesh is named meshName, their names will be
* "meshName_xAxis", "meshName_yAxis" and "meshName_zAxis"
*
* @private
*/
private _buildGizmos() {
var scene = this.client.scenes[this.sceneID];
var directions = this.target.getBoundingInfo().boundingBox.directions;
//Start tube at (0,0,0) because it will be automaticaly attached to the mesh when
// we set tube's parent
var center = new BABYLON.Vector3(0,0,0);
var size = 2 * this.target.getBoundingInfo().boundingSphere.radius;
var pathX = [center, center.add(directions[0].scaleInPlace(size))];
this.gizmos[0] = BABYLON.Mesh.CreateTube(this.target.name + '_xAxis', pathX,
0.03, 10, null, scene);
this.gizmos[0].material = new BABYLON.StandardMaterial(this.target.name + "_xAxisMat", scene);
this.gizmos[0].material.emissiveColor = BABYLON.Color3.Red();
var pathY = [center, center.add(directions[1].scaleInPlace(size))];
this.gizmos[1] = BABYLON.Mesh.CreateTube(this.target.name + '_yAxis', pathY,
0.03, 10, null, scene);
this.gizmos[1].material = new BABYLON.StandardMaterial(this.target.name + "_yAxisMat", scene);
this.gizmos[1].material.emissiveColor = BABYLON.Color3.Blue();
var pathZ = [center, center.add(directions[2].scaleInPlace(size))];
this.gizmos[2] = BABYLON.Mesh.CreateTube(this.target.name + '_zAxis', pathZ,
0.03, 10, null, scene);
this.gizmos[2].material = new BABYLON.StandardMaterial(this.target.name + "_zAxisMat", scene);
this.gizmos[2].material.emissiveColor = BABYLON.Color3.Green();
this.gizmos.forEach(g => {
g.parent = this.target;
});
// Exclude guizmos from lights so their color does not change
scene.lights.forEach(l => {
this.gizmos.forEach(g => {
l.excludedMeshes.push(g);
});
});
}
/**
* Search the scene for meshes representing gizmos.
* If found, return true, else return false.
* @returns {boolean}
* @private
*/
private _gizmosAlreadyExist() : boolean {
var scene = this.client.scenes[this.sceneID];
var gizmoX = scene.getMeshByName(this.target.name + '_xAxis');
return gizmoX == undefined ? false : true;
}
/**
* Find mesh axes if they already exist
* @private
*/
private _findGizmos() {
if (!this._gizmosAlreadyExist()) {
return;
}
var scene = this.client.scenes[this.sceneID];
this.gizmos[0] = scene.getMeshByName(this.target.name + '_xAxis');
this.gizmos[1] = scene.getMeshByName(this.target.name + '_yAxis');
this.gizmos[2] = scene.getMeshByName(this.target.name + '_zAxis');
}
/**
* Hide mesh axes
* @private
*/
private _hideMeshGizmos() {
if (!this._gizmosAlreadyExist()) {
this._buildGizmos();
} else {
this._findGizmos();
}
this.gizmos.forEach(g => {
g.isVisible = false;
});
}
/**
* Display mesh axes
* @private
*/
private _displayMeshGizmos() {
if (!this._gizmosAlreadyExist()) {
this._buildGizmos();
} else {
this._findGizmos();
}
this.gizmos.forEach(g => {
g.isVisible = true;
});
}
}
///**
// * For queries about animation (start etc).
// */
//class AnimQuery extends Query {
//
// private animTargetType : AnimTargetTypes;
// private animTargetName : string;
// private animTarget;
// private copyOfTargetAnimations : Array <any>;
// private currentFrame : number;
//
// constructor(client, queryObject) {
// super(client, queryObject);
// this.targetName = this.data.animName;
// this.animTargetName = this.data.animTargetName;
// this.animTargetType = this.data.animTargetType;
// this.copyOfTargetAnimations = [];
// this.findTarget();
// }
//
// public findTarget() : void {
// //might be unnecessary
// this._findAnimTarget();
// var animations = this.animTarget.animations;
// for(var i = 0; i < animations.length; ++i) {
// if (animations[i].name == this.targetName) {
// this.target = animations[i];
// break;
// }
// }
// }
//
// public execute() : void {
// switch (this.queryType) {
// case QueryTypes.START_ANIM :
// this._startAnimation();
// break;
// case QueryTypes.PAUSE_ANIM :
// this._pauseAnimation();
// break;
// case QueryTypes.UNPAUSE_ANIM :
// this._unpauseAnimation();
// break;
// case QueryTypes.STOP_ANIM :
// this._stopAnimation();
// break;
// default :
// console.log("Default case");
// break;
// }
// }
//
// private _startAnimation() {
// var keys = this.target.getKeys();
// this.client.scenes[this.sceneID].beginAnimation(this.animTarget,
// keys[0].frame,
// keys[keys.length - 1].frame,
// true);
// }
//
// private _pauseAnimation() {
// this.currentFrame = this.target.currentFrame;
// this.client.scenes[this.sceneID].stopAnimation(this.animTarget);
// }
//
// private _unpauseAnimation() {
// var keys = this.target.getKeys();
// this.client.scenes[this.sceneID].beginAnimation(this.animTarget,
// this.currentFrame,
// keys[keys.length - 1].frame,
// true);
// }
//
// private _stopAnimation() {
// this.currentFrame = 0;
// this.client.scenes[this.sceneID].stopAnimation(this.animTarget);
// }
//
// private _findAnimTarget() : void {
// switch(this.animTargetType) {
// case AnimTargetTypes.MESH:
// this.animTarget = this.client.scenes[this.sceneID].getMeshByName(this.animTargetName);
// break;
// default:
// break;
// }
// this.copyOfTargetAnimations = this.animTarget.animations.slice();
// }
//}
export class BabylonInspectorClient extends ClientPlugin {
//ATTRIBUTES
private id : string;
private _dataGenerator : DataGenerator;
engine;
scenes;
//CONSTRUCTOR
/**
* Consctructor
*/
constructor() {
super("babylonInspector"); // Name
this._ready = true; // No need to wait
this.id = "BABYLONINSPECTOR";
this._dataGenerator = new DataGenerator();
}
/**
* Return unique id for the plugin.
* @returns {string}
*/
public getID() : string {
return this.id;
}
/**
* Refresh client : sens BABYLON Engine again.
* Override this method with cleanup work that needs to happen
* as the user switches between clients on the dashboard.
*/
public refresh(): void {
if(typeof BABYLON !== 'undefined'){
if (this.engine) {
this._sendScenesData();
} else {
this.engine = this._getBabylonEngine();
this.scenes = this.engine.scenes;
this._sendScenesData();
}
}
}
/**
* Start the clientside code : initilization etc
*/
public startClientSide(): void {
if(typeof BABYLON !== 'undefined' && !BABYLON.Engine.isSupported()) {
//error
} else {
//document.addEventListener("DOMContentLoaded", () => {
this.engine = this._getBabylonEngine();
if (this.engine) {
this.scenes = this.engine.scenes;
this.refresh();
}
//});
}
}
/**
* Handle messages received from the dashboard, on the client.
* Then, send data back to dashboard.
* Received objects must follow pattern :
* {
* type : type of the query
* data : data of the query
* }
*/
public onRealtimeMessageReceivedFromDashboardSide(receivedObject: any): void {
switch (receivedObject.queryType) {
case QueryTypes.SPOT_MESH :
case QueryTypes.UNSPOT_MESH :
new SpotMeshQuery(this, receivedObject).execute();
break;
//case QueryTypes.START_ANIM :
//case QueryTypes.PAUSE_ANIM :
//case QueryTypes.UNPAUSE_ANIM :
//case QueryTypes.STOP_ANIM :
// new AnimQuery(this, receivedObject).execute();
// break;
case QueryTypes.TURN_OFF_LIGHT :
case QueryTypes.TURN_ON_LIGHT :
new SwitchLightQuery(this, receivedObject).execute();
break;
case QueryTypes.DISPLAY_MESH :
case QueryTypes.HIDE_MESH :
new ToggleMeshVisibilityQuery(this, receivedObject).execute();
break;
case QueryTypes.DISPLAY_MESH_GIZMO :
case QueryTypes.HIDE_MESH_GIZMO :
new GizmoOnMeshQuery(this, receivedObject).execute();
break;
default :
break;
}
}
//TOOLS
/**
* Find and return a mesh by scene ID and mesh name.
* @param meshName
* @param sceneID
* @returns {any}
* @private
*/
private _findMesh(meshName : string, sceneID : string) {
if(typeof BABYLON !== 'undefined'){
var id : number = +sceneID;
var scene = this.engine.scenes[id];
var mesh = scene.getMeshByName(meshName);
return mesh;
}
return null;
}
/**
* Send all data about the scenes
* @private
*/
private _sendScenesData() {
if (typeof BABYLON !== 'undefined' && this.scenes) {
var scenesData = this._dataGenerator.generateScenesData(this.scenes);
this.sendToDashboard({
messageType: 'SCENES_DATA',
data: scenesData,
clientURL: window.location.href
});
}
}
/**
* Loop on all objects to fetch BABYLON Engine object.
* @private
*/
private _getBabylonEngine() {
for (var member in window) {
if (typeof BABYLON !== 'undefined' && window[member] instanceof BABYLON.Engine) {
return window[member];
}
}
return null;
}
}
/**
* Register the plugin with vorlon core
*/
Core.RegisterClientPlugin(new BabylonInspectorClient());
} | the_stack |
import expressionBuilder from '../lib/expressionBuilder'
// Require Table and Entity classes
import Table from '../classes/Table'
import Entity from '../classes/Entity'
// Create basic table
const TestTable = new Table({
name: 'test-table',
partitionKey: 'pk'
})
// Create basic entity
const TestEntity = new Entity({
name: 'TestEntity',
attributes: {
pk: { partitionKey: true },
a: 'string',
b: 'string',
c: 'string',
d: 'string',
x: 'string',
y: 'string'
},
table: TestTable
})
describe('expressionBuilder',() => {
it('builds complex expression', () => {
const nested_exp = [
{ attr: 'a', eq: 'b' },
[
{ attr: 'a', ne: 'b' },
{ attr: 'a', exists: true },
[{ attr: 'a', between: ['b','c'] }]
],
[
{ attr: 'a', ne: 'b' },
{ attr: 'a', exists: true }
],
[
{ attr: 'a', ne: 'b' },
{ attr: 'a', exists: true }
],
{ attr: 'd', eq: 'e' },
[
[
{ or: false, attr: 'd', eq: 'e' },
{ or: true, attr: 'y', eq: 'x' },
],
[
{ or: true, attr: 'a', eq: 'b' },
[
{ or: false, attr: 'a', eq: 'b' },
{ or: true, attr: 'a', eq: 'b', negate:true }
]
],
{ or: true, attr: 'a', eq: 'b' },
{ or: true, attr: 'a', eq: 'b' }
]
]
const result = expressionBuilder(nested_exp,TestTable,'TestEntity')
expect(result.names).toEqual({
'#attr1': 'a',
'#attr2': 'a',
'#attr3': 'a',
'#attr4': 'a',
'#attr5': 'a',
'#attr6': 'a',
'#attr7': 'a',
'#attr8': 'a',
'#attr9': 'd',
'#attr10': 'd',
'#attr11': 'y',
'#attr12': 'a',
'#attr13': 'a',
'#attr14': 'a',
'#attr15': 'a',
'#attr16': 'a'
})
expect(result.values).toEqual({
':attr1': 'b',
':attr2': 'b',
':attr4_0': 'b',
':attr4_1': 'c',
':attr5': 'b',
':attr7': 'b',
':attr9': 'e',
':attr10': 'e',
':attr11': 'x',
':attr12': 'b',
':attr13': 'b',
':attr14': 'b',
':attr15': 'b',
':attr16': 'b'
})
expect(result.expression).toBe('#attr1 = :attr1 AND (#attr2 <> :attr2 AND attribute_exists(#attr3) AND (#attr4 between :attr4_0 and :attr4_1)) AND (#attr5 <> :attr5 AND attribute_exists(#attr6)) AND (#attr7 <> :attr7 AND attribute_exists(#attr8)) AND #attr9 = :attr9 AND ((#attr10 = :attr10 OR #attr11 = :attr11) OR (#attr12 = :attr12 AND (#attr13 = :attr13 OR (NOT #attr14 = :attr14))) OR #attr15 = :attr15 OR #attr16 = :attr16)')
})
it('coerces expression input to array', () => {
let result = expressionBuilder({ attr: 'a', eq: 'b' },TestTable,'TestEntity')
expect(result.names).toEqual({ '#attr1': 'a' })
expect(result.values).toEqual({ ':attr1': 'b' })
})
it('fail with conditional operator errors', () => {
expect(() => expressionBuilder({ attr: 'a', eq: 'b', ne: 'b' },TestTable,'TestEntity'))
.toThrow(`You can only supply one filter condition per query. Already using 'eq'`)
expect(() => expressionBuilder({ attr: 'a', eq: 'b', in: ['b'] },TestTable,'TestEntity'))
.toThrow(`You can only supply one filter condition per query. Already using 'eq'`)
expect(() => expressionBuilder({ attr: 'a', eq: 'b', lt: 'b' },TestTable,'TestEntity'))
.toThrow(`You can only supply one filter condition per query. Already using 'eq'`)
expect(() => expressionBuilder({ attr: 'a', eq: 'b', lte: 'b' },TestTable,'TestEntity'))
.toThrow(`You can only supply one filter condition per query. Already using 'eq'`)
expect(() => expressionBuilder({ attr: 'a', eq: 'b', gt: 'b' },TestTable,'TestEntity'))
.toThrow(`You can only supply one filter condition per query. Already using 'eq'`)
expect(() => expressionBuilder({ attr: 'a', eq: 'b', gte: 'b' },TestTable,'TestEntity'))
.toThrow(`You can only supply one filter condition per query. Already using 'eq'`)
expect(() => expressionBuilder({ attr: 'a', eq: 'b', between: ['b','c'] },TestTable,'TestEntity'))
.toThrow(`You can only supply one filter condition per query. Already using 'eq'`)
expect(() => expressionBuilder({ attr: 'a', eq: 'b', exists: false },TestTable,'TestEntity'))
.toThrow(`You can only supply one filter condition per query. Already using 'eq'`)
expect(() => expressionBuilder({ attr: 'a', eq: 'b', contains: 'b' },TestTable,'TestEntity'))
.toThrow(`You can only supply one filter condition per query. Already using 'eq'`)
expect(() => expressionBuilder({ attr: 'a', eq: 'b', beginsWith: 'b' },TestTable,'TestEntity'))
.toThrow(`You can only supply one filter condition per query. Already using 'eq'`)
expect(() => expressionBuilder({ attr: 'a', eq: 'b', type: 'string' },TestTable,'TestEntity'))
.toThrow(`You can only supply one filter condition per query. Already using 'eq'`)
})
it('fails with unknown arguments', () => {
// @ts-expect-error
expect(() => expressionBuilder({ attr: 'a', eq: 'b', invalidArg: true },TestTable,'TestEntity'))
.toThrow(`Invalid expression options: invalidArg`)
})
it('fails with invalid entity', () => {
expect(() => expressionBuilder({ attr: 'a', eq: 'b' },TestTable,'UnknownEntity'))
.toThrow(`'entity' value of 'UnknownEntity' must be a string and a valid table Entity name`)
})
it('fails when no attr or size argument', () => {
expect(() => expressionBuilder({ eq: 'b' },TestTable,'TestEntity'))
.toThrow(`A string for 'attr' or 'size' is required for condition expressions`)
})
it('falls back to table attributes if no entity specified', () => {
let result = expressionBuilder({ attr: 'a', eq: 'b' },TestTable)
expect(result.names).toEqual({ '#attr1': 'a' })
expect(result.values).toEqual({ ':attr1': 'b' })
})
it('uses size value and checks entity attribute', () => {
let result = expressionBuilder({ size: 'a', eq: 'b' },TestTable,'TestEntity')
expect(result.expression).toBe('size(#attr1) = :attr1')
expect(result.names).toEqual({ '#attr1': 'a' })
expect(result.values).toEqual({ ':attr1': 'b' })
})
it('uses size value and checks table attribute', () => {
let result = expressionBuilder({ size: 'a', eq: 'b' },TestTable)
expect(result.expression).toBe('size(#attr1) = :attr1')
expect(result.names).toEqual({ '#attr1': 'a' })
expect(result.values).toEqual({ ':attr1': 'b' })
})
it(`generates an 'eq' clause`, () => {
let result = expressionBuilder({ attr: 'a', eq: 'b' },TestTable,'TestEntity')
expect(result.expression).toBe('#attr1 = :attr1')
expect(result.names).toEqual({ '#attr1': 'a' })
expect(result.values).toEqual({ ':attr1': 'b' })
})
it(`generates an 'eq' clause with null/false values`, () => {
let result = expressionBuilder({ attr: 'a', eq: false },TestTable,'TestEntity')
expect(result.expression).toBe('#attr1 = :attr1')
expect(result.names).toEqual({ '#attr1': 'a' })
expect(result.values).toEqual({ ':attr1': false })
result = expressionBuilder({ attr: 'a', eq: null },TestTable,'TestEntity')
expect(result.expression).toBe('#attr1 = :attr1')
expect(result.names).toEqual({ '#attr1': 'a' })
expect(result.values).toEqual({ ':attr1': null })
result = expressionBuilder({ attr: 'a', eq: '' },TestTable,'TestEntity')
expect(result.expression).toBe('#attr1 = :attr1')
expect(result.names).toEqual({ '#attr1': 'a' })
expect(result.values).toEqual({ ':attr1': '' })
})
it(`generates a 'ne' clause`, () => {
let result = expressionBuilder({ attr: 'a', ne: 'b' },TestTable,'TestEntity')
expect(result.expression).toBe('#attr1 <> :attr1')
expect(result.names).toEqual({ '#attr1': 'a' })
expect(result.values).toEqual({ ':attr1': 'b' })
})
it(`generates an 'ne' clause with null/false values`, () => {
let result = expressionBuilder({ attr: 'a', ne: false },TestTable,'TestEntity')
expect(result.expression).toBe('#attr1 <> :attr1')
expect(result.names).toEqual({ '#attr1': 'a' })
expect(result.values).toEqual({ ':attr1': false })
result = expressionBuilder({ attr: 'a', ne: null },TestTable,'TestEntity')
expect(result.expression).toBe('#attr1 <> :attr1')
expect(result.names).toEqual({ '#attr1': 'a' })
expect(result.values).toEqual({ ':attr1': null })
result = expressionBuilder({ attr: 'a', ne: '' },TestTable,'TestEntity')
expect(result.expression).toBe('#attr1 <> :attr1')
expect(result.names).toEqual({ '#attr1': 'a' })
expect(result.values).toEqual({ ':attr1': '' })
})
it(`generates an 'in' clause`, () => {
let result = expressionBuilder({ attr: 'a', in: ['b','c'] },TestTable,'TestEntity')
expect(result.expression).toBe('#attr1 IN (:attr1_0,:attr1_1)')
expect(result.names).toEqual({ '#attr1': 'a' })
expect(result.values).toEqual({ ':attr1_0': 'b', ':attr1_1': 'c' })
})
it(`generates a 'lt' clause`, () => {
let result = expressionBuilder({ attr: 'a', lt: 'b' },TestTable,'TestEntity')
expect(result.expression).toBe('#attr1 < :attr1')
expect(result.names).toEqual({ '#attr1': 'a' })
expect(result.values).toEqual({ ':attr1': 'b' })
})
it(`generates a 'lte' clause`, () => {
let result = expressionBuilder({ attr: 'a', lte: 'b' },TestTable,'TestEntity')
expect(result.expression).toBe('#attr1 <= :attr1')
expect(result.names).toEqual({ '#attr1': 'a' })
expect(result.values).toEqual({ ':attr1': 'b' })
})
it(`generates a 'gt' clause`, () => {
let result = expressionBuilder({ attr: 'a', gt: 'b' },TestTable,'TestEntity')
expect(result.expression).toBe('#attr1 > :attr1')
expect(result.names).toEqual({ '#attr1': 'a' })
expect(result.values).toEqual({ ':attr1': 'b' })
})
it(`generates a 'gte' clause`, () => {
let result = expressionBuilder({ attr: 'a', gte: 'b' },TestTable,'TestEntity')
expect(result.expression).toBe('#attr1 >= :attr1')
expect(result.names).toEqual({ '#attr1': 'a' })
expect(result.values).toEqual({ ':attr1': 'b' })
})
it(`generates a 'between' clause`, () => {
let result = expressionBuilder({ attr: 'a', between: ['b','c'] },TestTable,'TestEntity')
expect(result.expression).toBe('#attr1 between :attr1_0 and :attr1_1')
expect(result.names).toEqual({ '#attr1': 'a' })
expect(result.values).toEqual({ ':attr1_0': 'b',':attr1_1': 'c' })
})
it(`generates a 'between' clause with 'size'`, () => {
let result = expressionBuilder({ size: 'a', between: ['b','c'] },TestTable,'TestEntity')
expect(result.expression).toBe('size(#attr1) between :attr1_0 and :attr1_1')
expect(result.names).toEqual({ '#attr1': 'a' })
expect(result.values).toEqual({ ':attr1_0': 'b',':attr1_1': 'c' })
})
it(`generates an 'exists' clause`, () => {
let result = expressionBuilder({ attr: 'a', exists: true },TestTable,'TestEntity')
expect(result.expression).toBe('attribute_exists(#attr1)')
expect(result.names).toEqual({ '#attr1': 'a' })
})
it(`generates a 'not exists' clause`, () => {
let result = expressionBuilder({ attr: 'a', exists: false },TestTable,'TestEntity')
expect(result.expression).toBe('attribute_not_exists(#attr1)')
expect(result.names).toEqual({ '#attr1': 'a' })
})
it(`generates a 'contains' clause`, () => {
let result = expressionBuilder({ attr: 'a', contains: 'b' },TestTable,'TestEntity')
expect(result.expression).toBe('contains(#attr1,:attr1)')
expect(result.names).toEqual({ '#attr1': 'a' })
expect(result.values).toEqual({ ':attr1': 'b' })
})
it(`generates a 'beginsWith' clause`, () => {
let result = expressionBuilder({ attr: 'a', beginsWith: 'b' },TestTable,'TestEntity')
expect(result.expression).toBe('begins_with(#attr1,:attr1)')
expect(result.names).toEqual({ '#attr1': 'a' })
expect(result.values).toEqual({ ':attr1': 'b' })
})
it(`generates a 'type' clause`, () => {
let result = expressionBuilder({ attr: 'a', type: 'b' },TestTable,'TestEntity')
expect(result.expression).toBe('attribute_type(#attr1,:attr1)')
expect(result.names).toEqual({ '#attr1': 'a' })
expect(result.values).toEqual({ ':attr1': 'b' })
})
it(`fails when 'between' value is not an array`, () => {
// @ts-expect-error
expect(() => expressionBuilder({ attr: 'a', between: 'b' },TestTable,'TestEntity'))
.toThrow(`'between' conditions require an array with two values.`)
})
it(`fails when 'in' value is not an array`, () => {
// @ts-expect-error
expect(() => expressionBuilder({ attr: 'a', in: 'b' },TestTable,'TestEntity'))
.toThrow(`'in' conditions require an array.`)
})
it(`fails when 'in' clause doesn't have an attr`, () => {
expect(() => expressionBuilder({ size: 'a', in: ['b'] },TestTable,'TestEntity'))
.toThrow(`'in' conditions require an 'attr'.`)
})
it(`fails when 'exists' clause doesn't have an attr`, () => {
expect(() => expressionBuilder({ size: 'a', exists: true },TestTable,'TestEntity'))
.toThrow(`'exists' conditions require an 'attr'.`)
})
it(`fails when 'beginsWith' clause doesn't have an attr`, () => {
expect(() => expressionBuilder({ size: 'a', beginsWith: 'b' },TestTable,'TestEntity'))
.toThrow(`'beginsWith' conditions require an 'attr'.`)
})
it(`fails when 'contains' clause doesn't have an attr`, () => {
expect(() => expressionBuilder({ size: 'a', contains: 'b' },TestTable,'TestEntity'))
.toThrow(`'contains' conditions require an 'attr'.`)
})
it(`fails when 'type' clause doesn't have an attr`, () => {
expect(() => expressionBuilder({ size: 'a', type: 'b' },TestTable,'TestEntity'))
.toThrow(`'type' conditions require an 'attr'.`)
})
it(`fails when no condition is provided`, () => {
expect(() => expressionBuilder({ attr: 'a' },TestTable,'TestEntity'))
.toThrow(`A condition is required`)
})
it('allows 0 in comparaison expression', () => {
expect(() => expressionBuilder({ attr: 'a', lte: 0 },TestTable,'TestEntity'))
.not.toThrow(`A condition is required`)
expect(() => expressionBuilder({ attr: 'a', lt: 0 },TestTable,'TestEntity'))
.not.toThrow(`A condition is required`)
expect(() => expressionBuilder({ attr: 'a', gte: 0 },TestTable,'TestEntity'))
.not.toThrow(`A condition is required`)
expect(() => expressionBuilder({ attr: 'a', gt: 0 },TestTable,'TestEntity'))
.not.toThrow(`A condition is required`)
})
}) | the_stack |
import assert from 'assert'
import lmdb from 'node-lmdb'
import fs from 'fs'
import msgpack from 'msgpack-lite'
import debugLib from 'debug'
import {I, queryTypes, sel, version as versionLib, err, bitHas, bitSet, resultTypes} from '@statecraft/core'
// TODO: Export this cleanly in some way.
import SubGroup from '@statecraft/core/dist/lib/subgroup'
import resolvable from '@josephg/resolvable'
const fieldOps = resultTypes[I.ResultType.Single]
const debug = debugLib('statecraft')
const CONFIG_KEY = Buffer.from('\x01config')
const VERSION_KEY = Buffer.from('\x01v')
// Valid keys are in the [0x02, 0xff) range.
const START_KEY = '\x02'
const END_KEY = '\xff'
const START_SEL = sel(START_KEY, false)
const END_SEL = sel(END_KEY, false)
const V_ZERO = new Uint8Array(8)
// ... At some point it'll make sense for the caller to get more detailed notifications about catchup state.
// For now the promise won't be called until catchup is complete.
const lmdbStore = <Val>(inner: I.Store<Val>, location: string): Promise<I.Store<Val>> => {
const env = new lmdb.Env()
// console.log('inner', inner)
if (inner.storeInfo.sources.length !== 1) {
// It would be trivial though.
throw new Error('LMDB store with multiple sources not implemented')
}
const source: I.Source = inner.storeInfo.sources[0]
// Check that the directory exists.
try { fs.mkdirSync(location) }
catch(e) { if (e.code !== 'EEXIST') throw e }
env.open({path: location, maxDbs: 2, noTls: true})
const dbi = env.openDbi({name: null, create: true})
// const configdb = env.openDbi({name: 'config', create: true})
// Note: I'm using 'native' Prozess version numbers, so the local store
// starts at version 0 and event 1 moves us to version 1.
let version: I.Version = new Uint8Array()
const setVersion = (txn: lmdb.Txn, v: I.Version) => {
version = v
txn.putBinary(dbi, VERSION_KEY, Buffer.from(version))
}
// Ok, first do catchup.
{
const txn = env.beginTxn()
const configBytes = txn.getBinary(dbi, CONFIG_KEY)
if (configBytes == null) {
// console.log('Database was created - no config!')
txn.putBinary(dbi, CONFIG_KEY, msgpack.encode({sc_ver: 1, source}))
setVersion(txn, new Uint8Array(8))
} else {
const {sc_ver, source:dbSource} = msgpack.decode(configBytes)
assert(sc_ver === 1, 'LDMB database was set up using invalid or old statecraft version.')
assert(dbSource === source, `LDMB database at ${location} is invalid. Delete and restart`)
version = new Uint8Array(txn.getBinary(dbi, VERSION_KEY))
}
txn.commit()
}
debug('Opened database at version', version)
const ready = resolvable()
// const ready = inner.start!([version])
// TODO: Generate these based on the opstore.
const capabilities = {
queryTypes: bitSet(I.QueryType.AllKV, I.QueryType.KV, I.QueryType.StaticRange, I.QueryType.Range),
mutationTypes: bitSet(I.ResultType.KV),
}
const decode = (bytes: Buffer | null): [Uint8Array, any] => {
if (bytes == null) return [V_ZERO, null]
else {
const [vBuf, data] = msgpack.decode(bytes)
return [new Uint8Array(vBuf), data]
}
}
const rawGet = (txn: lmdb.Txn, k: I.Key) => decode(txn.getBinaryUnsafe(dbi, k))
// TODO: Probably cleaner to write this as iterators? This is simpler / more
// understandable though.
const getKVResults = (dbTxn: lmdb.Txn, query: Iterable<I.Key>, opts: I.FetchOpts, resultsOut: Map<I.Key, Val>) => {
let maxVersion = V_ZERO
for (let k of query) {
const [lastMod, doc] = rawGet(dbTxn, k)
if (doc != null) resultsOut.set(k, opts.noDocs ? 1 : doc)
// Note we update maxVersion even if the document is null.
maxVersion = versionLib.vMax(maxVersion, lastMod)
}
return maxVersion
}
const getAllResults = (dbTxn: lmdb.Txn, opts: I.FetchOpts, resultsOut: Map<I.Key, Val>) => {
let maxVersion = V_ZERO
const cursor = new lmdb.Cursor(dbTxn, dbi)
let k = cursor.goToRange('\x02') // positioned right after config key
while (k != null) {
const bytes = cursor.getCurrentBinaryUnsafe()
const [lastMod, doc] = decode(bytes)
if (doc != null) resultsOut.set(k as string, opts.noDocs ? 1 : doc)
maxVersion = versionLib.vMax(maxVersion, lastMod)
k = cursor.goToNext()
}
cursor.close()
return maxVersion
}
const setCursor = (cursor: lmdb.Cursor, sel: I.StaticKeySelector) => {
let {k, isAfter} = sel
let ck = cursor.goToRange(k < START_KEY ? START_KEY : k) as null | string
if (ck === k && isAfter) ck = cursor.goToNext() as null | string
return ck === null || ck >= END_KEY ? null : ck
}
const moveCursor = (cursor: lmdb.Cursor, offset: number): string | null => {
while (true) {
const key = (offset > 0 ? cursor.goToNext() : cursor.goToPrev()) as null | string
// if (key == null) return offset > 0 ? END_KEY : START_KEY
if (key == null || key < START_KEY || key >= END_KEY) return null
offset += offset > 0 ? -1 : 1
if (offset == 0) return key
}
}
const bakeSel = (cursor: lmdb.Cursor, sel: I.KeySelector): I.StaticKeySelector => {
// This is a bit ugly, and I'm sure there's a nicer way to write this.
// This function could instead be written to just return a key.
let {k, isAfter} = sel
let offset = sel.offset || 0
if (k < START_KEY) { k = START_KEY; isAfter = false }
else if (k >= END_KEY) { k = END_KEY; isAfter = false }
let ck = setCursor(cursor, sel)
// let ck = cursor.goToRange(k) as null | string
// if (ck == k && isAfter) ck = cursor.goToNext() as null | string
// There's no key at or after the specified point.
if (ck == null) {
if (offset >= 0) return {k, isAfter} // Also valid: END_SEL.
else {
// offset is negative, so we're counting back from the end of the database.
ck = cursor.goToLast() as null | string
if (ck == null || ck < START_KEY) return START_SEL // Db is empty.
offset++
}
}
if (offset && (ck = moveCursor(cursor, offset)) == null) {
return offset > 0 ? END_SEL : START_SEL
} else return {k: ck, isAfter: false}
}
const bakeRange = (dbTxn: lmdb.Txn, {low, high, limit, reverse}: I.Range): I.StaticRange => {
const cursor = new lmdb.Cursor(dbTxn, dbi)
let lowBake = bakeSel(cursor, low)
let highBake = bakeSel(cursor, high)
if (limit != null) {
const fromBake = reverse ? highBake : lowBake
const toBake = reverse ? lowBake : highBake
if (sel.gtSel(toBake, fromBake)) {
setCursor(cursor, fromBake)
const limitEnd = moveCursor(cursor, reverse ? -limit : limit)
if (limitEnd != null && (reverse ? limitEnd < toBake.k : limitEnd > toBake.k)) {
toBake.k = limitEnd
toBake.isAfter = false // ?? I think this is right...
}
if (reverse) { lowBake = toBake }
else { highBake = toBake }
}
}
cursor.close()
return {low: lowBake, high: highBake, reverse}
}
function *rangeContentIter(dbTxn: lmdb.Txn, {low, high, reverse}: I.StaticRange) {
const cursor = new lmdb.Cursor(dbTxn, dbi)
const from = reverse ? high : low
const to = reverse ? low : high
let key = setCursor(cursor, from)
while (key != null
&& (reverse ? sel.kGt(key, to) : sel.kLt(key, to))) {
// This is awkward. Probably better to just break if we drop outside the range.
if (key >= START_KEY && key < END_KEY) yield [key, cursor.getCurrentBinaryUnsafe()] as [string, Buffer]
key = cursor.goToNext() as null | string
}
cursor.close()
}
const fetch: I.FetchFn<Val> = (query, opts = {}) => {
// console.log('lmdb fetch', query, opts)
if (!bitHas(capabilities.queryTypes, query.type)) return Promise.reject(new err.UnsupportedTypeError(`${query.type} not supported by lmdb store`))
const qops = queryTypes[query.type]
let bakedQuery: I.Query | undefined
const dbTxn = env.beginTxn({readOnly: true})
let results: I.ResultData<Val>
// KV txn. Query is a set of keys.
let maxVersion: I.Version
switch (query.type) {
case I.QueryType.KV:
results = new Map<I.Key, Val>()
maxVersion = getKVResults(dbTxn, query.q, opts, results)
break
case I.QueryType.AllKV:
results = new Map<I.Key, Val>()
maxVersion = getAllResults(dbTxn, opts, results)
break
case I.QueryType.Range:
bakedQuery = {type: I.QueryType.StaticRange, q: query.q.slice()}
case I.QueryType.StaticRange: {
const q = query.q as I.RangeQuery // | I.StaticRangeQuery
maxVersion = V_ZERO
results = q.map((range) => {
const staticRange = (query.type === I.QueryType.Range) ? bakeRange(dbTxn, range) : (range as I.StaticRange)
const docs = [] // A map might be nicer.
for (const [k, bytes] of rangeContentIter(dbTxn, staticRange)) {
const [lastMod, doc] = decode(bytes)
maxVersion = versionLib.vMax(maxVersion, lastMod)
docs.push([k, doc])
}
return docs
})
break
}
default: return Promise.reject(new err.UnsupportedTypeError(`${query.type} not supported by lmdb store`))
}
// = query.type === 'kv'
// ? getKVResults(dbTxn, query.q, opts, results)
// : getAllResults(dbTxn, opts, results)
dbTxn.abort()
// console.log('lmdb fetch', results, maxVersion, version)
return Promise.resolve({
bakedQuery,
results,
versions: [{from: maxVersion, to: version}]
})
}
const subGroup = new SubGroup({initialVersion: [version], fetch, getOps: inner.getOps.bind(inner)})
const store: I.Store<Val> = {
storeInfo: {
uid: `lmdb(${inner.storeInfo.uid})`, // TODO: Maybe just re-expose inner.storeinfo.uid? All kv wraps should be identical
sources: [source],
capabilities,
},
async mutate(type, _txn, versions, opts = {}) {
// TODO: Refactor this out by implementing internalDidChange
if (type !== I.ResultType.KV) throw new err.UnsupportedTypeError()
const txn = _txn as I.KVTxn<Val>
// await ready
debug('mutate', txn)
const expectedVersion = (versions && versions[0] != null) ? versions[0]! : version
// Check that the transaction applies cleanly.
const dbTxn = env.beginTxn({readOnly: true})
for (const [k, op] of txn) {
const [v, data] = rawGet(dbTxn, k)
if (expectedVersion.length && versionLib.vCmp(v, expectedVersion) > 0) {
dbTxn.abort()
return Promise.reject(new err.WriteConflictError('Write conflict in key ' + k))
}
try {
if (fieldOps.checkOp) {
fieldOps.checkOp(op, fieldOps.create(data))
}
} catch (e) {
dbTxn.abort()
return Promise.reject(e)
}
}
dbTxn.abort()
// console.log('sendTxn', txn, expectedVersion)
// const resultVersion = await sendTxn(client, txn, opts.meta || {}, version, {})
// We know its valid at the current version, so we're ok to pass that here.
const innerV = versions == null ? [version] : versions.slice()
innerV[0] = version
const result = await inner.mutate(I.ResultType.KV, txn, innerV, opts)
debug('mutate cb', result)
return result
},
fetch,
getOps: inner.getOps.bind(inner),
subscribe: subGroup.create.bind(subGroup),
close() {
// close the lmdb database.
dbi.close()
env.close()
// We take ownership, so this makes sense.
inner.close()
},
}
;(async () => {
for await (const cu of inner.subscribe({type: I.QueryType.AllKV, q: true}, {fromVersion: [version]})) {
if (cu.replace) throw new Error('LMDB stores inner store replacing data is not implemented')
// console.log('lmdb store got update', cu)
let evtTxn = env.beginTxn()
let nextVersion = new Uint8Array()
for (let i = 0; i < cu.txns.length; i++) {
const {txn, meta, versions} = cu.txns[i]
const toV = versions[0]
if (toV == null) throw new Error('Invalid catchup data - null version in txn')
const txn_ = txn as I.KVTxn<Val>
for (const [k, op] of txn_) {
// const oldData = fieldOps.create(rawGet(dbTxn, k)[0], op)
const oldData = rawGet(evtTxn, k)[1]
const newData = fieldOps.apply(oldData, op)
// console.log('updated key', k, 'from', oldData, 'to', newData)
// I'm leaving an empty entry in the lmdb database even if newData is
// null so fetch will correctly report last modified versions.
// This can be stripped with a periodically updating baseVersion if
// thats useful.
evtTxn.putBinary(dbi, k, msgpack.encode([Buffer.from(toV), newData]))
}
// nextVersion = toV
}
nextVersion = cu.toVersion[0]!
// TODO: Consider setting subgroup minversion here.
subGroup.onOp(0, version, cu.txns)
// console.log('setversion', nextVersion)
setVersion(evtTxn, nextVersion)
evtTxn.commit()
if (cu.caughtUp) ready.resolve()
}
})()
return ready.then(() => store)
// return Promise.resolve(store)
}
export default lmdbStore | the_stack |
import { getSynopsis } from 'parsing';
const LANGUAGE_ID = 'javascript';
describe('JavaScript Functions', () => {
test('Function expression with no parameters', async () => {
const code = `function hello() {
console.log('Hello, world!');
}`;
const synopsis = getSynopsis(code, LANGUAGE_ID, code);
expect(synopsis).toEqual({
kind: 'function',
params: [],
returns: false
});
});
test('Function expression with required parameters', async () => {
const code = `function printKeyValue(key, value) {
console.log(key + ' : ' + value);
}`;
const synopsis = getSynopsis(code, LANGUAGE_ID, code);
const params = [
{
name: 'key',
required: true,
},
{
name: 'value',
required: true,
},
]
expect(synopsis).toEqual({
kind: 'function',
params,
returns: false
});
});
test('Function expression with optional parameters', async () => {
const code = `function printKeyValue(key, value = 'default') {
console.log(key + ' : ' + value);
}`;
const synopsis = getSynopsis(code, LANGUAGE_ID, code);
const params = [
{
name: 'key',
required: true,
},
{
name: 'value',
required: false,
defaultValue: 'default',
},
]
expect(synopsis).toEqual({
kind: 'function',
params,
returns: false
});
});
test('Function expression with export statement', async () => {
const code = `export function printKeyValue(key, value = 'default') {
console.log(key + ' : ' + value);
}`;
const synopsis = getSynopsis(code, LANGUAGE_ID, code);
const params = [
{
name: 'key',
required: true,
},
{
name: 'value',
required: false,
defaultValue: 'default',
},
];
expect(synopsis).toEqual({
kind: 'function',
params,
returns: false
});
});
test('Function expression with export default statement with function name', async () => {
const code = `export default function printKeyValue(key, value = 'default') {
console.log(key + ' : ' + value);
}`;
const synopsis = getSynopsis(code, LANGUAGE_ID, code);
const params = [
{
name: 'key',
required: true,
},
{
name: 'value',
required: false,
defaultValue: 'default',
},
]
expect(synopsis).toEqual({
kind: 'function',
params,
returns: false
});
});
test('Function expression with return statement', async () => {
const code = `function hello() {
return false;
}`;
const synopsis = getSynopsis(code, LANGUAGE_ID, code);
expect(synopsis).toEqual({
kind: 'function',
params: [],
returns: true
});
});
test('Nested function', async () => {
const code = `function hello() {
function bar() {
return 'bar';
}
console.log('hello');
}`;
const synopsis = getSynopsis(code, LANGUAGE_ID, code);
expect(synopsis).toEqual({
kind: 'function',
params: [],
returns: false
});
});
test('Arrow function with no return or params', async () => {
const code = `const hello = () => {
console.log('hello world');
}`;
const synopsis = getSynopsis(code, LANGUAGE_ID, code);
expect(synopsis).toEqual({
kind: 'function',
params: [],
returns: false
});
});
test('Arrow function with parameters', async () => {
const code = `const printKeyValue = (key, value) => {
console.log(key + ' : ' + value);
}`;
const synopsis = getSynopsis(code, LANGUAGE_ID, code);
const params = [
{
name: 'key',
required: true,
},
{
name: 'value',
required: true,
},
];
expect(synopsis).toEqual({
kind: 'function',
params,
returns: false
});
});
test('Arrow function with return', async () => {
const code = `const hello = () => {
return false;
}`;
const synopsis = getSynopsis(code, LANGUAGE_ID, code);
expect(synopsis).toEqual({
kind: 'function',
params: [],
returns: true
});
});
test('Variable declared function', async () => {
const code = `export const school = function(id) {
return schools.doc(id);
}`;
const synopsis = getSynopsis(code, LANGUAGE_ID, code);
expect(synopsis).toEqual({
kind: 'function',
params: [{
name: 'id',
required: true,
}],
returns: true
});
});
test('Variable declared function optional param', async () => {
const code = `export const school = function(id = "default") {
return schools.doc(id);
}`;
const synopsis = getSynopsis(code, LANGUAGE_ID, code);
expect(synopsis).toEqual({
kind: 'function',
params: [{
name: 'id',
required: false,
defaultValue: 'default',
}],
returns: true
});
});
test('Method with no parameters', async () => {
const classCode = `
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
// Getter
get area() {
return this.calcArea();
}
// Method
calcArea() {
return this.height * this.width;
}
}
`;
const funcInClass = `
calcArea() {
return this.height * this.width;
}`;
const synopsis = getSynopsis(funcInClass, LANGUAGE_ID, classCode);
expect(synopsis).toEqual({
kind: 'function',
params: [],
returns: true
});
});
test('Method with parameters', async () => {
const classCode = `
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
// Getter
get area() {
return this.calcArea();
}
// Method
calcArea() {
return this.height * this.width;
}
areaMultiplied(multipliedBy) {
return multipliedBy * calcArea();
}
}`;
const funcInClass = `
areaMultiplied(multipliedBy) {
return multipliedBy * calcArea();
}`;
const synopsis = getSynopsis(funcInClass, LANGUAGE_ID, classCode);
const params = [
{
name: 'multipliedBy',
required: true,
}
];
expect(synopsis).toEqual({
kind: 'function',
params,
returns: true
});
});
test('Method with no return', async () => {
const classCode = `
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
// Getter
get area() {
return this.calcArea();
}
// Method
hello() {
console.log('hello world');
}
}
`;
const funcInClass = `
hello() {
console.log('hello world');
}`;
const synopsis = getSynopsis(funcInClass, LANGUAGE_ID, classCode);
expect(synopsis).toEqual({
kind: 'function',
params: [],
returns: false
});
});
test('Method with extra whitespace', async () => {
const classCode = `
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
// Getter
get area() {
return this.calcArea();
}
// Method
hello() {
console.log('hello world');
}
}
`;
const funcInClass = `\n\n
hello() {
console.log('hello world');
} `;
const synopsis = getSynopsis(funcInClass, LANGUAGE_ID, classCode);
expect(synopsis).toEqual({
kind: 'function',
params: [],
returns: false
});
});
test('Async method', async () => {
const code = `
const mintlifyFiles = async () => {
const errors = [];
const mints = [];
return {
mints,
errors
};
}`;
const synopsis = getSynopsis(code, LANGUAGE_ID, code);
expect(synopsis).toEqual({
kind: 'function',
params: [],
returns: true
});
});
test('Function with rest parameters', async () => {
const code = `
const printKeyValue = (...args) => {
console.log(args);
}`;
const synopsis = getSynopsis(code, LANGUAGE_ID, code);
const params = [
{
name: 'args',
required: true,
}
];
expect(synopsis).toEqual({
kind: 'function',
params,
returns: false
});
});
/*
functions it can't parse:
default export with no function name
https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export
export default function () {}
*/
});
describe('JavaScript Classes', () => {
test('Class with no extends', async () => {
const code = `
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
// Getter
get area() {
return this.calcArea();
}
// Method
calcArea() {
return this.height * this.width;
}
}
`;
const synopsis = getSynopsis(code, LANGUAGE_ID, code);
expect(synopsis).toEqual({
kind: 'class'
});
});
test('Class that extends another Class', async () => {
const code = `
class Square extends Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
// Getter
get area() {
return this.calcArea();
}
// Method
calcArea() {
return this.height * this.width;
}
}
`;
const synopsis = getSynopsis(code, LANGUAGE_ID, code);
expect(synopsis).toEqual({
kind: 'class',
extends: 'Rectangle'
});
});
});
describe('JavaScript Unspecified', () => {
test('One line of variable declaration', async () => {
const code = "const a = 'a'";
const synopsis = getSynopsis(code, LANGUAGE_ID, code);
expect(synopsis).toEqual({
kind: 'unspecified'
});
});
test('Two lines of code', async () => {
const code = `
const a = 'a';
const b = 'b';
`;
const synopsis = getSynopsis(code, LANGUAGE_ID, code);
expect(synopsis).toEqual({
kind: 'unspecified'
});
});
test('One line of calling a function', async () => {
const code = 'fun();';
const synopsis = getSynopsis(code, LANGUAGE_ID, code);
expect(synopsis).toEqual({
kind: 'unspecified'
});
});
}); | the_stack |
import {Mutable, Proto, Arrays, ObserverType} from "@swim/util";
import type {FastenerOwner, Fastener} from "@swim/component";
import {
AnyConstraintExpression,
ConstraintExpression,
ConstraintVariable,
ConstraintProperty,
ConstraintRelation,
AnyConstraintStrength,
ConstraintStrength,
Constraint,
ConstraintScope,
ConstraintContext,
} from "@swim/constraint";
import type {AnyView, View} from "./View";
import {ViewRelationInit, ViewRelationClass, ViewRelation} from "./ViewRelation";
/** @internal */
export type ViewRefType<F extends ViewRef<any, any>> =
F extends ViewRef<any, infer V> ? V : never;
/** @public */
export interface ViewRefInit<V extends View = View> extends ViewRelationInit<V> {
extends?: {prototype: ViewRef<any, any>} | string | boolean | null;
key?: string | boolean;
}
/** @public */
export type ViewRefDescriptor<O = unknown, V extends View = View, I = {}> = ThisType<ViewRef<O, V> & I> & ViewRefInit<V> & Partial<I>;
/** @public */
export interface ViewRefClass<F extends ViewRef<any, any> = ViewRef<any, any>> extends ViewRelationClass<F> {
}
/** @public */
export interface ViewRefFactory<F extends ViewRef<any, any> = ViewRef<any, any>> extends ViewRefClass<F> {
extend<I = {}>(className: string, classMembers?: Partial<I> | null): ViewRefFactory<F> & I;
define<O, V extends View = View>(className: string, descriptor: ViewRefDescriptor<O, V>): ViewRefFactory<ViewRef<any, V>>;
define<O, V extends View = View>(className: string, descriptor: {observes: boolean} & ViewRefDescriptor<O, V, ObserverType<V>>): ViewRefFactory<ViewRef<any, V>>;
define<O, V extends View = View, I = {}>(className: string, descriptor: {implements: unknown} & ViewRefDescriptor<O, V, I>): ViewRefFactory<ViewRef<any, V> & I>;
define<O, V extends View = View, I = {}>(className: string, descriptor: {implements: unknown; observes: boolean} & ViewRefDescriptor<O, V, I & ObserverType<V>>): ViewRefFactory<ViewRef<any, V> & I>;
<O, V extends View = View>(descriptor: ViewRefDescriptor<O, V>): PropertyDecorator;
<O, V extends View = View>(descriptor: {observes: boolean} & ViewRefDescriptor<O, V, ObserverType<V>>): PropertyDecorator;
<O, V extends View = View, I = {}>(descriptor: {implements: unknown} & ViewRefDescriptor<O, V, I>): PropertyDecorator;
<O, V extends View = View, I = {}>(descriptor: {implements: unknown; observes: boolean} & ViewRefDescriptor<O, V, I & ObserverType<V>>): PropertyDecorator;
}
/** @public */
export interface ViewRef<O = unknown, V extends View = View> extends ViewRelation<O, V>, ConstraintScope, ConstraintContext {
(): V | null;
(view: AnyView<V> | null, target?: View | null, key?: string): O;
/** @override */
get fastenerType(): Proto<ViewRef<any, any>>;
/** @protected @override */
onInherit(superFastener: Fastener): void;
readonly view: V | null;
getView(): V;
setView(view: AnyView<V> | null, target?: View | null, key?: string): V | null;
attachView(view?: AnyView<V>, target?: View | null): V;
detachView(): V | null;
insertView(parent?: View | null, view?: AnyView<V>, target?: View | null, key?: string): V;
removeView(): V | null;
deleteView(): V | null;
/** @internal @override */
bindView(view: View, target: View | null): void;
/** @internal @override */
unbindView(view: View): void;
/** @override */
detectView(view: View): V | null;
constraint(lhs: AnyConstraintExpression, relation: ConstraintRelation, rhs?: AnyConstraintExpression, strength?: AnyConstraintStrength): Constraint;
/** @internal */
readonly constraints: ReadonlyArray<Constraint>;
/** @override */
hasConstraint(constraint: Constraint): boolean;
/** @override */
addConstraint(constraint: Constraint): void;
/** @override */
removeConstraint(constraint: Constraint): void;
/** @override */
activateConstraint(constraint: Constraint): void;
/** @override */
deactivateConstraint(constraint: Constraint): void;
/** @override */
constraintVariable(name: string, value?: number, strength?: AnyConstraintStrength): ConstraintProperty<unknown, number>;
/** @internal */
readonly constraintVariables: ReadonlyArray<ConstraintVariable>;
/** @override */
hasConstraintVariable(variable: ConstraintVariable): boolean;
/** @override */
addConstraintVariable(variable: ConstraintVariable): void;
/** @override */
removeConstraintVariable(variable: ConstraintVariable): void;
/** @override */
activateConstraintVariable(constraintVariable: ConstraintVariable): void;
/** @override */
deactivateConstraintVariable(constraintVariable: ConstraintVariable): void;
/** @override */
setConstraintVariable(constraintVariable: ConstraintVariable, state: number): void;
/** @internal @protected */
activateLayout(): void;
/** @internal @protected */
deactivateLayout(): void;
/** @protected @override */
onMount(): void;
/** @protected @override */
onUnmount(): void;
/** @internal */
get key(): string | undefined; // optional prototype field
}
/** @public */
export const ViewRef = (function (_super: typeof ViewRelation) {
const ViewRef: ViewRefFactory = _super.extend("ViewRef");
Object.defineProperty(ViewRef.prototype, "fastenerType", {
get: function (this: ViewRef): Proto<ViewRef<any, any>> {
return ViewRef;
},
configurable: true,
});
ViewRef.prototype.onInherit = function (this: ViewRef, superFastener: ViewRef): void {
this.setView(superFastener.view);
};
ViewRef.prototype.getView = function <V extends View>(this: ViewRef<unknown, V>): V {
const view = this.view;
if (view === null) {
let message = view + " ";
if (this.name.length !== 0) {
message += this.name + " ";
}
message += "view";
throw new TypeError(message);
}
return view;
};
ViewRef.prototype.setView = function <V extends View>(this: ViewRef<unknown, V>, newView: AnyView<V> | null, target?: View | null, key?: string): V | null {
if (newView !== null) {
newView = this.fromAny(newView);
}
let oldView = this.view;
if (oldView !== newView) {
if (target === void 0) {
target = null;
}
let parent: View | null;
if (this.binds && (parent = this.parentView, parent !== null)) {
if (oldView !== null && oldView.parent === parent) {
if (target === null) {
target = oldView.nextSibling;
}
oldView.remove();
}
if (newView !== null) {
if (key === void 0) {
key = this.key;
}
this.insertChild(parent, newView, target, key);
}
oldView = this.view;
}
if (oldView !== newView) {
if (oldView !== null) {
this.deactivateLayout();
this.willDetachView(oldView);
(this as Mutable<typeof this>).view = null;
this.onDetachView(oldView);
this.deinitView(oldView);
this.didDetachView(oldView);
}
if (newView !== null) {
this.willAttachView(newView, target);
(this as Mutable<typeof this>).view = newView;
this.onAttachView(newView, target);
this.initView(newView);
this.didAttachView(newView, target);
}
}
}
return oldView;
};
ViewRef.prototype.attachView = function <V extends View>(this: ViewRef<unknown, V>, newView?: AnyView<V>, target?: View | null): V {
const oldView = this.view;
if (newView !== void 0 && newView !== null) {
newView = this.fromAny(newView);
} else if (oldView === null) {
newView = this.createView();
} else {
newView = oldView;
}
if (newView !== oldView) {
if (target === void 0) {
target = null;
}
if (oldView !== null) {
this.deactivateLayout();
this.willDetachView(oldView);
(this as Mutable<typeof this>).view = null;
this.onDetachView(oldView);
this.deinitView(oldView);
this.didDetachView(oldView);
}
this.willAttachView(newView, target);
(this as Mutable<typeof this>).view = newView;
this.onAttachView(newView, target);
this.initView(newView);
this.didAttachView(newView, target);
}
return newView;
};
ViewRef.prototype.detachView = function <V extends View>(this: ViewRef<unknown, V>): V | null {
const oldView = this.view;
if (oldView !== null) {
this.deactivateLayout();
this.willDetachView(oldView);
(this as Mutable<typeof this>).view = null;
this.onDetachView(oldView);
this.deinitView(oldView);
this.didDetachView(oldView);
}
return oldView;
};
ViewRef.prototype.insertView = function <V extends View>(this: ViewRef<unknown, V>, parent?: View | null, newView?: AnyView<V>, target?: View | null, key?: string): V {
if (newView !== void 0 && newView !== null) {
newView = this.fromAny(newView);
} else {
const oldView = this.view;
if (oldView === null) {
newView = this.createView();
} else {
newView = oldView;
}
}
if (parent === void 0 || parent === null) {
parent = this.parentView;
}
if (target === void 0) {
target = null;
}
if (key === void 0) {
key = this.key;
}
if (parent !== null && (newView.parent !== parent || newView.key !== key)) {
this.insertChild(parent, newView, target, key);
}
const oldView = this.view;
if (newView !== oldView) {
if (oldView !== null) {
this.deactivateLayout();
this.willDetachView(oldView);
(this as Mutable<typeof this>).view = null;
this.onDetachView(oldView);
this.deinitView(oldView);
this.didDetachView(oldView);
oldView.remove();
}
this.willAttachView(newView, target);
(this as Mutable<typeof this>).view = newView;
this.onAttachView(newView, target);
this.initView(newView);
this.didAttachView(newView, target);
}
return newView;
};
ViewRef.prototype.removeView = function <V extends View>(this: ViewRef<unknown, V>): V | null {
const view = this.view;
if (view !== null) {
view.remove();
}
return view;
};
ViewRef.prototype.deleteView = function <V extends View>(this: ViewRef<unknown, V>): V | null {
const view = this.detachView();
if (view !== null) {
view.remove();
}
return view;
};
ViewRef.prototype.bindView = function <V extends View>(this: ViewRef<unknown, V>, view: View, target: View | null): void {
if (this.binds && this.view === null) {
const newView = this.detectView(view);
if (newView !== null) {
this.willAttachView(newView, target);
(this as Mutable<typeof this>).view = newView;
this.onAttachView(newView, target);
this.initView(newView);
this.didAttachView(newView, target);
}
}
};
ViewRef.prototype.unbindView = function <V extends View>(this: ViewRef<unknown, V>, view: View): void {
if (this.binds) {
const oldView = this.detectView(view);
if (oldView !== null && this.view === oldView) {
this.deactivateLayout();
this.willDetachView(oldView);
(this as Mutable<typeof this>).view = null;
this.onDetachView(oldView);
this.deinitView(oldView);
this.didDetachView(oldView);
}
}
};
ViewRef.prototype.detectView = function <V extends View>(this: ViewRef<unknown, V>, view: View): V | null {
const key = this.key;
if (key !== void 0 && key === view.key) {
return view as V;
}
return null;
};
ViewRef.prototype.constraint = function (this: ViewRef<ConstraintScope & ConstraintContext, View>, lhs: AnyConstraintExpression, relation: ConstraintRelation, rhs?: AnyConstraintExpression, strength?: AnyConstraintStrength): Constraint {
lhs = ConstraintExpression.fromAny(lhs);
if (rhs !== void 0) {
rhs = ConstraintExpression.fromAny(rhs);
}
const expression = rhs !== void 0 ? lhs.minus(rhs) : lhs;
if (strength === void 0) {
strength = ConstraintStrength.Required;
} else {
strength = ConstraintStrength.fromAny(strength);
}
const constraint = new Constraint(this.owner, expression, relation, strength);
this.addConstraint(constraint);
return constraint;
};
ViewRef.prototype.hasConstraint = function (this: ViewRef, constraint: Constraint): boolean {
return this.constraints.indexOf(constraint) >= 0;
};
ViewRef.prototype.addConstraint = function (this: ViewRef, constraint: Constraint): void {
const oldConstraints = this.constraints;
const newConstraints = Arrays.inserted(constraint, oldConstraints);
if (oldConstraints !== newConstraints) {
(this as Mutable<typeof this>).constraints = newConstraints;
this.activateConstraint(constraint);
}
};
ViewRef.prototype.removeConstraint = function (this: ViewRef, constraint: Constraint): void {
const oldConstraints = this.constraints;
const newConstraints = Arrays.removed(constraint, oldConstraints);
if (oldConstraints !== newConstraints) {
this.deactivateConstraint(constraint);
(this as Mutable<typeof this>).constraints = newConstraints;
}
};
ViewRef.prototype.activateConstraint = function (this: ViewRef<ConstraintContext, View>, constraint: Constraint): void {
this.owner.activateConstraint(constraint);
};
ViewRef.prototype.deactivateConstraint = function (this: ViewRef<ConstraintContext, View>, constraint: Constraint): void {
this.owner.deactivateConstraint(constraint);
};
ViewRef.prototype.constraintVariable = function (this: ViewRef, name: string, value?: number, strength?: AnyConstraintStrength): ConstraintProperty<unknown, number> {
if (value === void 0) {
value = 0;
}
if (strength !== void 0) {
strength = ConstraintStrength.fromAny(strength);
} else {
strength = ConstraintStrength.Strong;
}
const property = ConstraintProperty.create(this) as ConstraintProperty<unknown, number>;
Object.defineProperty(property, "name", {
value: name,
configurable: true,
});
if (value !== void 0) {
property.setValue(value);
}
property.setStrength(strength);
property.mount();
return property;
};
ViewRef.prototype.hasConstraintVariable = function (this: ViewRef, constraintVariable: ConstraintVariable): boolean {
return this.constraintVariables.indexOf(constraintVariable) >= 0;
};
ViewRef.prototype.addConstraintVariable = function (this: ViewRef, constraintVariable: ConstraintVariable): void {
const oldConstraintVariables = this.constraintVariables;
const newConstraintVariables = Arrays.inserted(constraintVariable, oldConstraintVariables);
if (oldConstraintVariables !== newConstraintVariables) {
(this as Mutable<typeof this>).constraintVariables = newConstraintVariables;
this.activateConstraintVariable(constraintVariable);
}
};
ViewRef.prototype.removeConstraintVariable = function (this: ViewRef, constraintVariable: ConstraintVariable): void {
const oldConstraintVariables = this.constraintVariables;
const newConstraintVariables = Arrays.removed(constraintVariable, oldConstraintVariables);
if (oldConstraintVariables !== newConstraintVariables) {
this.deactivateConstraintVariable(constraintVariable);
(this as Mutable<typeof this>).constraintVariables = newConstraintVariables;
}
};
ViewRef.prototype.activateConstraintVariable = function (this: ViewRef<ConstraintContext, View>, constraintVariable: ConstraintVariable): void {
this.owner.activateConstraintVariable(constraintVariable);
};
ViewRef.prototype.deactivateConstraintVariable = function (this: ViewRef<ConstraintContext, View>, constraintVariable: ConstraintVariable): void {
this.owner.deactivateConstraintVariable(constraintVariable);
};
ViewRef.prototype.setConstraintVariable = function (this: ViewRef<ConstraintContext, View>, constraintVariable: ConstraintVariable, state: number): void {
this.owner.setConstraintVariable(constraintVariable, state);
};
ViewRef.prototype.activateLayout = function (this: ViewRef<ConstraintContext, View>): void {
const constraintVariables = this.constraintVariables;
for (let i = 0, n = constraintVariables.length; i < n; i += 1) {
this.owner.activateConstraintVariable(constraintVariables[i]!);
}
const constraints = this.constraints;
for (let i = 0, n = constraints.length; i < n; i += 1) {
this.owner.activateConstraint(constraints[i]!);
}
};
ViewRef.prototype.deactivateLayout = function (this: ViewRef<ConstraintContext, View>): void {
const constraints = this.constraints;
for (let i = 0, n = constraints.length; i < n; i += 1) {
this.owner.deactivateConstraint(constraints[i]!);
}
const constraintVariables = this.constraintVariables;
for (let i = 0, n = constraintVariables.length; i < n; i += 1) {
this.owner.deactivateConstraintVariable(constraintVariables[i]!);
}
};
ViewRef.prototype.onMount = function (this: ViewRef): void {
_super.prototype.onMount.call(this);
this.activateLayout();
};
ViewRef.prototype.onUnmount = function (this: ViewRef): void {
this.deactivateLayout();
_super.prototype.onUnmount.call(this);
};
ViewRef.construct = function <F extends ViewRef<any, any>>(fastenerClass: {prototype: F}, fastener: F | null, owner: FastenerOwner<F>): F {
if (fastener === null) {
fastener = function (view?: AnyView<ViewRefType<F>> | null, target?: View | null, key?: string): ViewRefType<F> | null | FastenerOwner<F> {
if (view === void 0) {
return fastener!.view;
} else {
fastener!.setView(view, target, key);
return fastener!.owner;
}
} as F;
delete (fastener as Partial<Mutable<F>>).name; // don't clobber prototype name
Object.setPrototypeOf(fastener, fastenerClass.prototype);
}
fastener = _super.construct(fastenerClass, fastener, owner) as F;
(fastener as Mutable<typeof fastener>).view = null;
(fastener as Mutable<typeof fastener>).constraints = Arrays.empty;
(fastener as Mutable<typeof fastener>).constraintVariables = Arrays.empty;
return fastener;
};
ViewRef.define = function <O, V extends View>(className: string, descriptor: ViewRefDescriptor<O, V>): ViewRefFactory<ViewRef<any, V>> {
let superClass = descriptor.extends as ViewRefFactory | null | undefined;
const affinity = descriptor.affinity;
const inherits = descriptor.inherits;
delete descriptor.extends;
delete descriptor.implements;
delete descriptor.affinity;
delete descriptor.inherits;
if (descriptor.key === true) {
Object.defineProperty(descriptor, "key", {
value: className,
configurable: true,
});
} else if (descriptor.key === false) {
Object.defineProperty(descriptor, "key", {
value: void 0,
configurable: true,
});
}
if (superClass === void 0 || superClass === null) {
superClass = this;
}
const fastenerClass = superClass.extend(className, descriptor);
fastenerClass.construct = function (fastenerClass: {prototype: ViewRef<any, any>}, fastener: ViewRef<O, V> | null, owner: O): ViewRef<O, V> {
fastener = superClass!.construct(fastenerClass, fastener, owner);
if (affinity !== void 0) {
fastener.initAffinity(affinity);
}
if (inherits !== void 0) {
fastener.initInherits(inherits);
}
return fastener;
};
return fastenerClass;
};
return ViewRef;
})(ViewRelation); | the_stack |
import React, { useRef, useEffect } from 'react'
import * as d3 from 'd3'
import {
ZoomInOutlined,
ZoomOutOutlined,
ReloadOutlined,
} from '@ant-design/icons'
import { Space } from 'antd'
import { cyan, magenta, grey } from '@ant-design/colors'
import { useTranslation } from 'react-i18next'
import { TopologyStoreLocation } from '@lib/client'
import styles from './index.module.less'
import { InstanceKindName } from '@lib/utils/instanceTable'
//////////////////////////////////////
type ShortStrMap = Record<string, string>
export function getShortStrMap(
data: TopologyStoreLocation | undefined
): ShortStrMap {
let allShortStrMap: ShortStrMap = {}
if (data === undefined) {
return allShortStrMap
}
// location labels
// failure-domain.beta.kubernetes.io/region => region
data.location_labels?.forEach((label) => {
if (label.indexOf('/') >= 0) {
const shortStr = label.split('/').pop()
if (shortStr) {
allShortStrMap[label] = shortStr
}
}
})
// location labels value
data.location_labels?.forEach((label) => {
// get label values
const labelValues: string[] = []
data.stores?.forEach((store) => {
const val = store.labels?.[label]
if (val) {
labelValues.push(val)
}
})
const shortStrMap = trimDuplicate(labelValues)
allShortStrMap = Object.assign(allShortStrMap, shortStrMap)
})
// tikv & tiflash nodes address
const addresses = (data.stores || []).map((s) => s.address!)
addresses.forEach((addr) => {
if (addr.startsWith('db-')) {
const shortStr = addr.split('.').shift()
if (shortStr) {
allShortStrMap[addr] = shortStr
}
}
})
return allShortStrMap
}
// input: ['aaa-111a.abc.123', 'aaa-222a.abc.123', 'aaa-333a.abc.123'], items in the array have either the same prefix or suffix, or both.
// output:
// {
// "aaa-111a.abc.123":"111a",
// "aaa-222a.abc.123":"222a",
// "aaa-333a.abc.123":"333a"
// }
export function trimDuplicate(strArr: string[]): ShortStrMap {
const shortStrMap: ShortStrMap = {}
const strSet = new Set(strArr)
if (strSet.size < 2) {
return shortStrMap
}
let i = 0
let c
const charSet = new Set()
// calc the prefix length
let headDotOrMinusPos = -1
while (true) {
charSet.clear()
for (let str of strSet) {
c = str[i]
if (c === undefined) {
break
}
charSet.add(c)
}
if (c === undefined) {
break
}
if (charSet.size > 1) {
break
}
if (c === '.' || c === '-') {
headDotOrMinusPos = i
}
i++
}
// calc the suffix length
i = 0
let tailDotOrMinusPos = -1
while (true) {
charSet.clear()
for (let str of strSet) {
c = str[str.length - 1 - i]
if (c === undefined) {
break
}
charSet.add(c)
}
if (c === undefined) {
break
}
if (charSet.size > 1) {
break
}
if (c === '.' || c === '-') {
tailDotOrMinusPos = i
}
i++
}
if (headDotOrMinusPos === -1 && tailDotOrMinusPos === -1) {
return shortStrMap
}
strSet.forEach((s) => {
const startIdx = headDotOrMinusPos + 1
const endIdx =
tailDotOrMinusPos === -1 ? s.length : s.length - 1 - tailDotOrMinusPos
const short = s.slice(startIdx, endIdx)
shortStrMap[s] = short
})
return shortStrMap
}
//////////////////////////////////////
const NODE_STORES = 'Stores'
const NODE_TIFLASH = InstanceKindName.tiflash
const NODE_TIKV = InstanceKindName.tikv
type TreeNode = {
name: string
value: string
children: TreeNode[]
}
export function buildTreeData(
data: TopologyStoreLocation | undefined
): TreeNode {
const treeData: TreeNode = { name: NODE_STORES, value: '', children: [] }
if ((data?.location_labels?.length || 0) > 0) {
const locationLabels: string[] = data?.location_labels || []
for (const store of data?.stores || []) {
// reset curNode, point to tree nodes beginning
let curNode = treeData
for (const curLabel of locationLabels) {
const curLabelVal = store.labels![curLabel]
if (curLabelVal === undefined) {
continue
}
let subNode: TreeNode | undefined = curNode.children.find(
(el) => el.name === curLabel && el.value === curLabelVal
)
if (subNode === undefined) {
subNode = { name: curLabel, value: curLabelVal, children: [] }
curNode.children.push(subNode)
}
// make curNode point to subNode
curNode = subNode
}
const storeType =
store.labels!['engine'] === 'tiflash' ? NODE_TIFLASH : NODE_TIKV
curNode.children.push({
name: storeType,
value: store.address!,
children: [],
})
}
}
return treeData
}
//////////////////////////////////////
interface ITooltipConfig {
enable: boolean
offsetX: number
offsetY: number
}
export interface IStoreLocationProps {
dataSource: any
shortStrMap?: ShortStrMap
getMinHeight?: () => number
onReload?: () => void
}
const MAX_STR_LENGTH = 16
const margin = { left: 60, right: 40, top: 80, bottom: 100 }
const dx = 40
const diagonal = d3
.linkHorizontal()
.x((d: any) => d.y)
.y((d: any) => d.x)
function calcHeight(root) {
let x0 = Infinity
let x1 = -x0
root.each((d) => {
if (d.x > x1) x1 = d.x
if (d.x < x0) x0 = d.x
})
return x1 - x0
}
export default function StoreLocationTree({
dataSource,
shortStrMap = {},
getMinHeight,
onReload,
}: IStoreLocationProps) {
const divRef = useRef<HTMLDivElement>(null)
const { t } = useTranslation()
const tooltipConfig = useRef<ITooltipConfig>()
tooltipConfig.current = {
enable: true,
offsetX: 0,
offsetY: 0,
}
useEffect(() => {
let divWidth = divRef.current?.clientWidth || 0
const root = d3.hierarchy(dataSource) as any
root.descendants().forEach((d, i) => {
d.id = i
d._children = d.children
// collapse all nodes default
// if (d.depth) d.children = null
})
const dy = divWidth / (root.height + 2)
let tree = d3.tree().nodeSize([dx, dy])
const div = d3.select(divRef.current)
div.select('svg#slt').remove()
const svg = div
.append('svg')
.attr('id', 'slt')
.attr('width', divWidth)
.attr('height', dx + margin.top + margin.bottom)
.style('font', '14px sans-serif')
.style('user-select', 'none')
const bound = svg
.append('g')
.attr('transform', `translate(${margin.left}, ${margin.top})`)
const gLink = bound
.append('g')
.attr('fill', 'none')
.attr('stroke', '#ddd')
.attr('stroke-width', 2)
const gNode = bound
.append('g')
.attr('cursor', 'pointer')
.attr('pointer-events', 'all')
// tooltip
const tooltip = d3.select('#store-location-tooltip')
// zoom
const zoom = d3
.zoom()
.scaleExtent([0.1, 5])
.filter(function () {
// ref: https://godbasin.github.io/2018/02/07/d3-tree-notes-4-zoom-amd-drag/
// only zoom when pressing CTRL
const isWheelEvent = d3.event instanceof WheelEvent
return !isWheelEvent || (isWheelEvent && d3.event.ctrlKey)
})
.on('start', () => {
// hide tooltip if it shows
tooltip.style('opacity', 0)
tooltipConfig.current!.enable = false
})
.on('zoom', () => {
const t = d3.event.transform
bound.attr(
'transform',
`translate(${t.x + margin.left}, ${t.y + margin.top}) scale(${t.k})`
)
// this will cause unexpected result when dragging
// svg.attr('transform', d3.event.transform)
})
.on('end', () => {
const t = d3.event.transform
tooltipConfig.current = {
enable: t.k === 1, // disable tooltip if zoom
offsetX: t.x,
offsetY: t.y,
}
})
svg.call(zoom as any)
// zoom actions
d3.select('#slt-zoom-in').on('click', function () {
zoom.scaleBy(svg.transition().duration(500) as any, 1.2)
})
d3.select('#slt-zoom-out').on('click', function () {
zoom.scaleBy(svg.transition().duration(500) as any, 0.8)
})
d3.select('#slt-zoom-reset').on('click', function () {
// https://stackoverflow.com/a/51981636/2998877
svg
.transition()
.duration(500)
.call(zoom.transform as any, d3.zoomIdentity)
onReload?.()
})
update(root)
function update(source) {
// use altKey to slow down the animation, interesting!
const duration = d3.event && d3.event.altKey ? 2500 : 500
const nodes = root.descendants().reverse()
const links = root.links()
// compute the new tree layout
// it modifies root self
tree(root)
const boundHeight = calcHeight(root)
// node.x represent the y axes position actually
// [root.y, root.x] is [0, 0], we need to move it to [0, boundHeight/2]
root.descendants().forEach((d, i) => {
d.x += boundHeight / 2
})
if (root.x0 === undefined) {
// initial root.x0, root.y0, only need to set it once
root.x0 = root.x
root.y0 = root.y
}
const contentHeight = boundHeight + margin.top + margin.bottom
const transition = svg
.transition()
.duration(duration)
.attr('width', divWidth)
.attr('height', Math.max(getMinHeight?.() || 0, contentHeight))
// update the nodes
const node = gNode.selectAll('g').data(nodes, (d: any) => d.id)
// enter any new nodes at the parent's previous position
const nodeEnter = node
.enter()
.append('g')
.attr('transform', (_d) => `translate(${source.y0},${source.x0})`)
.attr('fill-opacity', 0)
.attr('stroke-opacity', 0)
.on('click', (d: any) => {
d.children = d.children ? null : d._children
update(d)
})
.on('mouseenter', onMouseEnter)
.on('mouseleave', onMouseLeave)
function onMouseEnter(datum) {
if (!tooltipConfig.current?.enable) {
return
}
const { name, value } = datum.data
if (
shortStrMap[name] === undefined &&
shortStrMap[value] === undefined
) {
return
}
tooltip.select('#store-location-tooltip-name').text(name)
tooltip.select('#store-location-tooltip-value').text(value)
const x = datum.y + margin.left + tooltipConfig.current.offsetX
const y = datum.x + margin.top - 20 + tooltipConfig.current.offsetY
tooltip.style(
'transform',
`translate(calc(-50% + ${x}px), calc(-100% + ${y}px))`
)
tooltip.style('opacity', 1)
}
function onMouseLeave() {
tooltip.style('opacity', 0)
}
// circle
nodeEnter
.append('circle')
.attr('r', 8)
.attr('fill', '#fff')
.attr('stroke', (d: any) => {
if (d._children) {
return grey[1]
}
if (d.data.name === NODE_TIFLASH) {
return magenta[4]
}
return cyan[5]
})
.attr('stroke-width', 3)
// text for root node
nodeEnter
.filter(({ data: { name } }: any) => name === NODE_STORES)
.append('text')
.attr('dy', '0.31em')
.attr('x', -15)
.attr('text-anchor', 'end')
.text(({ data: { name } }: any) => name)
// text for non-root and non-leaf nodes
const middleNodeText = nodeEnter
.filter(
({ data: { name } }: any) =>
name !== NODE_STORES && name !== NODE_TIFLASH && name !== NODE_TIKV
)
.append('text')
middleNodeText
.append('tspan')
.text(({ data: { name } }: any) => shortStrMap[name] ?? name)
.attr('x', -15)
.attr('dy', '-0.2em')
.attr('text-anchor', 'end')
middleNodeText
.append('tspan')
.text(({ data: { value } }: any) => {
if (value.length <= MAX_STR_LENGTH) {
return value
}
let shortStr = shortStrMap[value] ?? value
if (shortStr.length > MAX_STR_LENGTH) {
const midIdx = Math.round(MAX_STR_LENGTH / 2) - 1
shortStr =
shortStr.slice(0, midIdx) +
'..' +
shortStr.slice(shortStr.length - midIdx, shortStr.length)
}
return shortStr
})
.attr('x', -15)
.attr('dy', '1em')
.attr('text-anchor', 'end')
// text for leaf nodes
const leafNodeText = nodeEnter
.filter(
({ data: { name } }: any) =>
name === NODE_TIFLASH || name === NODE_TIKV
)
.append('text')
leafNodeText
.append('tspan')
.text(({ data: { name } }: any) => name)
.attr('x', 15)
.attr('dy', '-0.2em')
leafNodeText
.append('tspan')
.text(({ data: { value } }: any) => shortStrMap[value] ?? value)
.attr('x', 15)
.attr('dy', '1em')
// transition nodes to their new position
node
.merge(nodeEnter as any)
.transition(transition as any)
.attr('transform', (d: any) => `translate(${d.y},${d.x})`)
.attr('fill-opacity', 1)
.attr('stroke-opacity', 1)
// transition exiting nodes to the parent's new position
node
.exit()
.transition(transition as any)
.remove()
.attr('transform', (d) => `translate(${source.y},${source.x})`)
.attr('fill-opacity', 0)
.attr('stroke-opacity', 0)
// update the links
const link = gLink.selectAll('path').data(links, (d: any) => d.target.id)
// enter any new links at the parent's previous position
const linkEnter = link
.enter()
.append('path')
.attr('d', (_d) => {
const o = { x: source.x0, y: source.y0 }
return diagonal({ source: o, target: o } as any)
})
// transition links to their new position
link
.merge(linkEnter as any)
.transition(transition as any)
.attr('d', diagonal as any)
// transition exiting nodes to the parent's new position
link
.exit()
.transition(transition as any)
.remove()
.attr('d', (_d) => {
const o = { x: source.x, y: source.y }
return diagonal({ source: o, target: o } as any)
})
// stash the old positions for transition
root.eachBefore((d) => {
d.x0 = d.x
d.y0 = d.y
})
}
function resizeHandler() {
divWidth = divRef.current?.clientWidth || 0
const dy = divWidth / (root.height + 2)
tree = d3.tree().nodeSize([dx, dy])
update(root)
}
window.addEventListener('resize', resizeHandler)
return () => {
window.removeEventListener('resize', resizeHandler)
}
}, [dataSource, getMinHeight, onReload, shortStrMap])
return (
<div ref={divRef} style={{ position: 'relative' }}>
<Space
style={{
cursor: 'pointer',
fontSize: 18,
position: 'absolute',
}}
>
<ReloadOutlined id="slt-zoom-reset" />
<ZoomInOutlined id="slt-zoom-in" />
<ZoomOutOutlined id="slt-zoom-out" />
<span
style={{
fontStyle: 'italic',
fontSize: 12,
display: 'block',
margin: '0 auto',
}}
>
*{t('cluster_info.list.store_topology.tooltip')}
</span>
</Space>
<div id="store-location-tooltip" className={styles.tooltip}>
<div id="store-location-tooltip-name"></div>
<div id="store-location-tooltip-value"></div>
</div>
</div>
)
}
// refs:
// https://observablehq.com/@d3/tidy-tree
// https://observablehq.com/@d3/collapsible-tree | the_stack |
module TDev
{
export class SizeDesc
{
public elt:HTMLElement;
public top:number;
constructor(public stmt:AST.Stmt) {
this.elt = this.stmt.renderedAs;
this.top = Util.offsetIn(this.elt, TheEditor.codeInner).y;
}
}
export class Selector
extends SideTab
{
public codeButtons:HTMLElement[] = [];
private topButtonRow:HTMLElement;
private topLeftButtonRow:HTMLElement;
private extractedName:HTMLInputElement;
private bottomButtonRow:HTMLElement;
private bottomLeftButtonRow:HTMLElement;
private buttonsAround:HTMLElement;
private selectionBlock:AST.Block;
private selectionBegin = 0;
private selectionEnd = 0;
private tops:SizeDesc[] = [];
private scrollCont:HTMLElement;
private directAdd = false;
private useCodeButtons = false;
private displayDoubleTapHint = false;
public codeView:HTMLElement;
public selectedStmt:AST.Stmt;
private selectionActive = false;
private multiStmtSelectionActive = false;
private dragMode = false;
private sideKeyFocus = false;
private topDrag:DragMarker;
private bottomDrag: DragMarker;
private breakpointBtn: HTMLElement;
constructor() {
super()
}
public somethingSelected() { return this.selectionActive; }
public nonActionSelected() { return this.selectionActive && !(this.selectedStmt instanceof AST.ActionHeader); }
public phoneNarrow() { return true }
static insertionButtons(): { name: string; desc: string; tick: Ticks; node: string; widget: string; }[]{
var inTutorial = !!TheEditor.stepTutorial;
var widgets = Browser.EditorSettings.widgets();
var ifDefault = inTutorial ? "" : widgets.ifConditionDefault;
var forDefault = inTutorial ? "" : widgets.forConditionDefault;
var whileBodyDefault = inTutorial ? "" : widgets.whileBodyDefault;
var whileDefault = inTutorial ? "" : widgets.whileConditionDefault;
return [{
name: "if", desc: lf("conditional"), tick: Ticks.codeIf,
node: "if " + (ifDefault || "") + " then { }",
widget:''
},
{
name: "for", desc: lf("repeat n times"), tick: Ticks.codeFor,
node: "for 0 <= i < " + (forDefault || "") + " do { }",
widget: ''
},
{
name: "while", desc: lf("repeat while"), tick: Ticks.codeWhile,
node: "while " + (whileDefault || "") + " do { " + (whileBodyDefault || "") + " }",
widget: ''
},
{
name: "for each", desc: lf("repeat on collection"), tick: Ticks.codeForEach,
node: "foreach e in do { }",
widget: "foreach",
},
{
name: "boxed", desc: lf("UI widget"), tick: Ticks.codeBoxed,
node: "do box { }",
widget: "boxed"
},
].filter(btn => !btn.widget || TheEditor.widgetEnabled(btn.widget));
}
public init(e:Editor)
{
super.init(e);
this.codeView = e.codeInner;
}
private isSelected(n:AST.Stmt)
{
for (var i = this.selectionBegin; i <= this.selectionEnd; ++i)
if (this.selectionBlock.stmts[i] == n) return true;
return false;
}
public edit(n:AST.AstNode) {
return TheEditor.editNode(n, false); // TODO XXX - why did we set refreshIds=true here previously?
}
private addAt(j:number, bl:AST.Block)
{
var ch = bl.stmts.slice(0);
if (j < ch.length && ch[j].isPlaceholder()) {
this.edit(ch[j]);
return; // no need to insert a new one
} else if (j > 0 && ch[j-1].isPlaceholder()) {
this.edit(ch[j-1]);
return; // likewise
}
var n = bl.emptyStmt();
if (AST.isElseIf(bl.stmts[j])) {
n = AST.Parser.parseStmt(Selector.insertionButtons()[0].node);
(<AST.If>n).isElseIf = true;
}
TheEditor.initIds(n, true)
ch.splice(j, 0, n);
bl.setChildren(ch);
// TheEditor.refreshDecl();
this.edit(n);
// For new record fields, just like for [var] declarations, we edit
// the field name right away.
if (n instanceof AST.RecordField || n instanceof AST.ActionParameter)
TheEditor.calculator.inlineEdit(TheEditor.calculator.expr.tokens[0]);
}
public addCallback(off:number, stmt = null, t = Ticks.noEvent)
{ return () => {
tick(t);
TheEditor.getSpyManager().onAddNear(stmt);
if (!stmt) {
if (off <= 0) stmt = this.selectionBlock.stmts[this.selectionBegin];
else stmt = this.selectionBlock.stmts[this.selectionEnd];
if (stmt instanceof AST.FieldComment)
stmt = stmt.parent.parent
}
var idx = stmt.parentBlock().stmts.indexOf(stmt);
if (off < 0) off = 0;
if (off == 2) {
off = 1;
var prim = stmt.primaryBody();
if (prim != null) {
this.addAt(0, prim);
return;
}
}
this.addAt(idx + off, stmt.parent);
};
}
public deleteButton()
{
return div(null, HTML.mkButtonTick(lf("delete"), Ticks.btnCut, () => {
this.deleteSelection();
TheEditor.dismissSidePane();
}))
}
public deleteSelection()
{
if (!!this.selectionBlock.immutableReason) {
HTML.showErrorNotification(this.selectionBlock.immutableReason);
return;
}
TheEditor.getSpyManager().onDelete(this.selectionBlock);
this.copyOutSelection().forEach(s => {
s.onDelete();
});
var ch = this.selectionBlock.stmts.slice(0);
ch.splice(this.selectionBegin, this.selectionEnd - this.selectionBegin + 1);
var needInit = false
if (ch.length == 0 && !this.selectionBlock.allowEmpty()) {
ch.push(this.selectionBlock.emptyStmt());
needInit = true
}
this.selectedStmt = this.selectionBlock.stmts[Math.max(this.selectionBegin - 1, 0)];
this.selectionBlock.setChildren(ch);
if (needInit)
TheEditor.initIds(this.selectionBlock)
this.selectionBlock.notifyChange()
}
private cutSelection()
{
this.copySelection(true);
this.deleteSelection();
this.unselect();
}
private copySelection(isCut : boolean = false)
{
if (!this.canCopyPaste()) return;
var ch = this.copyOutSelection();
if (ch.length == 0) return;
ch = ch.map((s:AST.Stmt) => {
// strip 'where' and 'with x :='
if (s instanceof AST.Where || s instanceof AST.OptionalParameter)
return AST.mkExprStmt(s.calcNode())
if (s instanceof AST.InlineAction)
return null
return s
}).filter(s => !!s)
/*if (ch.length == 1 && ch[0] instanceof AST.ExprStmt) {
TheEditor.clipMgr.copy({ type: "tokens", data: (<AST.ExprStmt>ch[0]).expr.serialize() });
} else*/ {
var block = new AST.CodeBlock();
block.stmts = ch; // don't use setChildren(), that would override the parent
TheEditor.clipMgr.copy({ type: "block", data: block.serialize(), scriptId: (Script ? Script.localGuid : Util.guidGen()), isCut: isCut });
}
}
private toggleBreakpointHandler() {
return () => TheEditor.toggleBreakpoint(this.selectedStmt);
}
private setupButtons(isfresh: boolean) : HTMLElement {
var extractedName = isfresh ? "do stuff" : this.extractedName.value;
var mkBtn = (lbl:string, key:string, tck:Ticks, f:()=>void) => {
var b = HTML.mkButtonTick(lbl, tck, f)
KeyboardMgr.instance.btnShortcut(b, key)
return b
}
var btn:HTMLElement;
var btns = <HTMLElement[]>[
div("selHeader", lf("clipboard")),
mkBtn(lf("cut selection"), "Ctrl-X, Shift-Del", Ticks.codeCutSelection, () => { this.cutSelection() }),
btn = mkBtn(lf("copy selection"), "Ctrl-C, Ctrl-Ins", Ticks.codeCopySelection, () => { this.copySelection(); this.unselect() }),
mkBtn(lf("delete selection"), "Del", Ticks.codeDeleteSelection, () => { this.deleteSelection(); this.unselect() })
];
if (this.selectionBlock instanceof AST.CodeBlock) {
btns.push(
div("selHeader", lf("extract selection into function")),
this.extractedName = HTML.mkTextInput("text", lf("function name")),
mkBtn(lf("extract"), "Ctrl-E", Ticks.codeExtractAction, () => { this.extract() }));
btns.push(div("selHeader", lf("surround with")));
this.extractedName.value = Script.freshName(extractedName);
Selector.insertionButtons().forEach(ib =>
btns.push(HTML.mkButton(ib.name, () => {
TDev.Browser.EditorSoundManager.intellibuttonClick();
this.surround(ib.node)();
})))
btns.push(HTML.mkButton(lf("comment out"), () => {
TDev.Browser.EditorSoundManager.intellibuttonClick();
this.surround("if false then { }")();
}))
}
this.setChildren(btns);
return btn;
}
public startSelection() : void
{
if (!this.selectedStmt || !this.selectionBlock || !this.canCopyPaste()) return;
this.multiStmtSelectionActive = true;
var prevStmt = this.selectedStmt;
TheEditor.resetSidePane();
this.selectedStmt = prevStmt;
TheEditor.showSideTab(this, true);
this.scrollCont = TheEditor.codeInner;
this.hideCodeButtons();
EditorRenderer.setActive(this.selectedStmt, true);
this.selectionActive = true;
var btn = this.setupButtons(true);
this.setupDrags();
// needed on android to prevent keyboard popping up
Util.setTimeout(50, () => btn.focus());
}
private extract()
{
var stmts = this.copyOutSelection();
var callPlaceholder = this.replaceSelectionWithPlaceholder();
var extracted = AST.Parser.emptyBlock();
extracted.setChildren(stmts);
var extr = new AST.Extractor(extracted,
TDev.TheEditor.currentAction(),
callPlaceholder,
Script.freshName(this.extractedName.value));
extr.run();
if (extr.failed.length > 0) {
var ss = this.selectionBlock.stmts
var ch = ss.slice(0, this.selectionBegin).concat(extracted.stmts).concat(ss.slice(this.selectionBegin + 1, ss.length))
this.selectionBlock.setChildren(ch);
this.unselect()
extr.failed.forEach(s => {
var elt = s && s.renderedAs
if (elt)
Util.coreAnim("shakeTip", 500, elt)
})
return
}
TheEditor.initIds(extr.extractedAction)
Script.addDecl(extr.extractedAction);
TheEditor.queueNavRefresh();
TheEditor.typeCheckNow();
TheEditor.dismissSidePane();
var elt = callPlaceholder.renderedAs;
if (elt) Util.coreAnim("blinkLocation", 1000, elt);
}
public copyOutSelection()
{
return this.selectionBlock ? this.selectionBlock.stmts.slice(this.selectionBegin, this.selectionEnd + 1) : [];
}
private replaceSelectionWithPlaceholder()
{
var ch = this.selectionBlock.stmts.slice(0);
var placeHolder = AST.Parser.emptyExprStmt();
TheEditor.initIds(placeHolder, true)
ch.splice(this.selectionBegin, this.selectionEnd - this.selectionBegin + 1, placeHolder);
this.selectionBlock.setChildren(ch);
return placeHolder;
}
private surround(node:string)
{ return () => {
tick(Ticks.codeSurround)
var ch0 = this.copyOutSelection();
var placeHolder = this.replaceSelectionWithPlaceholder();
var n = AST.Parser.parseStmt(node);
this.changeStmtTypeCore(n, placeHolder);
n.primaryBody().setChildren(ch0);
this.edit(n);
}
}
public changeStmtType(node:string)
{
var n = AST.Parser.parseStmt(node);
this.changeStmtTypeCore(n, this.selectedStmt);
//this.initIdVisitor.dispatch(n); // TODO XXX - is this the right place?
this.edit(n);
}
public changeStmtTypeCore(n:AST.Stmt, at:AST.Stmt)
{
var a = TDev.TheEditor.currentAction();
if (!!a) {
for (var pr in n) {
if ((<any> n)[pr] instanceof AST.LocalDef) {
var l = <AST.LocalDef> (<any> n)[pr];
var nn = TheEditor.calculator.forceLoopLocalName;
if (!nn) nn = a.nameLocal(l.getName());
TheEditor.calculator.forceLoopLocalName = null;
l.rename(nn);
}
}
}
var ch = at.parentBlock().stmts.slice(0);
var idx = ch.indexOf(at);
var len = 1;
if (at.isPlaceholder()) {
} else if (n.calcNode() && at.nodeType() == "exprStmt") {
n.calcNode().tokens = at.calcNode().tokens
} else {
idx++; len = 0;
}
ch.splice(idx, len, n);
at.parentBlock().setChildren(ch);
}
public setup(stmt:AST.Stmt)
{
this.setSelected(stmt);
this.selectionActive = true;
this.multiStmtSelectionActive = false;
}
public setSelected(stmt:AST.Stmt)
{
this.hideCurrent();
this.selectedStmt = stmt;
if (!stmt) return;
this.selectionBlock = <AST.Block>stmt.parent;
if (!this.selectionBlock || this.selectionBlock instanceof AST.App) {
this.selectionBegin = 0;
this.selectionEnd = -1;
} else {
this.selectionBegin = this.selectionBlock.stmts.indexOf(stmt);
this.selectionEnd = this.selectionBegin;
}
this.setLineFlag(this.selectedStmt, "carret", true);
}
public addBeforeSelected(n:AST.Stmt)
{
var ch = this.selectionBlock.stmts.slice(0);
var idx = ch.indexOf(this.selectedStmt);
if (idx < 0) return;
ch.splice(idx, 0, n);
this.selectionBlock.setChildren(ch);
}
public hideCurrent()
{
if (!!this.selectedStmt)
this.setLineFlag(this.selectedStmt, "carret", false);
}
public showCurrent()
{
this.setSelected(TheEditor.firstIfMissing(this.selectedStmt));
}
private unselect()
{
TheEditor.dismissSidePane();
}
public recomputeSelection()
{
var beginParents = [];
for (var beg = this.topDrag.currentNode; beg != null; beg = beg.parent)
beginParents.push(beg);
var endNode = this.bottomDrag.currentNode;
while (!!endNode && beginParents.indexOf(endNode.parent) < 0)
endNode = endNode.parent;
if (!endNode) this.emptySelection();
else {
if (!(endNode.parent instanceof AST.Block))
endNode = endNode.parent;
if (!endNode.parent) this.emptySelection();
else {
var idx = beginParents.indexOf(endNode.parent);
this.selectionBlock = <AST.Block> endNode.parent;
this.selectionBegin = this.selectionBlock.stmts.indexOf(beginParents[idx - 1]);
this.selectionEnd = this.selectionBlock.stmts.indexOf(endNode);
}
if (this.selectionEnd < this.selectionBegin)
this.emptySelection();
else
this.applySelection();
}
}
private emptySelection()
{
this.selectionBegin = -1;
this.selectionEnd = -1;
this.applySelection();
}
private applySelection()
{
var elseIfs = [];
this.tops.forEach((s:SizeDesc) => {
if (elseIfs.indexOf(s.stmt) >= 0) return;
var v = this.isSelected(s.stmt);
s.elt.setFlag("selected", v);
if (v)
s.elt.setFlag("current", false)
var st = s.stmt;
/*
if (this.isSelected(st)) {
while (st instanceof AST.If) {
st = (<AST.If> st).elseIfNode;
elseIfs.push(st);
if (!st) break;
st.renderedAs.setFlag("selected", v);
}
}
*/
});
}
private setupDrags()
{
// TheEditor.refreshDecl();
this.setSizes();
this.applySelection();
this.codeButtons = [];
this.topDrag = new DragMarker(true, this);
this.bottomDrag = new DragMarker(false, this);
this.repositionMarkers();
this.dragMode = true;
}
public repositionMarkers()
{
if (this.selectionBegin < 0) {
this.unselect();
return;
}
var p = Util.offsetIn(this.selectionBlock.stmts[this.selectionBegin].renderedAs, this.codeView);
var x0 = p.y;
var endElt = this.selectionBlock.stmts[this.selectionEnd].renderedAs;
if (!endElt) {
this.unselect();
return;
}
if ((<HTMLElement> endElt.parentNode).className == "elseIfHolder")
endElt = <HTMLElement>endElt.parentNode;
p = Util.offsetIn(endElt, this.codeView);
var x1 = p.y + endElt.offsetHeight;
this.topDrag.position(x0);
this.bottomDrag.position(x1);
/*
var overlap = (x0 + btnH) - x1 + 5;
if (overlap > 0) {
x0 -= overlap / 2;
x1 += overlap / 2;
}
*/
// for up button: find first stmt below it, for down first above
// then extend selection based on these two
// update selected className, do not redraw everything
/*
var missingSize = hh - bottomPos - 10;
var spacer = div(null);
spacer.style.height = missingSize + "px";
codeView.appendChild(spacer);
codeButtons.push(spacer);
*/
}
public findNodeAt(pos:number)
{
for (var i = 0; i < this.tops.length; ++i)
if (this.tops[i].top > pos) break;
if (i > 0) i--;
return this.tops[i].stmt;
}
private setSizes()
{
var desc = (s:AST.AstNode) =>
{
if (s instanceof AST.Stmt) {
if (!(s instanceof AST.Block) && (<AST.Stmt>s).renderedAs)
this.tops.push(new SizeDesc(<AST.Stmt>s));
s.children().forEach(desc);
}
}
this.tops = [];
TheEditor.lastDecl.children().forEach(desc);
}
private selectionUp()
{
var p = this.selectionBlock.parent;
if (!p) return;
var gp = p.parentBlock();
if (!gp) return;
this.selectionBegin = gp.stmts.indexOf(p);
this.selectionEnd = this.selectionBegin;
this.selectionBlock = gp;
}
private updateSelection()
{
this.applySelection();
this.repositionMarkers();
}
public pasteCode()
{
tick(Ticks.codePaste)
var node = TheEditor.clipMgr.paste();
if (!!node) {
//Util.log(">>> pasting from "+node.scriptId+((node.scriptId == Script.localGuid) ? " (me)" : "")+(node.isCut ? " (cut)" : " (copied)"));
var calc = TheEditor.calculator;
if (node.type == "tokens" && calc.isActive()) {
calc.pasteTokens()
return;
}
if (node.type == "decls") {
TheEditor.pasteNode();
} else if (node.type == "block" || node.type == "tokens") {
if (!this.canCopyPaste()) return;
var stmt = AST.Parser.parseStmt(node.data);
// refresh the IDs in stmt if pasted data
// (1) came from another script, or
// (2) was *copied* instead of cut
if(node.scriptId != Script.localGuid || !node.isCut) {
TheEditor.initIds(stmt, true);
}
if (!stmt) return;
var stmts = [stmt];
if (stmt instanceof AST.Block)
stmts = (<AST.Block>stmt).stmts;
if (stmts.length == 0)
stmts.push(this.selectionBlock.emptyStmt());
else if (this.selectionBlock instanceof AST.ConditionBlock)
stmts = stmts.filter((s) => s instanceof AST.ExprStmt).map((s:any) => AST.mkWhere(s.expr));
else if (this.selectionBlock instanceof AST.FieldBlock)
stmts = stmts.filter(s => s instanceof AST.RecordField)
else // If not a [FieldBlock], then [RecordField]'s are not allowed
stmts = stmts.filter(s => !(s instanceof AST.RecordField))
var ch = this.selectionBlock.stmts.slice(0);
var selLen = this.selectionEnd - this.selectionBegin + 1
if (this.multiStmtSelectionActive || (selLen == 1 && ch[this.selectionBegin].isPlaceholder()))
ch.spliceArr(this.selectionBegin, selLen, stmts);
else
ch.spliceArr(this.selectionEnd + 1, 0, stmts);
this.selectionBlock.setChildren(ch);
// Specific adjustments for records: avoid duplicate names,
// and make sure the [isKey] parameter is set consistently.
if (this.selectionBlock instanceof AST.FieldBlock) {
var fb = <AST.FieldBlock> this.selectionBlock;
stmts.forEach(s => {
var rf = <AST.RecordField> s;
rf.isKey = fb.isKeyBlock();
rf.setName(fb.mkUniqName(rf.getName()));
});
}
}
}
this.unselect();
}
public injectBelow(node:AST.Stmt)
{
var nodes:AST.Stmt[] = [node];
if (node instanceof AST.Block)
nodes = (<AST.Block>node).stmts;
var ch = this.selectionBlock.stmts.slice(0);
var curr = this.copyOutSelection();
if (!this.multiStmtSelectionActive && curr.length == 1) {
var innerBlocks = curr[0].children().filter((n) => n instanceof AST.Block);
if (innerBlocks[0]) {
var innerBlock = <AST.Block>innerBlocks[0];
innerBlock.setChildren(nodes.concat(innerBlock.stmts));
this.unselect();
return;
}
}
if (curr.length == 1 && curr[0].isPlaceholder())
ch.spliceArr(this.selectionBegin, 1, nodes);
else
ch.spliceArr(this.selectionEnd + 1, 0, nodes);
this.selectionBlock.setChildren(ch);
this.unselect();
}
public getStmtIntelliItems() : IntelliItem[]
{
var res:IntelliItem[] = [];
var add = (ib:any) => {
var it = new IntelliItem();
it.nameOverride = ib.name;
if (ib.name == "for each") it.nameOverride = "foreach"; // easier search
it.descOverride = ib.desc;
if (ib.node && !ib.usageKey) {
var stmt = AST.Parser.parseStmt(ib.node)
ib.usageKey = stmt.nodeType()
}
it.usageKey = ib.usageKey;
var cbHandler = () => {
tick(ib.tick)
api.core.stmtUsage(ib.usageKey).localCount += 10;
this.changeStmtType(ib.node);
}
it.cbOverride = cbHandler;
it.score = -1;
res.push(it);
}
var addOpStmt = (op, help) => {
if (this.editor.widgetEnabled(op)) {
add({ name: op, desc: help, node: "", usageKey: op })
res.peek().cbOverride = () => TheEditor.calculator.insertOp(op, true);
}
}
add({ name: "var", desc: lf("new variable"), node: "", usageKey: "var" });
res.peek().cbOverride = () => {
tick(Ticks.codeNewVar)
TheEditor.calculator.newVar()
};
addOpStmt("show", lf("display value"))
Selector.insertionButtons().forEach(add);
addOpStmt("return", lf("stop function"))
addOpStmt("break", lf("stop loop"))
addOpStmt("continue", lf("skip iteration"))
if (this.editor.widgetEnabled("comment"))
add({ name: lf("// comment"), desc: lf("insert comment"), node: "//" });
return res;
}
public positionButtonRows()
{
if (!this.selectionBlock || !this.topButtonRow || !this.selectedStmt) return;
this.topButtonRow.className = "code-button-row " + (TheEditor.calculator.inSelectionMode() ? "tokenSelection" : "lineSelection");
this.topButtonRow.style.width = "auto";
var btnHeight = this.topButtonRow.offsetHeight;
var overlap = -0.2 * SizeMgr.topFontSize;
var h = this.buttonsAround.offsetHeight;
var pp = Util.offsetIn(this.buttonsAround, this.codeView);
this.topButtonRow.style.top = pp.y - btnHeight + overlap + "px";
this.topLeftButtonRow.style.top = pp.y - btnHeight + overlap + "px";
this.bottomButtonRow.style.top = pp.y + h - overlap + "px";
this.bottomLeftButtonRow.style.top = pp.y + h - overlap + "px";
var xx = pp.x - SizeMgr.topFontSize * 1.5;
this.topLeftButtonRow.style.left = xx + "px";
this.bottomLeftButtonRow.style.left = xx + "px";
var disableAdd = this.selectedStmt.isPlaceholder() || this.selectionBlock.immutableReason || !this.selectionBlock.allowAdding();
var inlineEditMode = TheEditor.calculator.isInlineEditing() && !!elt("inlineEditCloseBtn");
Util.childNodes(this.topButtonRow, this.topLeftButtonRow, this.bottomButtonRow, this.bottomLeftButtonRow).forEach((e:HTMLElement) => {
e.setFlag("disabled",
TheEditor.isDebuggerMode() || inlineEditMode ||
((<any>e).enableForPlaceholder && !disableAdd) ||
((<any>e).disableForPlaceholder && disableAdd) ||
this.selectionBlock.immutableReason);
});
var disableBreakpoints = !this.selectedStmt || (this.selectedStmt.nodeType() === "comment") || (!TheEditor.isDebuggerMode() && Script.annotatedBy !== AST.AnnotationMode.Crash);
if (this.breakpointBtn) this.breakpointBtn.setFlag("disabled", disableBreakpoints);
}
public canCopyPaste()
{
return (this.selectionBlock instanceof AST.CodeBlock ||
this.selectedStmt instanceof AST.OptionalParameter ||
this.selectionBlock instanceof AST.FieldBlock)
&& !(this.selectedStmt instanceof AST.FieldComment)
&& !this.editor.isDebuggerMode()
&& this.editor.widgetEnabled("copyPaste");
}
public setupCodeButtons() : void
{
this.hideCodeButtons();
this.selectedStmt = TheEditor.firstIfMissing(this.selectedStmt);
var stmt = this.selectedStmt;
if (!stmt) return;
this.setLineFlag(stmt, "carret", true);
if (!this.selectionActive) return;
this.topButtonRow = div("code-button-row");
this.topLeftButtonRow = div("code-button-row-left");
this.bottomLeftButtonRow = div("code-button-row-left");
this.bottomButtonRow = div("code-button-row");
this.codeButtons.push(this.topButtonRow, this.topLeftButtonRow, this.bottomButtonRow, this.bottomLeftButtonRow);
this.codeView.appendChildren([this.topButtonRow, this.topLeftButtonRow, this.bottomButtonRow, this.bottomLeftButtonRow]);
this.buttonsAround = EditorRenderer.setActive(stmt, true);
function mkBtn(s:string, lbl:string, key:string, tck:Ticks, f:()=>void, up = true) {
var lbl0 = null;
var lbl1 = null;
if (up) { lbl0 = div("code-button-desc", lbl); }
else { lbl1 = div("code-button-desc", lbl); }
var img0 = div("code-button-frame", HTML.mkImg(s))
var img1 = null;
if (lbl == "cut" || lbl == "copy") {
img0.className += " lineSelection";
img1 = div("code-button-frame", HTML.mkImg(s.replace("black", "#85B100")))
img1.className += " tokenSelection";
}
var b0 = HTML.mkButtonElt("code-button", lbl0, img0, img1, lbl1);
(<any>b0).disableForPlaceholder = tck == Ticks.btnAddUp || tck == Ticks.btnAddDown;
HTML.setTickCallback(b0, tck, () => {
TDev.Browser.EditorSoundManager.intellibuttonClick();
f();
})
TheEditor.keyMgr.btnShortcut(b0, key);
return b0;
}
function mkBtnDown(s:string, lbl:string, key:string, tck:Ticks, f:()=>void) {
return mkBtn(s, lbl, key, tck, f, false)
}
if (this.selectionBlock) {
var calc = TheEditor.calculator;
if (this.canCopyPaste()) {
this.topButtonRow.setChildren([
mkBtn("svg:paste,currentColor", lf("paste"), "Ctrl-V, Shift-Ins", Ticks.btnPaste, () => {
this.pasteCode()
}),
mkBtn("svg:copy,currentColor", lf("copy"), "Ctrl-C, Ctrl-Ins", Ticks.btnCopy, () => {
if (calc.inSelectionMode()) {
calc.copyHandler()
} else {
this.copyCode();
}
}),
mkBtn("svg:cut,currentColor", lf("cut"), "Ctrl-X, Shift-Del", Ticks.btnCut, () => {
if (calc.inSelectionMode()) {
calc.cutHandler()
} else {
this.cutCode();
}
})
]);
} else {
this.topButtonRow.setChildren([
mkBtn("svg:trash,currentColor", lf("delete"), "Ctrl-X, Shift-Del", Ticks.btnCut, () => {
this.cutCode();
})
]);
}
var moveLeft:HTMLElement = null;
if (stmt.isLastChild() &&
stmt.parentBlock().parent.parentBlock() != null &&
stmt.isExecutableStmt()) {
var act = TheEditor.currentAction();
if (act && (stmt.parent == act.getPageBlock(true) || stmt.parent == act.getPageBlock(false))) {}
else if (stmt.parent.parent instanceof AST.InlineAction) {}
else if (TheEditor.stepTutorial) {}
else {
moveLeft = mkBtnDown("svg:ArrowDownL,currentColor", lf("move left"), "Ctrl-L", Ticks.btnMoveLeft, () => {
tick(Ticks.codeMoveLeft);
this.moveOut()
});
(<any>moveLeft).enableForPlaceholder = true;
}
}
this.breakpointBtn = null
if (stmt.isExecutableStmt() && TheEditor.debugSupported())
this.breakpointBtn = mkBtn("svg:breakpoint,red,clip=-150", lf("breakpoint"), undefined, Ticks.btnBreakpoint, this.toggleBreakpointHandler());
var noAdd = TheEditor.widgetEnabled("singleReturnValue")
&& stmt.parent instanceof AST.ParameterBlock
&& stmt.parent == (<AST.ActionHeader>(<AST.ParameterBlock>stmt.parent).parent).outParameters
&& stmt.parentAction().hasOutParameters();
this.topLeftButtonRow.setChildren([
noAdd ? null : mkBtn("svg:add,currentColor", lf("add"), "Ctrl-Enter", Ticks.btnAddUp, this.addCallback(-1, null, Ticks.codeAddAbove)),
this.breakpointBtn
]);
this.bottomLeftButtonRow.setChildren([moveLeft,
noAdd? null : mkBtnDown("svg:add,currentColor", lf("add"), "-Enter", Ticks.btnAddDown, this.addCallback(1, null, Ticks.codeAddBelow))
]);
var t = HelpTopic.findById(this.selectedStmt.helpTopic())
HelpTopic.contextTopics = t ? [t] : [];
var wrenchDiv = div("inlineBlock wrench-button")
this.setupWrench = (style, lbl, t, cb) =>
wrenchDiv.setChildren([ mkBtnDown("svg:" + style + ",white", lbl, "", t, cb) ]);
this.clearWrench = () => wrenchDiv.setChildren([])
this.bottomButtonRow.setChildren([
wrenchDiv,
this.canCopyPaste() && TheEditor.widgetEnabled("selectStatements") ?
mkBtnDown("svg:select,currentColor", lf("select"), " Shift-Up, Down", Ticks.btnSelect, () => {
this.startSelection();
}) : null
]);
}
this.positionButtonRows();
}
public clearWrench : () => void = () => {};
public setupWrench : (style:string, lbl:string, t:Ticks, cb:()=>void) => void;
public cutCode()
{
tick(Ticks.codeCut);
this.cutSelection()
}
public copyCode()
{
tick(Ticks.codeCopy);
this.copySelection();
this.unselect()
}
private moveOut()
{
var stmt = this.selectedStmt;
if (!stmt.isLastChild()) return;
var par = stmt.parentBlock();
var newCh = par.stmts.filter((x) => x != stmt);
if (newCh.length == 0 && !par.allowEmpty())
newCh.push(par.emptyStmt());
par.setChildren(newCh);
var newPar = par.parent.parentBlock();
newCh = newPar.stmts.slice(0);
var idx = newCh.indexOf(par.parent);
newCh.splice(idx + 1, 0, stmt);
newPar.setChildren(newCh);
TheEditor.calculator.bye();
this.edit(stmt);
}
private hideCodeButtons()
{
this.codeButtons.forEach((b:any) => {
b.removeSelf();
});
this.codeButtons = [];
}
public clear()
{
if (this.selectedStmt)
EditorRenderer.setActive(this.selectedStmt, false);
this.selectionActive = false;
this.multiStmtSelectionActive = false;
this.dragMode = false;
this.hideCodeButtons();
}
private setLineFlag(s:AST.Stmt, name:string, v:boolean)
{
var n = s.renderedAs;
if (!n) return;
n = <HTMLElement>n.firstChild;
if (!n) return;
n.setFlag(name, v);
}
private moveByPage(d:number)
{
this.setSizes();
var desc = this.tops.filter((s:SizeDesc) => s.stmt == this.selectedStmt)[0];
if (!desc) return null;
var targetPos = desc.top;
var pageSize = TheEditor.codeInner.clientHeight * 0.9;
var newDesc = desc;
if (d < 0) {
targetPos -= pageSize;
newDesc = this.tops.filter((s:SizeDesc) => s.top >= targetPos)[0];
} else {
targetPos += pageSize;
for (var i = 0; i < this.tops.length; ++i) {
if (this.tops[i].top >= targetPos) break;
newDesc = this.tops[i];
}
}
if (!newDesc) return null;
return newDesc.stmt;
}
private moveByLine(d:number)
{
var seenCurr = false;
var prev:AST.Stmt = null;
var next:AST.Stmt = null;
var act = TheEditor.currentAction();
if (!act) return null;
var desc = (s:AST.AstNode) =>
{
if (s instanceof AST.Stmt) {
if (!(s instanceof AST.Block)) {
if (s == this.selectedStmt) seenCurr = true;
else {
var st = <AST.Stmt>s;
if (st.renderedAs) {
if (seenCurr) {
if (next == null) next = st;
} else {
prev = st;
}
}
}
}
s.children().forEach(desc);
}
}
desc(act.header);
if (!seenCurr) return null; // something odd is going on
var r = next;
if (d < 0) r = prev;
return r;
}
public moveCarret(d:number)
{
var newNode:AST.Stmt = null;
this.selectedStmt = TheEditor.firstIfMissing(this.selectedStmt);
if (Math.abs(d) < 2) {
newNode = this.moveByLine(d);
} else {
newNode = this.moveByPage(d);
}
if (!newNode) return;
this.setSelected(newNode);
Util.ensureVisible(this.selectedStmt.renderedAs, TheEditor.codeInner);
}
public extendCarret(dir:number)
{
if (this.dragMode) {
if (dir < 0) {
if (this.selectionBegin <= 0)
this.selectionUp();
else
this.selectionBegin--;
} else {
if (this.selectionEnd + 1 >= this.selectionBlock.stmts.length)
this.selectionUp();
else
this.selectionEnd++;
}
this.updateSelection();
} else {
this.startSelection();
}
}
public bye()
{
this.clear();
//if (!!scrollCont)
// scrollCont.removeEventListener("scroll", this, false);
}
}
export class DragMarker
{
private topPos:number;
private handle:HTMLElement;
private handler:DragHandler;
currentNode:AST.Stmt;
constructor(public isTop:boolean, public parent:Selector)
{
this.handle = div("codeMarker " + (this.isTop ? "codeMarkerTop" : "codeMarkerBottom"), SVG.getHorizontalCursorMarker());
this.currentNode = this.parent.selectedStmt;
this.parent.codeButtons.push(this.handle);
this.parent.codeView.appendChild(this.handle);
this.handler = new DragHandler(this.handle, (e,x,y) => { this.extend(e, x, y); });
this.handler.lockX = true;
}
position(p:number)
{
this.topPos = p;
p -= SizeMgr.topFontSize * 2.1;
var s = this.handle.style;
//s.right = "0px";
s.top = p + "px";
}
private extend(evt:string, dx:number, dy:number)
{
var n = this.parent.findNodeAt(this.topPos + dy);
if (evt == "release") {
this.parent.repositionMarkers();
return;
}
if (n == this.currentNode) return;
this.currentNode = n;
this.parent.recomputeSelection();
}
}
export class SelectorEditor
extends StmtEditor
{
private stmt:AST.Stmt;
constructor() {
super()
}
public editedStmt():AST.Stmt { return this.stmt; }
public edit(ss:AST.Stmt)
{
tick(Ticks.editTapBelow)
this.stmt = ss;
TheEditor.showStmtEditor(this);
}
public bye()
{
}
}
} | the_stack |
import React, { useCallback, useRef, useState } from 'react'
import styled from 'styled-components'
import { useMutation } from '@apollo/client'
import { useWidthOf } from 'v2/hooks/useCurrentWidth'
import DropZoneUploader from 'v2/components/UI/DropZoneUploader'
import { AddBlockPasteUploader } from 'v2/components/AddBlock/components/AddBlockPasteUploader'
import Box from 'v2/components/UI/Box'
import Link from 'v2/components/UI/Link'
import { Textarea } from 'v2/components/UI/Inputs'
import GenericButton from 'v2/components/UI/GenericButton'
import Text from 'v2/components/UI/Text'
import Icon from 'v2/components/UI/Icons'
import Overlay from 'v2/components/UI/Overlay'
import constants from 'v2/styles/constants'
import CREATE_BLOCK_MUTATION from './mutations/createBlock'
import {
tableCreateAddBlockMutation,
tableCreateAddBlockMutationVariables,
} from '__generated__/tableCreateAddBlockMutation'
import Filter from '../FilterContainer'
import { ConnectableTypeEnum } from '__generated__/globalTypes'
import { ChannelTableConnectors_channel_connectors } from '__generated__/ChannelTableConnectors'
const AddButton = styled(GenericButton).attrs({
bg: 'gray.light',
})`
border-radius: 0px;
height: 100%;
width: 60px;
border: 0px solid transparent;
padding: 0;
border-left: 1px solid ${x => x.theme.colors.gray.light};
&:hover {
border: 0px solid transparent !important;
}
`
const Middle = styled(Box).attrs({
bg: 'white',
})`
width: 10px;
height: 110%;
transform: translateY(-1px);
`
const FilterButton = styled(GenericButton).attrs({
bg: 'gray.hint',
})`
border-radius: 0px;
height: 100%;
width: 36px;
border: 0px solid transparent;
padding: 0;
border-right: 1px solid ${x => x.theme.colors.gray.light};
&:hover {
border: 0px solid transparent !important;
border-right: 1px solid ${x => x.theme.colors.gray.light} !important;
}
`
const Message = styled(Box)`
text-align: left;
`
const Choose = styled(Link)`
position: relative;
border-bottom: 1px solid;
z-index: 1;
cursor: pointer;
`
const Input = styled(Textarea).attrs({
resize: 'none',
f: 2,
})`
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 100%;
height: 100%;
border: 0;
background-color: transparent;
overflow: hidden;
&:focus {
border: 0;
background-color: ${props => props.theme.colors.gray.light};
z-index: 2;
}
`
const Container = styled(Box)`
position: relative;
line-height: 0;
vertical-align: top;
height: 100%;
width: 100%;
text-align: right;
display: flex;
justify-content: space-between;
`
const AddFieldContainer = styled(Box)`
position: absolute;
background-color: ${({ theme }) => theme.colors.gray.hint};
top: 0;
right: ${({ offsetWidth }) => `${offsetWidth}px`};
height: 100%;
padding: ${constants.space[5]};
justify-content: flex-start;
line-height: 1;
align-items: center;
width: ${({ containerWidth, offsetWidth }) =>
`${containerWidth - offsetWidth - 2}px`};
display: ${({ mode }) => (mode == 'resting' ? 'none' : 'flex')};
`
type AddButtonState = 'resting' | 'ready' | 'active' | 'submitting' | 'error'
type FilterButtonState =
| 'resting'
| 'open'
| 'active'
| 'activeAndOpen'
| 'error'
interface TableAddButtonInnerProps {
containerWidth: number
offsetWidth: number
mode: AddButtonState
channelId: number
openUploadDialog: () => void
handleOnChange: (value: string) => void
handleOnKeyDown: (e: any) => void
value: string
}
const TableAddButtonInner: React.FC<TableAddButtonInnerProps> = ({
containerWidth,
offsetWidth,
mode,
openUploadDialog,
handleOnChange,
handleOnKeyDown,
value,
}) => {
return (
<AddFieldContainer
mode={mode}
containerWidth={containerWidth}
offsetWidth={offsetWidth}
>
{value.length == 0 && (
<Message p={6}>
<Text f={2} fontWeight="normal">
Drop or <Choose onClick={openUploadDialog}>choose</Choose> files,
paste a URL (image, video, or link) or type text here
</Text>
</Message>
)}
<Input onChange={handleOnChange} onKeyDown={handleOnKeyDown} />
</AddFieldContainer>
)
}
interface TableAddButtonProps {
channelId: number
addBlock: () => void
type?: ConnectableTypeEnum
user?: ChannelTableConnectors_channel_connectors
setType: (value: ConnectableTypeEnum) => void
setUser: (value: ChannelTableConnectors_channel_connectors) => void
}
export const TableAddButton: React.ForwardRefExoticComponent<TableAddButtonProps & {
ref?: React.Ref<HTMLElement>
}> = React.forwardRef(
(
{ channelId, addBlock, setType, setUser, type, user },
forwardedRef: React.MutableRefObject<HTMLInputElement | null> | null
) => {
const buttonContainerRef = useRef<HTMLElement>()
const filterRef = useRef<HTMLElement>()
const [value, setValue] = useState<string>('')
const { width: containerWidth } = useWidthOf({ ref: forwardedRef })
const { width: buttonContainerWidth } = useWidthOf({
ref: buttonContainerRef,
})
const [mode, setMode] = useState<AddButtonState>('resting')
const [filterMode, setFilterMode] = useState<FilterButtonState>('resting')
const [uploaderKey, setUploaderKey] = useState<number>(new Date().getTime())
const [createBlock] = useMutation<
tableCreateAddBlockMutation,
tableCreateAddBlockMutationVariables
>(CREATE_BLOCK_MUTATION)
//
// On filter button press
//
const handleFilterClick = useCallback(() => {
if (filterMode == 'open') {
return setFilterMode('resting')
}
if (filterMode === 'activeAndOpen') {
return setFilterMode('active')
}
if (filterMode === 'active') {
return setFilterMode('activeAndOpen')
}
if (filterMode === 'resting') {
return setFilterMode('open')
}
}, [setFilterMode, filterMode])
//
// On add button press
//
const handleOnClick = useCallback(() => {
if (mode === 'resting') {
return setMode('ready')
}
if (mode === 'ready') {
return setMode('resting')
}
if (mode === 'active') {
setMode('submitting')
return createBlock({
variables: { value, channel_id: channelId.toString() },
}).then(() => {
setMode('resting')
setValue('')
finishUpload()
addBlock()
})
}
}, [setMode, mode, value])
//
// On input change
//
const handleOnChange = useCallback(({ target: { value } }) => {
setValue(value)
if (value.length == 0) {
setMode('ready')
}
if (value.length > 0) {
setMode('active')
}
}, [])
const handleKeyDown = useCallback(
e => {
const { key, shiftKey } = e
if (key === 'Enter' && !shiftKey) {
e.preventDefault()
e.stopPropagation()
handleOnClick()
}
// Allows <shift+enter> to pass through
},
[handleOnClick]
)
//
// On successful upload (drop or choose file)
//
const handleUpload = useCallback(
({ url: value }) => {
return createBlock({
variables: { channel_id: channelId.toString(), value },
})
.then(response => {
if (response && response.data) {
addBlock()
}
})
.catch(err => {
console.error(err)
})
},
[createBlock, addBlock]
)
//
// Callback for upload finishing
//
const finishUpload = useCallback(() => {
setUploaderKey(new Date().getTime())
}, [setUploaderKey])
return (
<Container ref={buttonContainerRef}>
<AddBlockPasteUploader
createBlock={createBlock}
channelId={channelId}
onAddBlock={addBlock}
/>
<DropZoneUploader
accept="image/*,audio/*,video/*,application/*" // TODO
onUpload={handleUpload}
onComplete={finishUpload}
key={uploaderKey}
>
{({ openUploadDialog }) => (
<>
<Box position="relative" ref={filterRef}>
<FilterButton f={1} onClick={handleFilterClick}>
<Icon name="Filters" size="1rem" />
</FilterButton>
{filterRef.current &&
(filterMode == 'open' || filterMode === 'activeAndOpen') && (
<Overlay
alignToY="bottom"
alignToX="right"
anchorY="top"
anchorX="right"
targetEl={() => filterRef.current}
offsetY={5}
onClose={() => setFilterMode('resting')}
>
<Filter
id={channelId}
type={type}
user={user}
setType={setType}
setUser={setUser}
/>
</Overlay>
)}
</Box>
<Middle />
<AddButton onClick={handleOnClick} f={1}>
{
{
resting: 'Add +',
ready: 'Cancel',
active: 'Save',
submitting: 'Saving...',
error: 'Error',
}[mode]
}
</AddButton>
<TableAddButtonInner
key={uploaderKey}
value={value}
handleOnChange={handleOnChange}
handleOnKeyDown={handleKeyDown}
openUploadDialog={openUploadDialog}
channelId={channelId}
mode={mode}
containerWidth={containerWidth}
offsetWidth={buttonContainerWidth}
/>
</>
)}
</DropZoneUploader>
</Container>
)
}
) | the_stack |
import { PouchDB } from "./pouchdb-browser";
import xxhash from "xxhash-wasm";
import {
Entry,
EntryDoc,
EntryDocResponse,
EntryLeaf,
EntryNodeInfo,
NewEntry,
PlainEntry,
LoadedEntry,
Credential,
EntryMilestoneInfo,
LOG_LEVEL,
LEAF_WAIT_TIMEOUT,
MAX_DOC_SIZE,
MAX_DOC_SIZE_BIN,
NODEINFO_DOCID,
VER,
MILSTONE_DOCID,
DatabaseConnectingStatus,
ObsidianLiveSyncSettings,
} from "./lib/src/types";
import { RemoteDBSettings } from "./lib/src/types";
import { resolveWithIgnoreKnownError, delay, runWithLock, NewNotice, WrappedNotice, shouldSplitAsPlainText, splitPieces2, enableEncryption } from "./lib/src/utils";
import { path2id } from "./utils";
import { Logger } from "./lib/src/logger";
import { checkRemoteVersion, connectRemoteCouchDBWithSetting, getLastPostFailedBySize } from "./utils_couchdb";
import { openDB, deleteDB, IDBPDatabase } from "idb";
import { KeyValueDatabase, OpenKeyValueDatabase } from "./KeyValueDB";
type ReplicationCallback = (e: PouchDB.Core.ExistingDocument<EntryDoc>[]) => Promise<void>;
class LRUCache {
cache = new Map<string, string>([]);
revCache = new Map<string, string>([]);
maxCache = 100;
constructor() { }
get(key: string) {
// debugger
const v = this.cache.get(key);
if (v) {
// update the key to recently used.
this.cache.delete(key);
this.revCache.delete(v);
this.cache.set(key, v);
this.revCache.set(v, key);
}
return v;
}
revGet(value: string) {
// debugger
const key = this.revCache.get(value);
if (value) {
// update the key to recently used.
this.cache.delete(key);
this.revCache.delete(value);
this.cache.set(key, value);
this.revCache.set(value, key);
}
return key;
}
set(key: string, value: string) {
this.cache.set(key, value);
this.revCache.set(value, key);
if (this.cache.size > this.maxCache) {
for (const kv of this.cache) {
this.revCache.delete(kv[1]);
this.cache.delete(kv[0]);
if (this.cache.size <= this.maxCache) break;
}
}
}
}
export class LocalPouchDB {
auth: Credential;
dbname: string;
settings: RemoteDBSettings;
localDatabase: PouchDB.Database<EntryDoc>;
kvDB: KeyValueDatabase;
nodeid = "";
isReady = false;
recentModifiedDocs: string[] = [];
h32: (input: string, seed?: number) => string;
h64: (input: string, seedHigh?: number, seedLow?: number) => string;
h32Raw: (input: Uint8Array, seed?: number) => number;
// hashCache: {
// [key: string]: string;
// } = {};
// hashCacheRev: {
// [key: string]: string;
// } = {};
hashCaches = new LRUCache();
corruptedEntries: { [key: string]: EntryDoc } = {};
remoteLocked = false;
remoteLockedAndDeviceNotAccepted = false;
changeHandler: PouchDB.Core.Changes<EntryDoc> = null;
syncHandler: PouchDB.Replication.Sync<EntryDoc> | PouchDB.Replication.Replication<EntryDoc> = null;
leafArrivedCallbacks: { [key: string]: (() => void)[] } = {};
syncStatus: DatabaseConnectingStatus = "NOT_CONNECTED";
docArrived = 0;
docSent = 0;
docSeq = "";
isMobile = false;
cancelHandler<T extends PouchDB.Core.Changes<EntryDoc> | PouchDB.Replication.Sync<EntryDoc> | PouchDB.Replication.Replication<EntryDoc>>(handler: T): T {
if (handler != null) {
handler.removeAllListeners();
handler.cancel();
handler = null;
}
return null;
}
onunload() {
this.kvDB.close();
this.recentModifiedDocs = [];
this.leafArrivedCallbacks;
this.changeHandler = this.cancelHandler(this.changeHandler);
this.syncHandler = this.cancelHandler(this.syncHandler);
this.localDatabase.removeAllListeners();
}
constructor(settings: RemoteDBSettings, dbname: string, isMobile: boolean) {
this.auth = {
username: "",
password: "",
};
this.dbname = dbname;
this.settings = settings;
this.cancelHandler = this.cancelHandler.bind(this);
this.isMobile = isMobile;
}
close() {
Logger("Database closed (by close)");
this.isReady = false;
this.changeHandler = this.cancelHandler(this.changeHandler);
if (this.localDatabase != null) {
this.localDatabase.close();
}
this.kvDB.close();
}
async isOldDatabaseExists() {
const db = new PouchDB<EntryDoc>(this.dbname + "-livesync", {
auto_compaction: this.settings.useHistory ? false : true,
revs_limit: 20,
deterministic_revs: true,
skip_setup: true,
});
try {
const info = await db.info();
Logger(info, LOG_LEVEL.VERBOSE);
return db;
} catch (ex) {
return false;
}
}
async initializeDatabase(): Promise<boolean> {
await this.prepareHashFunctions();
if (this.localDatabase != null) this.localDatabase.close();
this.changeHandler = this.cancelHandler(this.changeHandler);
this.localDatabase = null;
this.localDatabase = new PouchDB<EntryDoc>(this.dbname + "-livesync-v2", {
auto_compaction: this.settings.useHistory ? false : true,
revs_limit: 100,
deterministic_revs: true,
});
this.kvDB = OpenKeyValueDatabase(this.dbname + "-livesync-kv");
Logger("Database info", LOG_LEVEL.VERBOSE);
Logger(await this.localDatabase.info(), LOG_LEVEL.VERBOSE);
Logger("Open Database...");
// The sequence after migration.
const nextSeq = async (): Promise<boolean> => {
Logger("Database Info");
Logger(await this.localDatabase.info(), LOG_LEVEL.VERBOSE);
// initialize local node information.
const nodeinfo: EntryNodeInfo = await resolveWithIgnoreKnownError<EntryNodeInfo>(this.localDatabase.get(NODEINFO_DOCID), {
_id: NODEINFO_DOCID,
type: "nodeinfo",
nodeid: "",
v20220607: true,
});
if (nodeinfo.nodeid == "") {
nodeinfo.nodeid = Math.random().toString(36).slice(-10);
await this.localDatabase.put(nodeinfo);
}
this.localDatabase.on("close", () => {
Logger("Database closed.");
this.isReady = false;
this.localDatabase.removeAllListeners();
});
this.nodeid = nodeinfo.nodeid;
// Traceing the leaf id
const changes = this.localDatabase
.changes({
since: "now",
live: true,
filter: (doc) => doc.type == "leaf",
})
.on("change", (e) => {
if (e.deleted) return;
this.leafArrived(e.id);
this.docSeq = `${e.seq}`;
});
this.changeHandler = changes;
this.isReady = true;
Logger("Database is now ready.");
return true;
};
Logger("Checking old database", LOG_LEVEL.VERBOSE);
const old = await this.isOldDatabaseExists();
//Migrate.
if (old) {
const oi = await old.info();
if (oi.doc_count == 0) {
Logger("Old database is empty, proceed to next step", LOG_LEVEL.VERBOSE);
// aleady converted.
return nextSeq();
}
//
const progress = NewNotice("Converting..", 0);
try {
Logger("We have to upgrade database..", LOG_LEVEL.NOTICE);
// To debug , uncomment below.
// this.localDatabase.destroy();
// await delay(100);
// this.localDatabase = new PouchDB<EntryDoc>(this.dbname + "-livesync-v2", {
// auto_compaction: this.settings.useHistory ? false : true,
// revs_limit: 100,
// deterministic_revs: true,
// });
const newDbStatus = await this.localDatabase.info();
Logger("New database is initialized");
Logger(newDbStatus);
if (this.settings.encrypt) {
enableEncryption(old, this.settings.passphrase, true);
}
const rep = old.replicate.to(this.localDatabase, { batch_size: 25, batches_limit: 10 });
rep.on("change", (e) => {
progress.setMessage(`Converting ${e.docs_written} docs...`);
Logger(`Converting ${e.docs_written} docs...`, LOG_LEVEL.VERBOSE);
});
const w = await rep;
progress.hide();
if (w.ok) {
Logger("Conversion completed!", LOG_LEVEL.NOTICE);
old.destroy(); // delete the old database.
this.isReady = true;
return await nextSeq();
} else {
throw new Error("Conversion failed!");
}
} catch (ex) {
progress.hide();
Logger("Conversion failed!, If you are fully synchronized, please drop the old database in the Hatch pane in setting dialog. or please make an issue on Github.", LOG_LEVEL.NOTICE);
Logger(ex);
this.isReady = false;
return false;
}
} else {
return await nextSeq();
}
}
async prepareHashFunctions() {
if (this.h32 != null) return;
const { h32, h64, h32Raw } = await xxhash();
this.h32 = h32;
this.h64 = h64;
this.h32Raw = h32Raw;
}
// leaf waiting
leafArrived(id: string) {
if (typeof this.leafArrivedCallbacks[id] !== "undefined") {
for (const func of this.leafArrivedCallbacks[id]) {
func();
}
delete this.leafArrivedCallbacks[id];
}
}
// wait
waitForLeafReady(id: string): Promise<boolean> {
return new Promise((res, rej) => {
// Set timeout.
const timer = setTimeout(() => rej(new Error(`Chunk reading timed out:${id}`)), LEAF_WAIT_TIMEOUT);
if (typeof this.leafArrivedCallbacks[id] == "undefined") {
this.leafArrivedCallbacks[id] = [];
}
this.leafArrivedCallbacks[id].push(() => {
clearTimeout(timer);
res(true);
});
});
}
async getDBLeaf(id: string, waitForReady: boolean): Promise<string> {
await this.waitForGCComplete();
// when in cache, use that.
const leaf = this.hashCaches.revGet(id);
if (leaf) {
return leaf;
}
try {
const w = await this.localDatabase.get(id);
if (w.type == "leaf") {
this.hashCaches.set(id, w.data);
return w.data;
}
throw new Error(`Corrupted chunk detected: ${id}`);
} catch (ex) {
if (ex.status && ex.status == 404) {
if (waitForReady) {
// just leaf is not ready.
// wait for on
if ((await this.waitForLeafReady(id)) === false) {
throw new Error(`time out (waiting chunk)`);
}
return this.getDBLeaf(id, false);
} else {
throw new Error(`Chunk was not found: ${id}`);
}
} else {
Logger(`Something went wrong on retriving chunk`);
throw ex;
}
}
}
async getDBEntryMeta(path: string, opt?: PouchDB.Core.GetOptions): Promise<false | LoadedEntry> {
await this.waitForGCComplete();
const id = path2id(path);
try {
let obj: EntryDocResponse = null;
if (opt) {
obj = await this.localDatabase.get(id, opt);
} else {
obj = await this.localDatabase.get(id);
}
if (obj.type && obj.type == "leaf") {
//do nothing for leaf;
return false;
}
// retrieve metadata only
if (!obj.type || (obj.type && obj.type == "notes") || obj.type == "newnote" || obj.type == "plain") {
const note = obj as Entry;
let children: string[] = [];
if (obj.type == "newnote" || obj.type == "plain") {
children = obj.children;
}
const doc: LoadedEntry & PouchDB.Core.IdMeta & PouchDB.Core.GetMeta = {
data: "",
_id: note._id,
ctime: note.ctime,
mtime: note.mtime,
size: note.size,
_deleted: obj._deleted,
_rev: obj._rev,
_conflicts: obj._conflicts,
children: children,
datatype: "newnote",
};
return doc;
}
} catch (ex) {
if (ex.status && ex.status == 404) {
return false;
}
throw ex;
}
return false;
}
async getDBEntry(path: string, opt?: PouchDB.Core.GetOptions, dump = false, waitForReady = true): Promise<false | LoadedEntry> {
await this.waitForGCComplete();
const id = path2id(path);
try {
let obj: EntryDocResponse = null;
if (opt) {
obj = await this.localDatabase.get(id, opt);
} else {
obj = await this.localDatabase.get(id);
}
if (obj.type && obj.type == "leaf") {
//do nothing for leaf;
return false;
}
//Check it out and fix docs to regular case
if (!obj.type || (obj.type && obj.type == "notes")) {
const note = obj as Entry;
const doc: LoadedEntry & PouchDB.Core.IdMeta & PouchDB.Core.GetMeta = {
data: note.data,
_id: note._id,
ctime: note.ctime,
mtime: note.mtime,
size: note.size,
_deleted: obj._deleted,
_rev: obj._rev,
_conflicts: obj._conflicts,
children: [],
datatype: "newnote",
};
if (typeof this.corruptedEntries[doc._id] != "undefined") {
delete this.corruptedEntries[doc._id];
}
if (dump) {
Logger(`Simple doc`);
Logger(doc);
}
return doc;
// simple note
}
if (obj.type == "newnote" || obj.type == "plain") {
// search childrens
try {
if (dump) {
Logger(`Enhanced doc`);
Logger(obj);
}
let childrens: string[];
try {
childrens = await Promise.all(obj.children.map((e) => this.getDBLeaf(e, waitForReady)));
if (dump) {
Logger(`Chunks:`);
Logger(childrens);
}
} catch (ex) {
Logger(`Something went wrong on reading chunks of ${obj._id} from database, see verbose info for detail.`, LOG_LEVEL.NOTICE);
Logger(ex, LOG_LEVEL.VERBOSE);
this.corruptedEntries[obj._id] = obj;
return false;
}
const data = childrens.join("");
const doc: LoadedEntry & PouchDB.Core.IdMeta & PouchDB.Core.GetMeta = {
data: data,
_id: obj._id,
ctime: obj.ctime,
mtime: obj.mtime,
size: obj.size,
_deleted: obj._deleted,
_rev: obj._rev,
children: obj.children,
datatype: obj.type,
_conflicts: obj._conflicts,
};
if (dump) {
Logger(`therefore:`);
Logger(doc);
}
if (typeof this.corruptedEntries[doc._id] != "undefined") {
delete this.corruptedEntries[doc._id];
}
return doc;
} catch (ex) {
if (ex.status && ex.status == 404) {
Logger(`Missing document content!, could not read ${obj._id} from database.`, LOG_LEVEL.NOTICE);
return false;
}
Logger(`Something went wrong on reading ${obj._id} from database:`, LOG_LEVEL.NOTICE);
Logger(ex);
}
}
} catch (ex) {
if (ex.status && ex.status == 404) {
return false;
}
throw ex;
}
return false;
}
async deleteDBEntry(path: string, opt?: PouchDB.Core.GetOptions): Promise<boolean> {
await this.waitForGCComplete();
const id = path2id(path);
try {
let obj: EntryDocResponse = null;
return await runWithLock("file:" + id, false, async () => {
if (opt) {
obj = await this.localDatabase.get(id, opt);
} else {
obj = await this.localDatabase.get(id);
}
if (obj.type && obj.type == "leaf") {
//do nothing for leaf;
return false;
}
//Check it out and fix docs to regular case
if (!obj.type || (obj.type && obj.type == "notes")) {
obj._deleted = true;
const r = await this.localDatabase.put(obj);
Logger(`entry removed:${obj._id}-${r.rev}`);
if (typeof this.corruptedEntries[obj._id] != "undefined") {
delete this.corruptedEntries[obj._id];
}
return true;
// simple note
}
if (obj.type == "newnote" || obj.type == "plain") {
obj._deleted = true;
const r = await this.localDatabase.put(obj);
Logger(`entry removed:${obj._id}-${r.rev}`);
if (typeof this.corruptedEntries[obj._id] != "undefined") {
delete this.corruptedEntries[obj._id];
}
return true;
} else {
return false;
}
});
} catch (ex) {
if (ex.status && ex.status == 404) {
return false;
}
throw ex;
}
}
async deleteDBEntryPrefix(prefixSrc: string): Promise<boolean> {
await this.waitForGCComplete();
// delete database entries by prefix.
// it called from folder deletion.
let c = 0;
let readCount = 0;
const delDocs: string[] = [];
const prefix = path2id(prefixSrc);
do {
const result = await this.localDatabase.allDocs({ include_docs: false, skip: c, limit: 100, conflicts: true });
readCount = result.rows.length;
if (readCount > 0) {
//there are some result
for (const v of result.rows) {
// let doc = v.doc;
if (v.id.startsWith(prefix) || v.id.startsWith("/" + prefix)) {
delDocs.push(v.id);
// console.log("!" + v.id);
} else {
if (!v.id.startsWith("h:")) {
// console.log("?" + v.id);
}
}
}
}
c += readCount;
} while (readCount != 0);
// items collected.
//bulk docs to delete?
let deleteCount = 0;
let notfound = 0;
for (const v of delDocs) {
try {
await runWithLock("file:" + v, false, async () => {
const item = await this.localDatabase.get(v);
item._deleted = true;
await this.localDatabase.put(item);
});
deleteCount++;
} catch (ex) {
if (ex.status && ex.status == 404) {
notfound++;
// NO OP. It should be timing problem.
} else {
throw ex;
}
}
}
Logger(`deleteDBEntryPrefix:deleted ${deleteCount} items, skipped ${notfound}`);
return true;
}
async putDBEntry(note: LoadedEntry) {
await this.waitForGCComplete();
// let leftData = note.data;
const savenNotes = [];
let processed = 0;
let made = 0;
let skiped = 0;
let pieceSize = MAX_DOC_SIZE_BIN;
let plainSplit = false;
let cacheUsed = 0;
const userpasswordHash = this.h32Raw(new TextEncoder().encode(this.settings.passphrase));
if (shouldSplitAsPlainText(note._id)) {
pieceSize = MAX_DOC_SIZE;
plainSplit = true;
}
const newLeafs: EntryLeaf[] = [];
// To keep low bandwith and database size,
// Dedup pieces on database.
// from 0.1.10, for best performance. we use markdown delimiters
// 1. \n[^\n]{longLineThreshold}[^\n]*\n -> long sentence shuld break.
// 2. \n\n shold break
// 3. \r\n\r\n should break
// 4. \n# should break.
let minimumChunkSize = this.settings.minimumChunkSize;
if (minimumChunkSize < 10) minimumChunkSize = 10;
let longLineThreshold = this.settings.longLineThreshold;
if (longLineThreshold < 100) longLineThreshold = 100;
const pieces = splitPieces2(note.data, pieceSize, plainSplit, minimumChunkSize, longLineThreshold);
for (const piece of pieces()) {
processed++;
let leafid = "";
// Get hash of piece.
let hashedPiece = "";
let hashQ = 0; // if hash collided, **IF**, count it up.
let tryNextHash = false;
let needMake = true;
const cache = this.hashCaches.get(piece);
if (cache) {
hashedPiece = "";
leafid = cache;
needMake = false;
skiped++;
cacheUsed++;
} else {
if (this.settings.encrypt) {
// When encryption has been enabled, make hash to be different between each passphrase to avoid inferring password.
hashedPiece = "+" + (this.h32Raw(new TextEncoder().encode(piece)) ^ userpasswordHash).toString(16);
} else {
hashedPiece = this.h32(piece);
}
leafid = "h:" + hashedPiece;
do {
let nleafid = leafid;
try {
nleafid = `${leafid}${hashQ}`;
const pieceData = await this.localDatabase.get<EntryLeaf>(nleafid);
if (pieceData.type == "leaf" && pieceData.data == piece) {
leafid = nleafid;
needMake = false;
tryNextHash = false;
this.hashCaches.set(piece, leafid);
} else if (pieceData.type == "leaf") {
Logger("hash:collision!!");
hashQ++;
tryNextHash = true;
} else {
leafid = nleafid;
tryNextHash = false;
}
} catch (ex) {
if (ex.status && ex.status == 404) {
//not found, we can use it.
leafid = nleafid;
needMake = true;
tryNextHash = false;
} else {
needMake = false;
tryNextHash = false;
throw ex;
}
}
} while (tryNextHash);
if (needMake) {
//have to make
const savePiece = piece;
const d: EntryLeaf = {
_id: leafid,
data: savePiece,
type: "leaf",
};
newLeafs.push(d);
this.hashCaches.set(piece, leafid);
made++;
} else {
skiped++;
}
}
savenNotes.push(leafid);
}
let saved = true;
if (newLeafs.length > 0) {
try {
const result = await this.localDatabase.bulkDocs(newLeafs);
for (const item of result) {
if (!(item as any).ok) {
if ((item as any).status && (item as any).status == 409) {
// conflicted, but it would be ok in childrens.
} else {
Logger(`Save failed:id:${item.id} rev:${item.rev}`, LOG_LEVEL.NOTICE);
Logger(item);
saved = false;
}
}
}
if (saved) {
Logger(`Chunk saved:${newLeafs.length} chunks`);
}
} catch (ex) {
Logger("Chunk save failed:", LOG_LEVEL.NOTICE);
Logger(ex, LOG_LEVEL.NOTICE);
saved = false;
}
}
if (saved) {
Logger(`note content saven, pieces:${processed} new:${made}, skip:${skiped}, cache:${cacheUsed}`);
const newDoc: PlainEntry | NewEntry = {
NewNote: true,
children: savenNotes,
_id: note._id,
ctime: note.ctime,
mtime: note.mtime,
size: note.size,
type: plainSplit ? "plain" : "newnote",
};
// Here for upsert logic,
await runWithLock("file:" + newDoc._id, false, async () => {
try {
const old = await this.localDatabase.get(newDoc._id);
if (!old.type || old.type == "notes" || old.type == "newnote" || old.type == "plain") {
// simple use rev for new doc
newDoc._rev = old._rev;
}
} catch (ex) {
if (ex.status && ex.status == 404) {
// NO OP/
} else {
throw ex;
}
}
const r = await this.localDatabase.put(newDoc, { force: true });
if (typeof this.corruptedEntries[note._id] != "undefined") {
delete this.corruptedEntries[note._id];
}
if (this.settings.checkIntegrityOnSave) {
if (!this.sanCheck(await this.localDatabase.get(r.id))) {
Logger("note save failed!", LOG_LEVEL.NOTICE);
} else {
Logger(`note has been surely saved:${newDoc._id}:${r.rev}`);
}
} else {
Logger(`note saved:${newDoc._id}:${r.rev}`);
}
});
} else {
Logger(`note coud not saved:${note._id}`);
}
}
updateInfo: () => void = () => {
console.log("default updinfo");
};
// eslint-disable-next-line require-await
async migrate(from: number, to: number): Promise<boolean> {
Logger(`Database updated from ${from} to ${to}`, LOG_LEVEL.NOTICE);
// no op now,
return true;
}
replicateAllToServer(setting: RemoteDBSettings, showingNotice?: boolean) {
return new Promise(async (res, rej) => {
await this.waitForGCComplete();
this.openOneshotReplication(
setting,
showingNotice,
async (e) => { },
false,
(e) => {
if (e === true) res(e);
rej(e);
},
true,
false
);
});
}
async checkReplicationConnectivity(setting: RemoteDBSettings, keepAlive: boolean, skipCheck: boolean, showResult: boolean) {
if (!this.isReady) {
Logger("Database is not ready.");
return false;
}
await this.waitForGCComplete();
if (setting.versionUpFlash != "") {
NewNotice("Open settings and check message, please.");
return false;
}
const uri = setting.couchDB_URI + (setting.couchDB_DBNAME == "" ? "" : "/" + setting.couchDB_DBNAME);
if (this.syncHandler != null) {
Logger("Another replication running.");
return false;
}
const dbret = await connectRemoteCouchDBWithSetting(setting, this.isMobile);
if (typeof dbret === "string") {
Logger(`could not connect to ${uri}: ${dbret}`, showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO);
return false;
}
if (!skipCheck) {
if (!(await checkRemoteVersion(dbret.db, this.migrate.bind(this), VER))) {
Logger("Remote database is newer or corrupted, make sure to latest version of self-hosted-livesync installed", LOG_LEVEL.NOTICE);
return false;
}
const defMilestonePoint: EntryMilestoneInfo = {
_id: MILSTONE_DOCID,
type: "milestoneinfo",
created: (new Date() as any) / 1,
locked: false,
accepted_nodes: [this.nodeid],
};
const remoteMilestone: EntryMilestoneInfo = await resolveWithIgnoreKnownError(dbret.db.get(MILSTONE_DOCID), defMilestonePoint);
this.remoteLocked = remoteMilestone.locked;
this.remoteLockedAndDeviceNotAccepted = remoteMilestone.locked && remoteMilestone.accepted_nodes.indexOf(this.nodeid) == -1;
if (remoteMilestone.locked && remoteMilestone.accepted_nodes.indexOf(this.nodeid) == -1) {
Logger("Remote database marked as 'Auto Sync Locked'. And this devide does not marked as resolved device. see settings dialog.", LOG_LEVEL.NOTICE);
return false;
}
if (typeof remoteMilestone._rev == "undefined") {
await dbret.db.put(remoteMilestone);
}
}
const syncOptionBase: PouchDB.Replication.SyncOptions = {
batches_limit: setting.batches_limit,
batch_size: setting.batch_size,
};
const syncOption: PouchDB.Replication.SyncOptions = keepAlive ? { live: true, retry: true, heartbeat: 30000, ...syncOptionBase } : { ...syncOptionBase };
return { db: dbret.db, info: dbret.info, syncOptionBase, syncOption };
}
openReplication(setting: RemoteDBSettings, keepAlive: boolean, showResult: boolean, callback: (e: PouchDB.Core.ExistingDocument<EntryDoc>[]) => Promise<void>) {
if (keepAlive) {
this.openContinuousReplication(setting, showResult, callback, false);
} else {
this.openOneshotReplication(setting, showResult, callback, false, null, false, false);
}
}
replicationActivated(notice: WrappedNotice) {
this.syncStatus = "CONNECTED";
this.updateInfo();
Logger("Replication activated");
if (notice != null) notice.setMessage(`Activated..`);
}
async replicationChangeDetected(e: PouchDB.Replication.SyncResult<EntryDoc>, notice: WrappedNotice, docSentOnStart: number, docArrivedOnStart: number, callback: ReplicationCallback) {
try {
if (e.direction == "pull") {
await callback(e.change.docs);
Logger(`replicated ${e.change.docs_read} doc(s)`);
this.docArrived += e.change.docs.length;
} else {
this.docSent += e.change.docs.length;
}
if (notice != null) {
notice.setMessage(`↑${this.docSent - docSentOnStart} ↓${this.docArrived - docArrivedOnStart}`);
}
this.updateInfo();
} catch (ex) {
Logger("Replication callback error", LOG_LEVEL.NOTICE);
Logger(ex, LOG_LEVEL.NOTICE);
//
}
}
replicationCompleted(notice: WrappedNotice, showResult: boolean) {
this.syncStatus = "COMPLETED";
this.updateInfo();
Logger("Replication completed", showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO);
if (notice != null) notice.hide();
this.syncHandler = this.cancelHandler(this.syncHandler);
}
replicationDeniend(notice: WrappedNotice, e: any) {
this.syncStatus = "ERRORED";
this.updateInfo();
this.syncHandler = this.cancelHandler(this.syncHandler);
if (notice != null) notice.hide();
Logger("Replication denied", LOG_LEVEL.NOTICE);
Logger(e);
}
replicationErrored(notice: WrappedNotice, e: any) {
this.syncStatus = "ERRORED";
this.syncHandler = this.cancelHandler(this.syncHandler);
this.updateInfo();
}
replicationPaused(notice: WrappedNotice) {
this.syncStatus = "PAUSED";
this.updateInfo();
if (notice != null) notice.hide();
Logger("replication paused", LOG_LEVEL.VERBOSE);
}
async openOneshotReplication(
setting: RemoteDBSettings,
showResult: boolean,
callback: (e: PouchDB.Core.ExistingDocument<EntryDoc>[]) => Promise<void>,
retrying: boolean,
callbackDone: (e: boolean | any) => void,
pushOnly: boolean,
pullOnly: boolean
): Promise<boolean> {
if (this.syncHandler != null) {
Logger("Replication is already in progress.", showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO);
return;
}
Logger("Oneshot Sync begin...");
let thisCallback = callbackDone;
const ret = await this.checkReplicationConnectivity(setting, true, retrying, showResult);
let notice: WrappedNotice = null;
if (ret === false) {
Logger("Could not connect to server.", showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO);
return;
}
if (showResult) {
notice = NewNotice("Looking for the point last synchronized point.", 0);
}
const { db, syncOptionBase } = ret;
this.syncStatus = "STARTED";
this.updateInfo();
const docArrivedOnStart = this.docArrived;
const docSentOnStart = this.docSent;
if (!retrying) {
// If initial replication, save setting to rollback
this.originalSetting = setting;
}
this.syncHandler = this.cancelHandler(this.syncHandler);
if (!pushOnly && !pullOnly) {
this.syncHandler = this.localDatabase.sync(db, { checkpoint: "target", ...syncOptionBase });
this.syncHandler
.on("change", async (e) => {
await this.replicationChangeDetected(e, notice, docSentOnStart, docArrivedOnStart, callback);
if (retrying) {
if (this.docSent - docSentOnStart + (this.docArrived - docArrivedOnStart) > this.originalSetting.batch_size * 2) {
// restore configration.
Logger("Back into original settings once.");
if (notice != null) notice.hide();
this.syncHandler = this.cancelHandler(this.syncHandler);
this.openOneshotReplication(this.originalSetting, showResult, callback, false, callbackDone, pushOnly, pullOnly);
}
}
})
.on("complete", (e) => {
this.replicationCompleted(notice, showResult);
if (thisCallback != null) {
thisCallback(true);
}
});
} else if (pullOnly) {
this.syncHandler = this.localDatabase.replicate.to(db, { checkpoint: "target", ...syncOptionBase });
this.syncHandler
.on("change", async (e) => {
await this.replicationChangeDetected({ direction: "pull", change: e }, notice, docSentOnStart, docArrivedOnStart, callback);
if (retrying) {
if (this.docSent - docSentOnStart + (this.docArrived - docArrivedOnStart) > this.originalSetting.batch_size * 2) {
// restore configration.
Logger("Back into original settings once.");
if (notice != null) notice.hide();
this.syncHandler = this.cancelHandler(this.syncHandler);
this.openOneshotReplication(this.originalSetting, showResult, callback, false, callbackDone, pushOnly, pullOnly);
}
}
})
.on("complete", (e) => {
this.replicationCompleted(notice, showResult);
if (thisCallback != null) {
thisCallback(true);
}
});
} else if (pushOnly) {
this.syncHandler = this.localDatabase.replicate.to(db, { checkpoint: "target", ...syncOptionBase });
this.syncHandler.on("complete", (e) => {
this.replicationCompleted(notice, showResult);
if (thisCallback != null) {
thisCallback(true);
}
});
}
this.syncHandler
.on("active", () => this.replicationActivated(notice))
.on("denied", (e) => {
this.replicationDeniend(notice, e);
if (thisCallback != null) {
thisCallback(e);
}
})
.on("error", (e) => {
this.replicationErrored(notice, e);
Logger("Replication stopped.", showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO);
if (notice != null) notice.hide();
if (getLastPostFailedBySize()) {
// Duplicate settings for smaller batch.
const xsetting: RemoteDBSettings = JSON.parse(JSON.stringify(setting));
xsetting.batch_size = Math.ceil(xsetting.batch_size / 2) + 2;
xsetting.batches_limit = Math.ceil(xsetting.batches_limit / 2) + 2;
if (xsetting.batch_size <= 5 && xsetting.batches_limit <= 5) {
Logger("We can't replicate more lower value.", showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO);
} else {
Logger(`Retry with lower batch size:${xsetting.batch_size}/${xsetting.batches_limit}`, showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO);
thisCallback = null;
this.openOneshotReplication(xsetting, showResult, callback, true, callbackDone, pushOnly, pullOnly);
}
} else {
Logger("Replication error", LOG_LEVEL.NOTICE);
Logger(e);
}
if (thisCallback != null) {
thisCallback(e);
}
})
.on("paused", (e) => this.replicationPaused(notice));
}
openContinuousReplication(setting: RemoteDBSettings, showResult: boolean, callback: (e: PouchDB.Core.ExistingDocument<EntryDoc>[]) => Promise<void>, retrying: boolean) {
if (this.syncHandler != null) {
Logger("Replication is already in progress.", showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO);
return;
}
Logger("Before LiveSync, start OneShot once...");
this.openOneshotReplication(
setting,
showResult,
callback,
false,
async () => {
Logger("LiveSync begin...");
const ret = await this.checkReplicationConnectivity(setting, true, true, showResult);
let notice: WrappedNotice = null;
if (ret === false) {
Logger("Could not connect to server.", showResult ? LOG_LEVEL.NOTICE : LOG_LEVEL.INFO);
return;
}
if (showResult) {
notice = NewNotice("Looking for the point last synchronized point.", 0);
}
const { db, syncOption } = ret;
this.syncStatus = "STARTED";
this.updateInfo();
const docArrivedOnStart = this.docArrived;
const docSentOnStart = this.docSent;
if (!retrying) {
//TODO if successfly saven, roll back org setting.
this.originalSetting = setting;
}
this.syncHandler = this.cancelHandler(this.syncHandler);
this.syncHandler = this.localDatabase.sync<EntryDoc>(db, {
...syncOption,
pull: {
checkpoint: "target",
},
push: {
checkpoint: "source",
},
});
this.syncHandler
.on("active", () => this.replicationActivated(notice))
.on("change", async (e) => {
await this.replicationChangeDetected(e, notice, docSentOnStart, docArrivedOnStart, callback);
if (retrying) {
if (this.docSent - docSentOnStart + (this.docArrived - docArrivedOnStart) > this.originalSetting.batch_size * 2) {
// restore sync values
Logger("Back into original settings once.");
if (notice != null) notice.hide();
this.syncHandler = this.cancelHandler(this.syncHandler);
this.openContinuousReplication(this.originalSetting, showResult, callback, false);
}
}
})
.on("complete", (e) => this.replicationCompleted(notice, showResult))
.on("denied", (e) => this.replicationDeniend(notice, e))
.on("error", (e) => {
this.replicationErrored(notice, e);
Logger("Replication stopped.", LOG_LEVEL.NOTICE);
})
.on("paused", (e) => this.replicationPaused(notice));
},
false,
true
);
}
originalSetting: RemoteDBSettings = null;
closeReplication() {
this.syncStatus = "CLOSED";
this.updateInfo();
this.syncHandler = this.cancelHandler(this.syncHandler);
Logger("Replication closed");
}
async resetLocalOldDatabase() {
const oldDB = await this.isOldDatabaseExists();
if (oldDB) {
oldDB.destroy();
NewNotice("Deleted! Please re-launch obsidian.", LOG_LEVEL.NOTICE);
} else {
NewNotice("Old database is not exist.", LOG_LEVEL.NOTICE);
}
}
async resetDatabase() {
await this.waitForGCComplete();
this.changeHandler = this.cancelHandler(this.changeHandler);
await this.closeReplication();
Logger("Database closed for reset Database.");
this.isReady = false;
await this.localDatabase.destroy();
await this.kvDB.destroy();
this.localDatabase = null;
await this.initializeDatabase();
Logger("Local Database Reset", LOG_LEVEL.NOTICE);
}
async tryResetRemoteDatabase(setting: RemoteDBSettings) {
await this.closeReplication();
const con = await connectRemoteCouchDBWithSetting(setting, this.isMobile);
if (typeof con == "string") return;
try {
await con.db.destroy();
Logger("Remote Database Destroyed", LOG_LEVEL.NOTICE);
await this.tryCreateRemoteDatabase(setting);
} catch (ex) {
Logger("Something happened on Remote Database Destory:", LOG_LEVEL.NOTICE);
Logger(ex, LOG_LEVEL.NOTICE);
}
}
async tryCreateRemoteDatabase(setting: RemoteDBSettings) {
await this.closeReplication();
const con2 = await connectRemoteCouchDBWithSetting(setting, this.isMobile);
if (typeof con2 === "string") return;
Logger("Remote Database Created or Connected", LOG_LEVEL.NOTICE);
}
async markRemoteLocked(setting: RemoteDBSettings, locked: boolean) {
const uri = setting.couchDB_URI + (setting.couchDB_DBNAME == "" ? "" : "/" + setting.couchDB_DBNAME);
const dbret = await connectRemoteCouchDBWithSetting(setting, this.isMobile);
if (typeof dbret === "string") {
Logger(`could not connect to ${uri}:${dbret}`, LOG_LEVEL.NOTICE);
return;
}
if (!(await checkRemoteVersion(dbret.db, this.migrate.bind(this), VER))) {
Logger("Remote database is newer or corrupted, make sure to latest version of self-hosted-livesync installed", LOG_LEVEL.NOTICE);
return;
}
const defInitPoint: EntryMilestoneInfo = {
_id: MILSTONE_DOCID,
type: "milestoneinfo",
created: (new Date() as any) / 1,
locked: locked,
accepted_nodes: [this.nodeid],
};
const remoteMilestone: EntryMilestoneInfo = await resolveWithIgnoreKnownError(dbret.db.get(MILSTONE_DOCID), defInitPoint);
remoteMilestone.accepted_nodes = [this.nodeid];
remoteMilestone.locked = locked;
if (locked) {
Logger("Lock remote database to prevent data corruption", LOG_LEVEL.NOTICE);
} else {
Logger("Unlock remote database to prevent data corruption", LOG_LEVEL.NOTICE);
}
await dbret.db.put(remoteMilestone);
}
async markRemoteResolved(setting: RemoteDBSettings) {
const uri = setting.couchDB_URI + (setting.couchDB_DBNAME == "" ? "" : "/" + setting.couchDB_DBNAME);
const dbret = await connectRemoteCouchDBWithSetting(setting, this.isMobile);
if (typeof dbret === "string") {
Logger(`could not connect to ${uri}:${dbret}`, LOG_LEVEL.NOTICE);
return;
}
if (!(await checkRemoteVersion(dbret.db, this.migrate.bind(this), VER))) {
Logger("Remote database is newer or corrupted, make sure to latest version of self-hosted-livesync installed", LOG_LEVEL.NOTICE);
return;
}
const defInitPoint: EntryMilestoneInfo = {
_id: MILSTONE_DOCID,
type: "milestoneinfo",
created: (new Date() as any) / 1,
locked: false,
accepted_nodes: [this.nodeid],
};
// check local database hash status and remote replicate hash status
const remoteMilestone: EntryMilestoneInfo = await resolveWithIgnoreKnownError(dbret.db.get(MILSTONE_DOCID), defInitPoint);
// remoteMilestone.locked = false;
remoteMilestone.accepted_nodes = Array.from(new Set([...remoteMilestone.accepted_nodes, this.nodeid]));
// this.remoteLocked = false;
Logger("Mark this device as 'resolved'.", LOG_LEVEL.NOTICE);
await dbret.db.put(remoteMilestone);
}
gcRunning = false;
async waitForGCComplete() {
while (this.gcRunning) {
Logger("Waiting for Garbage Collection completed.");
await delay(1000);
}
}
async sanCheck(entry: EntryDoc): Promise<boolean> {
if (entry.type == "plain" || entry.type == "newnote") {
const children = entry.children;
Logger(`sancheck:checking:${entry._id} : ${children.length}`, LOG_LEVEL.VERBOSE);
try {
const dc = await this.localDatabase.allDocs({ keys: [...children] });
if (dc.rows.some((e) => "error" in e)) {
this.corruptedEntries[entry._id] = entry;
Logger(`sancheck:corrupted:${entry._id} : ${children.length}`, LOG_LEVEL.VERBOSE);
return false;
}
return true;
} catch (ex) {
Logger(ex);
}
}
return false;
}
async garbageCollect() {
if (this.settings.useHistory) {
Logger("GC skipped for using history", LOG_LEVEL.VERBOSE);
return;
}
if ((this.settings as ObsidianLiveSyncSettings).liveSync) {
Logger("GC skipped while live sync.", LOG_LEVEL.VERBOSE);
return;
}
// NOTE:Garbage collection could break old revisions.
await runWithLock("replicate", true, async () => {
if (this.gcRunning) return;
this.gcRunning = true;
let idbGC: IDBPDatabase<{ id: string }> = null;
const storeIDB = "gc";
const idbname = "idb-" + this.dbname + "-idb-gcx";
try {
const procAllDocs = async (getLeaf: boolean, startkey: string, endkey: string, callback: (idordoc: string[]) => Promise<void>) => {
let c = 0;
let readCount = 0;
do {
const result = await this.localDatabase.allDocs({ include_docs: false, skip: c, limit: 2000, conflicts: !getLeaf, startkey: startkey, endkey: endkey });
readCount = result.rows.length;
if (readCount > 0) {
await callback(result.rows.map((e) => e.id));
}
c += readCount;
} while (readCount != 0);
};
// Delete working indexedDB once.
await deleteDB(idbname);
idbGC = await openDB(idbname, 1, {
upgrade(db) {
db.createObjectStore(storeIDB, { keyPath: "id" });
},
});
// Mark all chunks once.
await procAllDocs(true, "h:", "h_", async (docs) => {
Logger(`Chunks marked - :${docs.length}`);
const tx = idbGC.transaction(storeIDB, "readwrite");
const store = tx.objectStore(storeIDB);
for (const docId of docs) {
await store.put({ id: docId });
}
await tx.done;
});
Logger("All chunks are marked once");
const unmarkUsedByHashId = async (doc: EntryDoc) => {
if ("children" in doc) {
const tx = idbGC.transaction(storeIDB, "readwrite");
const store = tx.objectStore(storeIDB);
for (const hashId of doc.children) {
await store.delete(hashId);
}
await tx.done;
}
};
Logger("Processing existen docs");
let procDocs = 0;
await procAllDocs(false, null, null, async (doc) => {
const docIds = (doc as string[]).filter((e) => !e.startsWith("h:") && !e.startsWith("ps:"));
for (const docId of docIds) {
procDocs++;
if (procDocs % 25 == 0) Logger(`${procDocs} Processed`);
const docT = await this.localDatabase.get(docId, { revs_info: true });
if (docT._deleted) continue;
// Unmark about latest doc.
unmarkUsedByHashId(docT);
const revs = docT._revs_info;
// Unmark old revisions
for (const rev of revs) {
if (rev.status != "available") continue;
const docRev = await this.localDatabase.get(docId, { rev: rev.rev });
unmarkUsedByHashId(docRev);
if (docRev._conflicts) {
// Unmark the conflicted chunks of old revisions.
for (const cid of docRev._conflicts) {
const docConflict = await this.localDatabase.get<EntryDoc>(docId, { rev: cid });
unmarkUsedByHashId(docConflict);
}
}
}
// Unmark the conflicted chunk.
if (docT._conflicts) {
for (const cid of docT._conflicts) {
const docConflict = await this.localDatabase.get<EntryDoc>(docId, { rev: cid });
unmarkUsedByHashId(docConflict);
}
}
}
});
// All marked chunks could be deleted.
Logger("Delete non-used chunks");
let dataLeft = false;
let chunkKeys: string[] = [];
let totalDelCount = 0;
do {
const tx = idbGC.transaction(storeIDB, "readonly");
const store = tx.objectStore(storeIDB);
let cursor = await store.openCursor();
if (cursor == null) break;
const maxconcurrentDocs = 10;
let delChunkCount = 0;
do {
// console.log(cursor.key, cursor.value);
if (cursor) {
chunkKeys.push(cursor.key as string);
delChunkCount++;
dataLeft = true;
} else {
dataLeft = false;
}
cursor = await cursor.continue();
} while (cursor && dataLeft && delChunkCount < maxconcurrentDocs);
// if (chunkKeys.length > 0) {
totalDelCount += delChunkCount;
const delDocResult = await this.localDatabase.allDocs({ keys: chunkKeys, include_docs: true });
const delDocs = delDocResult.rows.map((e) => ({ ...e.doc, _deleted: true }));
await this.localDatabase.bulkDocs(delDocs);
Logger(`deleted from pouchdb:${delDocs.length}`);
const tx2 = idbGC.transaction(storeIDB, "readwrite");
const store2 = tx2.objectStore(storeIDB);
for (const doc of chunkKeys) {
await store2.delete(doc);
}
Logger(`deleted from workspace:${chunkKeys.length}`);
await tx2.done;
// }
chunkKeys = [];
} while (dataLeft);
Logger(`Deleted ${totalDelCount} chunks`);
Logger("Teardown the database");
if (idbGC != null) {
idbGC.close();
idbGC = null;
}
await deleteDB(idbname);
this.gcRunning = false;
Logger("Done");
} catch (ex) {
Logger("Error on garbage collection");
Logger(ex);
} finally {
if (idbGC != null) {
idbGC.close();
}
await deleteDB(idbname);
this.gcRunning = false;
}
});
}
} | the_stack |
import getDropIndex from './getDropIndex';
describe('getDropIndex', () => {
describe('from header to header', () => {
it('should return 0 when there are 3 columns and the second is dragged before the first', () => {
const res = getDropIndex({
dropTarget: 'header',
dragTarget: 'header',
dir: -1,
ranges: [
{ left: 0, right: 100, index: 0 },
{ left: 100, right: 200, index: 1 },
{ left: 200, right: 300, index: 2 },
],
dragRange: { left: 30, right: 130, index: 1 },
}).index;
expect(res).toEqual(0);
});
it('should return correct when there are locked columns', () => {
const res = getDropIndex({
dropTarget: 'header',
dragTarget: 'header',
dir: -1,
ranges: [
{ left: 0, right: 100, index: 0 },
{ left: 100, right: 200, index: 1 },
{ left: 200, right: 300, index: 2 },
],
dragRange: { left: 30, right: 130, index: 1 },
}).index;
expect(res).toEqual(0);
});
it('should return 1 when there are 4 items and the last one is dragged over the first one', () => {
const res = getDropIndex({
dropTarget: 'header',
dragTarget: 'header',
dir: -1,
ranges: [
{ left: 0, right: 100, index: 0 },
{ left: 100, right: 200, index: 1 },
{ left: 200, right: 300, index: 2 },
{ left: 300, right: 400, index: 3 },
],
dragRange: { left: 120, right: 220, index: 3 },
}).index;
expect(res).toEqual(1);
});
it('should return 2 when there are 2 items and dragging the first one to the right', () => {
const res = getDropIndex({
dropTarget: 'header',
dragTarget: 'header',
dir: 1,
ranges: [
{ left: 11, right: 1452, index: 0 },
{ left: 1452, right: 1582, index: 1 },
],
dragRange: { left: 110, right: 1551, index: 0 },
}).index;
expect(res).toEqual(2);
});
it('should return 1 when there are 3 columns and the second is dragged just a bit to the left', () => {
const res = getDropIndex({
dropTarget: 'header',
dragTarget: 'header',
dir: -1,
ranges: [
{ left: 0, right: 100, index: 0 },
{ left: 100, right: 200, index: 1 },
{ left: 200, right: 300, index: 2 },
],
dragRange: { left: 90, right: 190, index: 1 },
}).index;
expect(res).toEqual(1);
});
});
describe('from header to group', () => {
it('should return 2 when there are 2 groupBy and a column is dragged at the end', () => {
const res = getDropIndex({
dropTarget: 'group',
dragTarget: 'header',
dir: -1,
ranges: [
{ left: 0, right: 100, index: 0 },
{ left: 105, right: 205, index: 1 },
],
dragRange: { left: 320, right: 420, index: 6 },
}).index;
expect(res).toEqual(2);
});
it('should return 1 when there are no groupBy and column is dragged', () => {
const res = getDropIndex({
dragTarget: 'header',
dropTarget: 'group',
dir: -1,
ranges: [],
dragRange: { left: 600, right: 700, index: 3 },
}).index;
expect(res).toEqual(0);
});
it('should return 1 when there are 3 groupBy and a column is dragged in between the last 2', () => {
const res = getDropIndex({
dropTarget: 'group',
dragTarget: 'header',
dir: -1,
ranges: [
{ left: 16, right: 91, index: 0 },
{ left: 96, right: 171, index: 1 },
{ left: 176, right: 252, index: 2 },
],
dragRange: { left: 186, right: 636, index: 4 },
}).index;
expect(res).toEqual(2);
});
});
describe('from group to header', () => {
it('should be able to drag the only box from header to the many boxes in header, at position 1', () => {
const res = getDropIndex({
dragTarget: 'group',
dropTarget: 'header',
dir: 1,
ranges: [
{ left: 0, right: 100, index: 0 },
{ left: 100, right: 200, index: 1 },
{ left: 200, right: 300, index: 2 },
{ left: 300, right: 400, index: 3 },
],
dragRange: { left: 60, right: 160, index: 0 },
}).index;
expect(res).toEqual(1);
});
});
describe('from group to group', () => {
it('should return 2 when there are 2 items, and dragging the first one over the second one', () => {
const res = getDropIndex({
dropTarget: 'group',
dragTarget: 'group',
dir: 1,
ranges: [
{ left: 0, right: 100, index: 0 },
{ left: 100, right: 200, index: 1 },
],
dragRange: { left: 80, right: 180, index: 0 },
}).index;
expect(res).toEqual(2);
});
it('should return 3 when there are 3 items, and dragging the first one past the last one', () => {
const res = getDropIndex({
dropTarget: 'group',
dragTarget: 'group',
dir: 1,
ranges: [
{ left: 0, right: 100, index: 0 },
{ left: 100, right: 200, index: 1 },
{ left: 200, right: 300, index: 2 },
],
dragRange: { left: 580, right: 680, index: 0 },
}).index;
expect(res).toEqual(3);
});
it('should return 2 when there are 3 items, and dragging the first over the second one', () => {
const res = getDropIndex({
dropTarget: 'group',
dragTarget: 'group',
dir: 1,
ranges: [
{ left: 0, right: 100, index: 0 },
{ left: 100, right: 200, index: 1 },
{ left: 200, right: 300, index: 2 },
],
dragRange: { left: 60, right: 160, index: 0 },
}).index;
expect(res).toEqual(2);
});
it('should return 0 when there are 3 items, and dragging the first over the first half of the first one', () => {
const res = getDropIndex({
dropTarget: 'group',
dragTarget: 'group',
dir: 1,
ranges: [
{ left: 0, right: 100, index: 0 },
{ left: 100, right: 200, index: 1 },
{ left: 200, right: 300, index: 2 },
],
dragRange: { left: 49, right: 140, index: 0 },
}).index;
expect(res).toEqual(0);
});
it('should return 0 when there are 3 items, and dragging the first over the first half of the first one - more complex scenario', () => {
const ranges = [
{ left: 16, right: 91, index: 0 },
{ left: 96, right: 171, index: 1 },
{ left: 176, right: 252, index: 2 },
];
const res = getDropIndex({
ranges,
dir: 1,
dragTarget: 'group',
dropTarget: 'group',
dragRange: { left: 58, right: 133, index: 0 },
}).index;
expect(res).toEqual(0);
});
it('should return 0 when dragging the first item over itself', () => {
const res = getDropIndex({
dropTarget: 'group',
dragTarget: 'group',
dir: 1,
ranges: [
{ left: 0, right: 100, index: 0 },
{ left: 100, right: 200, index: 1 },
],
dragRange: { left: 8, right: 108, index: 0 },
}).index;
expect(res).toEqual(0);
});
it('should return 2 when there are 3 items and dragging the last to the right', () => {
const res = getDropIndex({
dropTarget: 'group',
dragTarget: 'group',
dir: 1,
ranges: [
{ left: 0, right: 100, index: 0 },
{ left: 100, right: 200, index: 1 },
{ left: 200, right: 300, index: 2 },
],
dragRange: { left: 350, right: 450, index: 2 },
}).index;
expect(res).toEqual(2);
});
it('should return 3 when there are 3 items and dragging the middle one to the right', () => {
const res = getDropIndex({
dropTarget: 'group',
dragTarget: 'group',
dir: 1,
ranges: [
{ left: 0, right: 100, index: 0 },
{ left: 100, right: 200, index: 1 },
{ left: 200, right: 300, index: 2 },
],
dragRange: { left: 350, right: 450, index: 1 },
}).index;
expect(res).toEqual(3);
});
it('should return 0 when there are 3 items and dragging the first to the left', () => {
const res = getDropIndex({
dropTarget: 'group',
dragTarget: 'group',
dir: -1,
ranges: [
{ left: 0, right: 100, index: 0 },
{ left: 100, right: 200, index: 1 },
{ left: 200, right: 300, index: 2 },
],
dragRange: { left: -100, right: 0, index: 0 },
}).index;
expect(res).toEqual(0);
});
});
describe('from header to header, with validPositions', () => {
it(`should return 2 when there are 3 items and dragging the
first one to the right, with only 1 & 2 being valid positions`, () => {
const res = getDropIndex({
dropTarget: 'header',
dragTarget: 'header',
dir: 1,
ranges: [
{ left: 0, right: 100, index: 0 },
{ left: 100, right: 200, index: 1 },
{ left: 200, right: 300, index: 2 },
],
dragRange: { left: 300, right: 400, index: 0 },
validDropPositions: { 0: true, 1: true, 2: true },
}).index;
expect(res).toEqual(2);
});
it(`should return 1 when there are 4 items and dragging the
second one to the right, with only 1 being valid position`, () => {
const res = getDropIndex({
dropTarget: 'header',
dragTarget: 'header',
dir: 1,
ranges: [
{ left: 0, right: 100, index: 0 },
{ left: 100, right: 200, index: 1 },
{ left: 200, right: 300, index: 2 },
{ left: 300, right: 400, index: 3 },
],
dragRange: { left: 400, right: 500, index: 1 },
validDropPositions: { 1: true },
}).index;
expect(res).toEqual(1);
});
it('should return 3 when there are 5 columns, validPositions: 0, 1, 3, 4 and dragging the first one just before the first half of the third one', () => {
const res = getDropIndex({
dropTarget: 'header',
dragTarget: 'header',
dir: 1,
ranges: [
{ left: 0, right: 100, index: 0 },
{ left: 100, right: 200, index: 1 },
{ left: 200, right: 300, index: 2 },
{ left: 300, right: 400, index: 3 },
{ left: 400, right: 500, index: 4 },
],
dragRange: { left: 240, right: 340, index: 0 },
validDropPositions: { 0: true, 1: true, 3: true, 4: true },
}).index;
expect(res).toEqual(3);
});
it('should return 2 when there are 5 columns, validPositions: 0, 2, 4 and dragging the first one just before the first half of the third one', () => {
const res = getDropIndex({
dropTarget: 'header',
dragTarget: 'header',
dir: 1,
ranges: [
{ left: 0, right: 100, index: 0 },
{ left: 100, right: 200, index: 1 },
{ left: 200, right: 300, index: 2 },
{ left: 300, right: 400, index: 3 },
{ left: 400, right: 500, index: 4 },
],
dragRange: { left: 240, right: 340, index: 0 },
validDropPositions: { 0: true, 2: true, 4: true },
}).index;
expect(res).toEqual(2);
});
it('should return 4 when there are 5 columns, validPositions: 0, 1, 3, 4 and dragging the first one after the first half of the third one', () => {
const res = getDropIndex({
dropTarget: 'header',
dragTarget: 'header',
dir: 1,
ranges: [
{ left: 0, right: 100, index: 0 },
{ left: 100, right: 200, index: 1 },
{ left: 200, right: 300, index: 2 },
{ left: 300, right: 400, index: 3 },
{ left: 400, right: 500, index: 4 },
],
dragRange: { left: 360, right: 460, index: 0 },
validDropPositions: { 0: true, 1: true, 3: true, 4: true },
}).index;
expect(res).toEqual(4);
});
});
}); | the_stack |
import http = require("http");
import https = require("https");
import zlib = require("zlib");
import Logging = require("../Library/Logging");
import TelemetryClient = require("../Library/TelemetryClient");
import snippetInjectionHelper = require("../Library/SnippetInjectionHelper");
import Statsbeat = require("./Statsbeat");
import Constants = require("../Declarations/Constants");
import ConnectionStringParser = require("../Library/ConnectionStringParser");
class WebSnippet {
public static INSTANCE: WebSnippet;
private static _snippet: string;
private static _aiUrl: string;
private static _aiDeprecatedUrl: string;
private _isEnabled: boolean;
private _isInitialized: boolean;
private _isIkeyValid: boolean = true;
private _statsbeat: Statsbeat;
constructor(client: TelemetryClient) {
if (!!WebSnippet.INSTANCE) {
throw new Error("Web snippet injection should be configured from the applicationInsights object");
}
WebSnippet.INSTANCE = this;
// AI URL used to validate if snippet already included
WebSnippet._aiUrl = "https://js.monitor.azure.com/scripts/b/ai";
WebSnippet._aiDeprecatedUrl = "https://az416426.vo.msecnd.net/scripts/b/ai";
let clientSnippetConnectionString = client.config.webSnippetConnectionString;
let defaultIkey = client.config.instrumentationKey;
if (!!clientSnippetConnectionString) {
let clientSnippetIkey = this._getWebSnippetIkey(client.config.webSnippetConnectionString);
defaultIkey = clientSnippetIkey;
}
//TODO: quick fix for bundle error, remove this when npm is published
WebSnippet._snippet = snippetInjectionHelper.webSnippet.replace("INSTRUMENTATION_KEY", defaultIkey);
this._statsbeat = client.getStatsbeat();
//TODO: replace the path with npm package exports
//NOTE: should use the following part when npm is enabled
// let snippetPath = path.resolve(__dirname, "../../AutoCollection/snippet/snippet.min.js");
// try {
// fs.readFile(snippetPath, function (err, snippet) {
// if (err) {
// Logging.warn("Failed to load AI Web snippet. Ex:" + err);
// }
// //TODO:should add extra config: snippetInstrumentationKey
// WebSnippet._snippet = snippet.toString().replace("INSTRUMENTATION_KEY", client.config.instrumentationKey);
// });
// } catch (err) {
// Logging.warn("Read snippet error: " + err);
// }
}
public enable(isEnabled: boolean, webSnippetConnectionString?: string ) {
this._isEnabled = isEnabled;
if (!!webSnippetConnectionString) {
let iKey = this._getWebSnippetIkey(webSnippetConnectionString);
WebSnippet._snippet = snippetInjectionHelper.webSnippet.replace("INSTRUMENTATION_KEY", iKey);
}
if (this._isEnabled && !this._isInitialized && this._isIkeyValid) {
if (this._statsbeat) {
this._statsbeat.addFeature(Constants.StatsbeatFeature.WEB_SNIPPET);
}
this._initialize();
} else if (!this._isEnabled) {
if (this._statsbeat) {
this._statsbeat.removeFeature(Constants.StatsbeatFeature.WEB_SNIPPET);
}
}
}
public isInitialized() {
return this._isInitialized;
}
private _getWebSnippetIkey(connectionString: string) {
const csCode = ConnectionStringParser.parse(connectionString);
const iKeyCode = csCode.instrumentationkey || "";
if (!ConnectionStringParser.isIkeyValid(iKeyCode)) {
this._isIkeyValid = false;
Logging.info("Invalid web snippet connection string, web snippet will not be injected.");
}
return iKeyCode;
}
private _initialize() {
this._isInitialized = true;
const originalHttpServer = http.createServer;
const originalHttpsServer = https.createServer;
var isEnabled = this._isEnabled;
http.createServer = (requestListener?: (request: http.IncomingMessage, response: http.ServerResponse) => void) => {
const originalRequestListener = requestListener;
if (originalRequestListener) {
requestListener = (request: http.IncomingMessage, response: http.ServerResponse) => {
// Patch response write method
let originalResponseWrite = response.write;
let isGetRequest = request.method == "GET";
response.write = function wrap(a: Buffer | string, b?: Function | string, c?: Function | string) {
//only patch GET request
try {
if (isEnabled && isGetRequest) {
let headers = snippetInjectionHelper.getContentEncodingFromHeaders(response);
let writeBufferType = undefined;
if (typeof b === "string") {
writeBufferType = b;
}
if (headers === null || headers === undefined) {
if (WebSnippet.INSTANCE.ValidateInjection(response, a)) {
arguments[0] = WebSnippet.INSTANCE.InjectWebSnippet(response, a, undefined, writeBufferType);
}
} else if (headers.length) {
let encodeType = headers[0];
arguments[0] = WebSnippet.INSTANCE.InjectWebSnippet(response, a, encodeType);
}
}
} catch (err) {
Logging.warn("Inject snippet error: "+ err);
}
return originalResponseWrite.apply(response, arguments);
}
// Patch response end method for cases when HTML is added there
let originalResponseEnd = response.end;
response.end = function wrap(a?: Buffer | string | any, b?: Function | string, c?: Function) {
if (isEnabled && isGetRequest) {
try {
if (isEnabled && isGetRequest) {
let headers = snippetInjectionHelper.getContentEncodingFromHeaders(response);
let endBufferType = undefined;
if (typeof b === "string") {
endBufferType = b;
}
if (headers === null || headers === undefined) {
if (WebSnippet.INSTANCE.ValidateInjection(response, a)) {
arguments[0] = WebSnippet.INSTANCE.InjectWebSnippet(response, a, undefined, endBufferType);
}
} else if (headers.length) {
let encodeType = headers[0];
arguments[0] = WebSnippet.INSTANCE.InjectWebSnippet(response, a, encodeType);
}
}
} catch (err) {
Logging.warn("Inject snipet error: "+ err);
}
}
return originalResponseEnd.apply(response, arguments);
}
return originalRequestListener(request, response);
}
}
return originalHttpServer(requestListener);
}
https.createServer = function(options,httpsRequestListener) {
const originalHttpsRequestListener = httpsRequestListener;
if (originalHttpsRequestListener) {
httpsRequestListener = function (req, res) {
let isGetHttpsRequest = req.method == "GET";
let originalHttpsResponseWrite = res.write;
let originalHttpsResponseEnd = res.end;
res.write = function wrap(a: Buffer | string | any, b?:Function | string, c?: Function) {
try {
if (isEnabled && isGetHttpsRequest) {
let headers = snippetInjectionHelper.getContentEncodingFromHeaders(res);
let writeBufferType = undefined;
if (typeof b === "string") {
writeBufferType = b;
}
if (headers === null || headers === undefined) {
if (WebSnippet.INSTANCE.ValidateInjection(res, a)) {
arguments[0] = this.InjectWebSnippet(res, a, undefined, writeBufferType);
}
} else if (headers.length) {
let encodeType = headers[0];
arguments[0] = WebSnippet.INSTANCE.InjectWebSnippet(res, a, encodeType);
}
}
} catch (err) {
Logging.warn("Inject snippet error: "+ err);
}
return originalHttpsResponseWrite.apply(res,arguments);
}
res.end = function wrap(a: Buffer | string | any, b?:Function | string, c?: Function) {
try {
if (isEnabled && isGetHttpsRequest) {
let headers = snippetInjectionHelper.getContentEncodingFromHeaders(res);
let endBufferType = undefined;
if (typeof b === "string") {
endBufferType = b;
}
if (headers === null || headers === undefined) {
if (WebSnippet.INSTANCE.ValidateInjection(res, a)) {
arguments[0] = WebSnippet.INSTANCE.InjectWebSnippet(res, a, undefined, endBufferType);
}
} else if (headers.length) {
let encodeType = headers[0];
arguments[0] = WebSnippet.INSTANCE.InjectWebSnippet(res, a, encodeType);
}
}
} catch (err) {
Logging.warn("Inject snippet error: "+ err);
}
return originalHttpsResponseEnd.apply(res,arguments);
}
return originalHttpsRequestListener(req,res);
}
return originalHttpsServer(options, httpsRequestListener);
}
}
}
/**
* Validate response and try to inject Web snippet
*/
public ValidateInjection(response: http.ServerResponse, input: string | Buffer): boolean {
if (!response || !input || response.statusCode != 200) return false;
let isContentHtml = snippetInjectionHelper.isContentTypeHeaderHtml(response);
if (!isContentHtml) return false;
let inputStr = input.slice().toString();
if (inputStr.indexOf("<head>") >= 0 && inputStr.indexOf("</head>") >= 0) {
// Check if snippet not already present looking for AI Web SDK URL
if (inputStr.indexOf(WebSnippet._aiUrl) < 0 && inputStr.indexOf(WebSnippet._aiDeprecatedUrl) < 0) {
return true;
}
}
return false;
}
/**
* Inject Web snippet
*/
public InjectWebSnippet(response: http.ServerResponse, input: string | Buffer, encodeType?: snippetInjectionHelper.contentEncodingMethod, bufferEncodeType?: string ): string | Buffer {
try {
let isCompressedBuffer = !!encodeType;
if (!isCompressedBuffer) {
let html = input.toString();
let index = html.indexOf("</head>");
if (index < 0) return input;
let newHtml = snippetInjectionHelper.insertSnippetByIndex(index,html,WebSnippet._snippet);
if (typeof input === "string") {
response.removeHeader("Content-Length");
input = newHtml;
response.setHeader("Content-Length", Buffer.byteLength(input));
} else if (Buffer.isBuffer(input)) {
let bufferType = bufferEncodeType? bufferEncodeType:"utf8";
let isValidBufferType = snippetInjectionHelper.isBufferType(input, bufferType);
if (isValidBufferType) {
response.removeHeader("Content-Length");
let encodedString = Buffer.from(newHtml).toString(bufferType);
input = Buffer.from(encodedString,bufferType);
response.setHeader("Content-Length", input.length);
}
}
} else {
response.removeHeader("Content-Length");
input = this._getInjectedCompressBuffer(response,input as Buffer,encodeType);
response.setHeader("Content-Length", input.length);
}
}
catch (ex) {
Logging.warn("Failed to inject web snippet and change content-lenght headers. Exception:" + ex);
}
return input;
}
//***********************
// should NOT use sync functions here. But currently cannot get async functions to work
// because reponse.write return boolean
// and also this function do not support partial compression as well
// need more investigation
private _getInjectedCompressBuffer(response: http.ServerResponse, input: Buffer, encodeType: snippetInjectionHelper.contentEncodingMethod): Buffer {
switch (encodeType) {
case snippetInjectionHelper.contentEncodingMethod.GZIP:
let gunzipBuffer = zlib.gunzipSync(input);
if (this.ValidateInjection(response,gunzipBuffer)) {
let injectedGunzipBuffer = this.InjectWebSnippet(response, gunzipBuffer);
input = zlib.gzipSync(injectedGunzipBuffer);
}
break;
case snippetInjectionHelper.contentEncodingMethod.DEFLATE:
let inflateBuffer = zlib.inflateSync(input);
if (this.ValidateInjection(response,inflateBuffer)) {
let injectedInflateBuffer = this.InjectWebSnippet(response, inflateBuffer);
input = zlib.deflateSync(injectedInflateBuffer);
}
break;
case snippetInjectionHelper.contentEncodingMethod.BR:
let BrotliDecompressSync = snippetInjectionHelper.getBrotliDecompressSync(zlib);
let BrotliCompressSync = snippetInjectionHelper.getBrotliCompressSync(zlib);
if (BrotliDecompressSync && BrotliCompressSync) {
let decompressBuffer = BrotliDecompressSync(input);
if (this.ValidateInjection(response,decompressBuffer)) {
let injectedDecompressBuffer = this.InjectWebSnippet(response, decompressBuffer);
input = BrotliCompressSync(injectedDecompressBuffer);
}
break;
}
}
return input;
}
public dispose() {
WebSnippet.INSTANCE = null;
this.enable(false);
this._isInitialized = false;
}
}
export = WebSnippet; | the_stack |
import { StackFrame } from 'vscode-debugadapter';
import { ApexVariableContainer } from '../adapter/apexReplayDebug';
import {
ApexExecutionOverlayResultCommandSuccess,
HeapDumpExtents,
HeapDumpExtentValue
} from '../commands/apexExecutionOverlayResultCommand';
import {
ADDRESS_PREFIX,
APEX_PRIMITIVE_STRING,
EXTENT_TRIGGER_PREFIX,
KEY_VALUE_PAIR,
KEY_VALUE_PAIR_KEY,
KEY_VALUE_PAIR_VALUE,
LC_APEX_PRIMITIVE_BLOB,
LC_APEX_PRIMITIVE_BOOLEAN,
LC_APEX_PRIMITIVE_DATE,
LC_APEX_PRIMITIVE_DATETIME,
LC_APEX_PRIMITIVE_DECIMAL,
LC_APEX_PRIMITIVE_DOUBLE,
LC_APEX_PRIMITIVE_ID,
LC_APEX_PRIMITIVE_INTEGER,
LC_APEX_PRIMITIVE_LONG,
LC_APEX_PRIMITIVE_STRING,
LC_APEX_PRIMITIVE_TIME
} from '../constants';
import { LogContext } from './logContext';
export class HeapDumpService {
private logContext: LogContext;
public constructor(logContext: LogContext) {
this.logContext = logContext;
}
public replaceVariablesWithHeapDump(): void {
const topFrame = this.logContext.getTopFrame();
if (topFrame) {
this.replaceFrameVariablesWithHeapDump(topFrame);
}
}
public replaceFrameVariablesWithHeapDump(frame: StackFrame): void {
const heapdump = this.logContext.getHeapDumpForThisLocation(
frame.name,
frame.line
);
if (heapdump && heapdump.getOverlaySuccessResult()) {
const heapdumpResult = heapdump.getOverlaySuccessResult()!;
const frameInfo = this.logContext.getFrameHandler().get(frame.id);
// There should be an order here for processing the heap dumps
// 1. Process any Strings
// 2. Process any leaf references - leaf references are everything that's not a primitive type
// Once the leaf references are set then anything else, even items with nested references,
// should be able to be pieced together.
// 3. Process any variables for local, static and global scopes. With all of the leaf references
// from the extent in the ref list more complex items (ie collections of references) can be
// pieced together. For existing variables and variableRefs, clean out everything and rebuild
// the variables from scratch. The reason for this is that existing variables may or may not
// have their type information set correctly (ie. collections). Further, any variable handler
// references should really be recreated.
// Clear out the ref's map
this.logContext.getRefsMap().clear();
// Clear out the variableHandler
this.logContext.getVariableHandler().reset();
// Add the strings to the ref map. Strings are going to be in their own extent entry.
// With the strings in the ref map, when creating the leaf references, their values can be
// pulled during leaf creation.
this.createStringRefsFromHeapdump(heapdumpResult);
// Create the high level references
for (const outerExtent of heapdumpResult.HeapDump.extents) {
// Ignore primitiveTypes (includes strings)
if (!this.isPrimitiveType(outerExtent.typeName)) {
for (const innerExtent of outerExtent.extent) {
const ref = innerExtent.address;
const refContainer = new ApexVariableContainer(
'',
'',
outerExtent.typeName,
ref
);
this.updateLeafReferenceContainer(
refContainer,
innerExtent,
outerExtent.collectionType
);
// add the leaf to the ref's map
this.logContext.getRefsMap().set(ref, refContainer);
}
}
}
// At this point all the leaf references are collected and any variable should
// be able to be built from the leaves.
for (const outerExtent of heapdumpResult.HeapDump.extents) {
for (const innerExtent of outerExtent.extent) {
const symbolName =
innerExtent.symbols && innerExtent.symbols.length > 0
? innerExtent.symbols[0]
: undefined;
const className = symbolName
? this.logContext.getUtil().substringUpToLastPeriod(symbolName)
: undefined;
if (symbolName && frameInfo.locals.has(symbolName)) {
const localVar = frameInfo.locals.get(
symbolName
) as ApexVariableContainer;
// Ensure the typename is set correctly.
localVar.type = outerExtent.typeName;
// If the variable is a reference then create a new, updated variable
// from the reference and toss away the old one. The reason for this
// is that we really don't know the state/status of any of the variable's
// children and the same applies to the variablesRef which is necessary
// to expand the variable in variables window.
const refVar = this.logContext
.getRefsMap()
.get(innerExtent.address);
if (refVar) {
if (refVar.type === LC_APEX_PRIMITIVE_STRING) {
localVar.value = refVar.value;
} else {
const updatedVariable = this.createVariableFromReference(
symbolName,
refVar,
new Map<string, null>(),
new Array<ApexVariableContainer>()
);
if (updatedVariable) {
frameInfo.locals.set(localVar.name, updatedVariable);
}
}
// If the variable isn't a reference then it's just a single value
} else {
localVar.value = this.createStringFromExtentValue(
innerExtent.value.value
);
}
} else if (
symbolName &&
className &&
this.logContext.getStaticVariablesClassMap().has(className)
) {
const statics = this.logContext
.getStaticVariablesClassMap()
.get(className);
const staticVarName = this.logContext
.getUtil()
.substringFromLastPeriod(symbolName);
if (statics && statics.has(staticVarName)) {
const staticVar = statics.get(
staticVarName
) as ApexVariableContainer;
staticVar.type = outerExtent.typeName;
const refVar = this.logContext
.getRefsMap()
.get(innerExtent.address);
if (refVar) {
if (refVar.type === LC_APEX_PRIMITIVE_STRING) {
staticVar.value = refVar.value;
} else {
const updatedVariable = this.createVariableFromReference(
symbolName,
refVar,
new Map<string, null>(),
new Array<ApexVariableContainer>()
);
if (updatedVariable) {
statics.set(staticVar.name, updatedVariable);
}
}
// If the variable isn't a reference then it's just a single value
} else {
staticVar.value = this.createStringFromExtentValue(
innerExtent.value.value
);
}
}
}
}
}
// Create the trigger context variables in the global context. Unlike locals or statics
// the global variable container should be empty and these variables are created from
// scratch instead of updating existing variables.
if (this.logContext.isRunningApexTrigger()) {
for (const outerExtent of heapdumpResult.HeapDump.extents) {
if (this.isTriggerExtent(outerExtent)) {
// The trigger context variables are going to be immediate children of the outerExtent.
for (const innerExtent of outerExtent.extent) {
// All of the symbols are going to start with the trigger prefix and will be exclusive
// to trigger context varables. It's worth noting that any local variables or statics
// within the triggger will be under "this" and won't get picked up there.
if (innerExtent.symbols && innerExtent.symbols.length > 0) {
for (const symName of innerExtent.symbols) {
if (symName && symName.startsWith(EXTENT_TRIGGER_PREFIX)) {
const refVar = this.logContext
.getRefsMap()
.get(innerExtent.address);
if (refVar) {
const updatedVariable = this.createVariableFromReference(
symName,
refVar,
new Map<string, null>(),
new Array<ApexVariableContainer>()
);
if (updatedVariable) {
frameInfo.globals.set(symName, updatedVariable);
}
// If the variable isn't a reference then it's just a single value, create
// the variable and add it to the globals list
} else {
frameInfo.globals.set(
symName,
new ApexVariableContainer(
symName,
this.createStringFromExtentValue(
innerExtent.value.value
),
outerExtent.typeName
)
);
}
}
}
}
}
}
}
}
}
}
// If the extent has strings in it there will be an entry of "typeName": "String".
// Add those those to reference list before processing any other references. The
// reason for this is that it allows strings to be treated as values instead of
// child references
public createStringRefsFromHeapdump(
heapdump: ApexExecutionOverlayResultCommandSuccess
): void {
const refsMap = this.logContext.getRefsMap();
for (const outerExtent of heapdump.HeapDump.extents) {
if (outerExtent.typeName.toLowerCase() !== LC_APEX_PRIMITIVE_STRING) {
continue;
}
for (const innerExtent of outerExtent.extent) {
// If there's already a value for the string's address then update it with the extent's
// entry data
if (!refsMap.has(innerExtent.address)) {
refsMap.set(
innerExtent.address,
new ApexVariableContainer(
'',
innerExtent.value.value,
APEX_PRIMITIVE_STRING,
innerExtent.address
)
);
}
const refVar = refsMap.get(
innerExtent.address
) as ApexVariableContainer;
refVar.type = APEX_PRIMITIVE_STRING;
refVar.value = `'${innerExtent.value.value}'`;
}
}
}
public isAddress(value: any): boolean {
return (
typeof value === 'string' && (value as string).startsWith(ADDRESS_PREFIX)
);
}
public isTriggerExtent(outerExtent: HeapDumpExtents) {
if (
(outerExtent.typeName.toLowerCase() === LC_APEX_PRIMITIVE_BOOLEAN ||
this.isCollectionType(outerExtent.typeName)) &&
(outerExtent.count > 0 &&
outerExtent.extent[0].symbols !== null &&
outerExtent.extent[0].symbols!.length > 0 &&
outerExtent.extent[0].symbols![0].startsWith(EXTENT_TRIGGER_PREFIX))
) {
return true;
}
return false;
}
// This is where a reference turns into a variable. The refContainer is
// cloned into a new variable that has a variable name.
private copyReferenceContainer(
refContainer: ApexVariableContainer,
varName: string,
createVarRef = true
) {
const tmpContainer = new ApexVariableContainer(
varName,
refContainer.value,
refContainer.type,
refContainer.ref
);
tmpContainer.variables = refContainer.variables;
// If this isn't a primitive type then it needs to have its variableRef
// set so it can be expanded in the variables window. Note this check
// is kind of superfluous but it's better to be safe than sorry
if (!this.isPrimitiveType(tmpContainer.type)) {
if (createVarRef) {
tmpContainer.variablesRef = this.logContext
.getVariableHandler()
.create(tmpContainer);
} else {
// If the variable is being cloned for a name change then
// it needs to use the same variablesRef as the parent
tmpContainer.variablesRef = refContainer.variablesRef;
}
}
return tmpContainer;
}
// The way the variables are displayed in the variable's window is <varName>:<value>
// and the value is basically a 'toString' of the variable. This is easy enough for
// primitive types but for things like collections it ends up being something like
// MyStrList: ('1','2','3') which when expanded looks like
// MyStrList: ('1','2','3')
// 0: '1'
// 1: '2'
// 2: '3'
private createStringFromVarContainer(
varContainer: ApexVariableContainer,
visitedSet: Set<string>
): string {
// If the varContainer isn't a reference or is a string references
if (
!varContainer.ref ||
varContainer.type.toLowerCase() === LC_APEX_PRIMITIVE_STRING
) {
return varContainer.value;
}
// If the varContainer is a ref and it's already been visited then return the string
if (varContainer.ref) {
if (visitedSet.has(varContainer.ref)) {
return 'already output';
} else {
visitedSet.add(varContainer.ref);
}
}
let returnString = '';
try {
// For a list or set the name string is going to end up being (<val1>,...<valX)
// For a objects, the name string is going to end up being <TypeName>: {<Name1>=<Value1>,...<NameX>=<ValueX>}
const isListOrSet =
varContainer.type.toLowerCase().startsWith('list<') ||
varContainer.type.toLowerCase().startsWith('set<');
// The live debugger, for collections, doesn't include their type in variable name/value
const containerType = this.isCollectionType(varContainer.type)
? ''
: `${varContainer.type}:`;
returnString = isListOrSet ? '(' : `${containerType}{`;
let first = true;
// Loop through each of the container's variables to get the name/value combinations, calling to create
// the string if another collection is found.
for (const entry of Array.from(varContainer.variables.entries())) {
const valueAsApexVar = entry[1] as ApexVariableContainer;
if (!first) {
returnString += ', ';
}
if (valueAsApexVar.ref) {
// if this is also a ref then create the string from that
returnString += this.createStringFromVarContainer(
valueAsApexVar,
visitedSet
);
} else {
// otherwise get the name/value from the variable
returnString += isListOrSet
? valueAsApexVar.value
: `${valueAsApexVar.name}=${valueAsApexVar.value}`;
}
first = false;
}
returnString += isListOrSet ? ')' : '}';
} finally {
if (varContainer.ref) {
visitedSet.delete(varContainer.ref);
}
}
return returnString;
}
private isPrimitiveType(typeName: string): boolean {
const lcTypeName = typeName.toLocaleLowerCase();
if (
lcTypeName === LC_APEX_PRIMITIVE_BLOB ||
lcTypeName === LC_APEX_PRIMITIVE_BOOLEAN ||
lcTypeName === LC_APEX_PRIMITIVE_DATE ||
lcTypeName === LC_APEX_PRIMITIVE_DATETIME ||
lcTypeName === LC_APEX_PRIMITIVE_DECIMAL ||
lcTypeName === LC_APEX_PRIMITIVE_DOUBLE ||
lcTypeName === LC_APEX_PRIMITIVE_ID ||
lcTypeName === LC_APEX_PRIMITIVE_INTEGER ||
lcTypeName === LC_APEX_PRIMITIVE_LONG ||
lcTypeName === LC_APEX_PRIMITIVE_STRING ||
lcTypeName === LC_APEX_PRIMITIVE_TIME
) {
return true;
}
return false;
}
private isCollectionType(typeName: string): boolean {
return (
typeName.toLocaleLowerCase().startsWith('map<') ||
typeName.toLocaleLowerCase().startsWith('list<') ||
typeName.toLocaleLowerCase().startsWith('set<')
);
}
// Update the leaf reference which means do not follow any reference chain. Just update
// what is immediately on the reference.
// refContainer: ApexVariableContainer - the container to the reference being updated
// extentValue: HeapDumpExtentValue - the extent that contains the information/values for the ref
// collectionType - the type of the value (for lists/maps), not the type of key.
// Of note: when creating these leaf references there are values that will be detected as addresses
// by the isAddress function. These will get sorted out when we're creating the variable from the reference.
// At that time, when we try to get the reference and it doesn't exist then the value will be set and the
// the ref field on the variable cleared.
public updateLeafReferenceContainer(
refContainer: ApexVariableContainer,
extentValue: HeapDumpExtentValue,
collectionType: string | null
) {
// The collection type in the extent is either set or null. The ApexVariableContainer doesn't
// allow null for the type, if the type isn't set or is null then default it to the empty string
let valueCollectionType = '';
if (collectionType) {
valueCollectionType = collectionType;
}
let hasInnerRefs = false;
// If the typename is a collection
if (this.isCollectionType(refContainer.type)) {
// the collection is a map
if (extentValue.value.entry) {
let entryNumber = 0;
// get the map's key type and ensure key variables have their type set correctly
const mapKeyType = this.getKeyTypeForMap(
refContainer.type,
collectionType ? collectionType : ''
);
for (const extentValueEntry of extentValue.value.entry) {
let keyIsRef = this.isAddress(extentValueEntry.keyDisplayValue);
let valueIsRef = this.isAddress(extentValueEntry.value.value);
const keyValueName = `${KEY_VALUE_PAIR_KEY}${entryNumber.toString()}_${KEY_VALUE_PAIR_VALUE}${entryNumber.toString()}`;
const keyValueContainer = new ApexVariableContainer(
keyValueName,
'',
KEY_VALUE_PAIR
);
// create the key variable, ensure the key's type is set
const keyContainer = new ApexVariableContainer(
KEY_VALUE_PAIR_KEY,
'',
mapKeyType
);
if (keyIsRef) {
const keyRef = this.logContext
.getRefsMap()
.get(extentValueEntry.keyDisplayValue);
if (
keyRef &&
keyRef.type.toLowerCase() === LC_APEX_PRIMITIVE_STRING
) {
keyIsRef = false;
keyContainer.value = keyRef.value;
} else {
hasInnerRefs = true;
keyContainer.ref = extentValueEntry.keyDisplayValue;
}
} else {
keyContainer.value = extentValueEntry.keyDisplayValue.toString();
}
const valContainer = new ApexVariableContainer(
KEY_VALUE_PAIR_VALUE,
'',
valueCollectionType
);
if (valueIsRef) {
const valueRef = this.logContext
.getRefsMap()
.get(extentValueEntry.value.value);
if (
valueRef &&
valueRef.type.toLowerCase() === LC_APEX_PRIMITIVE_STRING
) {
valueIsRef = false;
valContainer.value = valueRef.value;
} else {
hasInnerRefs = true;
valContainer.ref = extentValueEntry.value.value;
}
} else {
valContainer.value = this.createStringFromExtentValue(
extentValueEntry.value.value
);
}
keyValueContainer.variables.set(keyContainer.name, keyContainer);
keyValueContainer.variables.set(valContainer.name, valContainer);
// If neither the key nor the value are references then update the
// key's string name and set the value
if (!keyIsRef && !valueIsRef) {
keyValueContainer.name = keyContainer.value;
keyValueContainer.value = valContainer.value;
}
// Add the key/value pair to the map
refContainer.variables.set(keyValueName, keyValueContainer);
entryNumber++;
}
// If the extentValue.value.entry doesn't exist then the collection is
// an list/set
} else {
const values = extentValue.value.value as any[];
for (let i = 0; i < values.length; i++) {
// If the value is an address that means that this is a reference
if (this.isAddress(values[i].value)) {
let valString = values[i].value;
const valRef = this.logContext.getRefsMap().get(values[i].value);
if (
valRef &&
valRef.type.toLowerCase() === LC_APEX_PRIMITIVE_STRING
) {
valString = valRef.value;
} else {
hasInnerRefs = true;
}
refContainer.variables.set(
i.toString(),
new ApexVariableContainer(
i.toString(),
valString,
valueCollectionType,
values[i].value
)
);
} else {
refContainer.variables.set(
i.toString(),
new ApexVariableContainer(
i.toString(),
this.createStringFromExtentValue(values[i].value),
valueCollectionType
)
);
}
}
}
// If the extent isn't for a collection then it's just an object reference
// collect the keyDisplayValue/value pairs. The keys, in this case, should
// not be references, they should be straight up strings for the member names.
// The values, on the other hand, could be references
} else {
for (const extentValueEntry of extentValue.value.entry) {
const valueIsRef = this.isAddress(extentValueEntry.value.value);
if (valueIsRef) {
let valString = extentValueEntry.value.value;
const valRef = this.logContext
.getRefsMap()
.get(extentValueEntry.value.value);
if (
valRef &&
valRef.type.toLowerCase() === LC_APEX_PRIMITIVE_STRING
) {
valString = valRef.value;
} else {
hasInnerRefs = true;
}
refContainer.variables.set(
extentValueEntry.keyDisplayValue,
new ApexVariableContainer(
extentValueEntry.keyDisplayValue,
valString,
'',
extentValueEntry.value.value
)
);
} else {
refContainer.variables.set(
extentValueEntry.keyDisplayValue,
new ApexVariableContainer(
extentValueEntry.keyDisplayValue,
this.createStringFromExtentValue(extentValueEntry.value.value),
''
)
);
}
}
}
// If the reference doesn't contain any child references then it's value can set here.
if (!hasInnerRefs) {
refContainer.value = this.createStringFromVarContainer(
refContainer,
new Set<string>()
);
}
}
public createStringFromExtentValue(value: any): string {
// can't toString undefined or null
if (value === undefined) {
return 'undefined';
} else if (value === null) {
return 'null';
}
return value.toString();
}
// When this is invoked, the leaf references have all been set and it is now time to
// create the variable, piecing it together from any references.
// The visitedMap is used to prevent circular lookups. Note: We don't actually
// care what the value is, we just care about the key.
public createVariableFromReference(
varName: string,
refVariable: ApexVariableContainer,
visitedMap: Map<string, ApexVariableContainer | null>,
updateAfterVarCreation: ApexVariableContainer[]
): ApexVariableContainer | undefined {
// if this isn't a reference?
if (!refVariable.ref) {
return undefined;
}
// If this reference has already been seen, then there's
// a good chance that the variable is still being created
// and we can't reset set the value now.
if (visitedMap.has(refVariable.ref)) {
const visitedVar = visitedMap.get(
refVariable.ref
) as ApexVariableContainer;
if (visitedVar !== null) {
if (visitedVar.name !== varName) {
const updatedNameVarContainer = this.copyReferenceContainer(
visitedVar,
varName,
false
);
updateAfterVarCreation.push(updatedNameVarContainer);
return updatedNameVarContainer;
} else {
return visitedVar;
}
}
return undefined;
}
try {
// First, clone the reference into the named variable
const namedVarContainer = this.copyReferenceContainer(
refVariable,
varName
);
// Create the visitedMap entry with what will be the actual
// variable.
visitedMap.set(refVariable.ref, namedVarContainer);
// If the value hasn't been set yet, then we have to walk through all of the children and update
// any child references on the variable with a recursive call
for (const entry of Array.from(namedVarContainer.variables.entries())) {
const childVarName = entry[0];
const childVarContainer = entry[1] as ApexVariableContainer;
// If the type is KEY_VALUE_PAIR then the name/vavlue of the container are will
// need to get updated if either of them are references. Further, the child container
// is going to need to have it's variablesRef set so it'll expand correctly. There will
// be exactly two immediate children in it's variables, one named 'key' and one named
// 'value'
if (childVarContainer.type === KEY_VALUE_PAIR) {
// process the key
const keyVarContainer = childVarContainer.variables.get(
KEY_VALUE_PAIR_KEY
) as ApexVariableContainer;
let keyName = keyVarContainer!.value;
if (keyVarContainer && keyVarContainer.ref) {
const keyRef = this.logContext
.getRefsMap()
.get(keyVarContainer.ref);
if (keyRef) {
const updatedKeyVarContainer = this.createVariableFromReference(
KEY_VALUE_PAIR_KEY,
keyRef!,
visitedMap,
updateAfterVarCreation
);
if (updatedKeyVarContainer) {
keyName = updatedKeyVarContainer.value;
childVarContainer.variables.set(
KEY_VALUE_PAIR_KEY,
updatedKeyVarContainer
);
}
// The value happened to match our pattern for an address but isn't in the references list.
// Set the value to the ref value and clear the ref.
} else {
keyVarContainer.value = keyVarContainer.ref;
keyVarContainer.ref = undefined;
}
}
// process the value
const valueVarContainer = childVarContainer.variables.get(
KEY_VALUE_PAIR_VALUE
) as ApexVariableContainer;
let valueVal = valueVarContainer!.value;
if (valueVarContainer && valueVarContainer.ref) {
const valueRef = this.logContext
.getRefsMap()
.get(valueVarContainer.ref);
if (valueRef) {
const updatedValueVarContainer = this.createVariableFromReference(
KEY_VALUE_PAIR_VALUE,
valueRef!,
visitedMap,
updateAfterVarCreation
);
if (updatedValueVarContainer) {
valueVal = updatedValueVarContainer.value;
childVarContainer.variables.set(
KEY_VALUE_PAIR_VALUE,
updatedValueVarContainer
);
}
// The value happened to match our pattern for an address but isn't in the references list.
// Set the value to the ref value and clear the ref.
} else {
valueVarContainer.value = valueVarContainer.ref;
valueVarContainer.ref = undefined;
}
}
// get the name/value of this entity which will end up being from the values of
// the key/value pair
childVarContainer.name = keyName;
childVarContainer.value = valueVal;
// the key/value entries
childVarContainer.variablesRef = this.logContext
.getVariableHandler()
.create(childVarContainer);
} else {
// If the child isn't a reference then continue
if (!childVarContainer.ref) {
continue;
}
// At this point a recursive call needs to be made to process this child variable
const childVarRefContainer = this.logContext
.getRefsMap()
.get(childVarContainer.ref!);
// The childVarRefContainer can be undefined. If this is the case then the
// variable's value just happened to match the pattern for an address.
if (childVarRefContainer) {
const updatedChildContainer = this.createVariableFromReference(
childVarName,
childVarRefContainer!,
visitedMap,
updateAfterVarCreation
);
// update the child variable in the map
if (updatedChildContainer) {
namedVarContainer.variables.set(
childVarName,
updatedChildContainer
);
}
// The value happened to match our pattern for an address but isn't in the references list.
// Set the value to the ref value and clear the ref.
} else {
childVarContainer.value = childVarContainer.ref;
childVarContainer.ref = undefined;
}
}
namedVarContainer.value = this.createStringFromVarContainer(
namedVarContainer,
new Set<string>()
);
}
return namedVarContainer;
} finally {
// Ensure the current reference is removed from the visited map
visitedMap.delete(refVariable.ref);
// If the visited map is empty that means the variable is done being hooked up
// If there are any items in the updateAfterVarCreation array then now is the
// time to update them
if (visitedMap.size === 0) {
updateAfterVarCreation.forEach(element => {
const varContainer = element as ApexVariableContainer;
varContainer.value = this.createStringFromVarContainer(
varContainer,
new Set<string>()
);
});
}
}
}
// The typename can contain a bunch of nested types. If this is a collection of
// collections then the collectionType won't be null.
// typeName: the full typeName of the Map
// collectionType: the typeName of the Map's value. This is necessary to in order to ensure
// that when the type name is split that it's split correctly since, due to
// potential nesting just splitting on the comma isn't good enough.
private getKeyTypeForMap(typeName: string, collectionType: string): string {
const lastIndexOfValue = ',' + collectionType;
const keyTypeName = typeName.substring(
typeName.indexOf('<') + 1,
typeName.lastIndexOf(lastIndexOfValue)
);
return keyTypeName;
}
} | the_stack |
declare module 'regular-table' {
// only need the @types/react pkg for this, not the runtime react pkg
import { DetailedHTMLProps, HTMLAttributes } from "react";
//// START: index.d.ts
/**
* The `<regular-table>` custom element.
*
* This module has no exports, but importing it has a side effect: the
* `RegularTableElement` class is registered as a custom element, after which
* it can be used as a standard DOM element.
*
* The documentation in this module defines the instance structure of a
* `<regular-table>` DOM object instantiated typically, through HTML or any
* relevent DOM method e.g. `document.createElement("perspective-viewer")` or
* `document.getElementsByTagName("perspective-viewer")`.
*
* @public
* @extends HTMLElement
*/
export class RegularTableElement extends HTMLElement {
/**
* For internal use by the Custom Elements API: "Invoked each time the
* custom element is appended into a document-connected element".
* Ref: https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements#Using_the_lifecycle_callbacks
*
* @internal
* @private
* @memberof RegularTableElement
*/
private connectedCallback;
/** @private */
private _column_sizes;
/** @private */
private _initialized;
/** @private */
private _style_callbacks;
/** @public @type {TableModel} */
public table_model: TableModel;
/**
* Reset the viewport of this regular table.
*
* @internal
* @private
* @memberof RegularTableElement
*/
private _reset_viewport;
/** @private @type {number} */
private _start_row;
/** @private @type {number} */
private _end_row;
/** @private @type {number} */
private _start_col;
/** @private @type {number} */
private _end_col;
/**
* Reset the scroll position of this regular table back to the origin.
*
* @internal
* @private
* @memberof RegularTableElement
*/
private _reset_scroll;
/**
* Reset column autosizing, such that column sizes will be recalculated
* on the next draw() call.
*
* @internal
* @protected
* @memberof RegularTableElement
*/
protected _resetAutoSize(): void;
/**
* Clears the current renderer `<table>`.
*
* @public
* @memberof RegularTableElement
*/
public clear(): void;
/**
* Adds a style listener callback. The style listeners are called
* whenever the <table> is re-rendered, such as through API invocations
* of draw() and user-initiated events such as scrolling. Within this
* optionally async callback, you can select <td>, <th>, etc. elements
* via regular DOM API methods like querySelectorAll().
*
* Example:
* const unsubscribe = table.addStyleListener(() => {
* for (const td of table.querySelectorAll("td")) {
* td.setAttribute("contenteditable", true);
* }
* });
*
* setTimeout(() => {
* unsubscribe();
* }, 1000);
* @public
* @memberof RegularTableElement
* @param {function({detail: RegularTableElement}): void} styleListener - A
* (possibly async) function that styles the inner <table>.
* @returns {function(): void} A function to remove this style listener.
*/
public addStyleListener(styleListener: (arg0: {
detail: RegularTableElement;
}) => void): () => void;
/**
* When called within the execution scope of a function registered to this
* `<regular-table>` as a `StyleListener`, invalidate this draw's
* dimensions and attempt to draw more columns. Useful if your
* `StyleListener` changes a cells dimensions, otherwise `<regular-table>`
* may not draw enough columns to fill the screen.
*
* @public
* @memberof RegularTableElement
*/
public invalidate(): void;
/** @private */
private _invalidated;
/**
* Returns the `MetaData` object associated with a `<td>` or `<th>`. When
* your `StyleListener` is invoked, use this method to look up additional
* `MetaData` about any `HTMLTableCellElement` in the rendered `<table>`.
*
* Example:
* const elems = document.querySelector("td:last-child td:last_child");
* const metadata = table.getMeta(elems);
* console.log(`Viewport corner is ${metadata.x}, ${metadata.y}`);
*
* const header = table.getMeta({row_header_x: 1, y: 3}).row_header;
* @public
* @memberof RegularTableElement
* @param {HTMLTableCellElement|Partial<MetaData>} element - The child element
* of this `<regular-table>` for which to look up metadata, or a
* coordinates-like object to refer to metadata by logical position.
* @returns {MetaData} The metadata associated with the element.
*/
public getMeta(element: HTMLTableCellElement | Partial<MetaData>): MetaData;
/**
* Get performance statistics about this `<regular-table>`. Calling this
* method resets the internal state, which makes it convenient to measure
* performance at regular intervals (see example).
*
* Example:
* const table = document.getElementById("my_regular_table");
* setInterval(() => {
* const {real_fps} = table.getDrawFPS();
* console.log(`Measured ${fps} fps`)
* });
* @public
* @memberof RegularTableElement
* @returns {Performance} Performance data aggregated since the last
* call to `getDrawFPS()`.
*/
public getDrawFPS(): Performance;
/**
* Call this method to set the `scrollLeft` and `scrollTop` for this
* `<regular-table>` by calculating the position of this `scrollLeft`
* and `scrollTop` relative to the underlying widths of its columns
* and heights of its rows.
*
* Example:
* table.scrollToCell(1, 3, 10, 30);
* @public
* @memberof RegularTableElement
* @param {number} x - The left most `x` index column to scroll into view.
* @param {number} y - The top most `y` index row to scroll into view.
* @param {number} ncols - Total number of columns in the data model.
* @param {number} nrows - Total number of rows in the data model.
*/
public scrollToCell(x: number, y: number, ncols: number, nrows: number): Promise<void>;
/**
* Call this method to set `DataListener` for this `<regular-table>`,
* which will be called whenever a new data slice is needed to render.
* Calls to `draw()` will fail if no `DataListener` has been set
*
* Example:
* table.setDataListener((x0, y0, x1, y1) => {
* return {
* num_rows: num_rows = DATA[0].length,
* num_columns: DATA.length,
* data: DATA.slice(x0, x1).map(col => col.slice(y0, y1))
* };
* })
* @public
* @memberof RegularTableElement
* @param {DataListener} dataListener
* `dataListener` is called by to request a rectangular section of data
* for a virtual viewport, (x0, y0, x1, y1), and returns a `DataReponse`
* object.
* @param {Object} options
* @param {("both"|"horizontal"|"vertical"|"none")} options.virtual_mode
* The `virtual_mode` options flag may be one of "both", "horizontal",
* "vertical", or "none" indicating which dimensions of the table should be
* virtualized (vs. rendering completely).
*/
public setDataListener(dataListener: DataListener, { virtual_mode }?: {
virtual_mode: ("both" | "horizontal" | "vertical" | "none");
}): void;
/** @private */
private _virtual_mode;
/** @private */
private _invalid_schema;
/** @private */
private _view_cache;
/**
* This func only exists to provide hints to doc compulation tools.
* Should never be run, and even if it is the body of the func will
* never execute.
*
* @internal
* @private
* @memberof RegularTableElement
*/
private __noop_jsdoc_hints;
/**
* Draws this virtual panel, given an object of render options that allow
* the implementor to fine tune the individual render frames based on the
* interaction and previous render state.
*
* @public
* @type {(opt?: DrawOptions) => void}
* @memberof RegularTableElement
* */
public draw: (opt?: DrawOptions) => void;
}
/**
* An object with performance statistics about calls to
* `draw()` from some time interval (captured in milliseconds by the
* `elapsed` proprty).
*/
export type Performance = {
/**
* - Avergage milliseconds per call.
*/
avg: number;
/**
* - `num_frames` / `elapsed`
*/
real_fps: number;
/**
* - `elapsed` / `avg`
*/
virtual_fps: number;
/**
* - Number of frames rendered.
*/
num_frames: number;
/**
* - Number of milliseconds since last call
* to `getDrawFPS()`.
*/
elapsed: number;
};
/**
* An object describing virtual rendering metadata about an
* `HTMLTableCellElement`, use this object to map rendered `<th>` or `<td>`
* elements back to your `data`, `row_headers` or `column_headers` within
* listener functions for `addStyleListener()` and `addEventListener()`.
*
* Example:
*
* MetaData (x = 0, column_header_y = 0))
* *-------------------------------------+
* | |
* | |
* +-------------------------------------+
* (row_header_x = 0, y = 0) (x = 0, y = 0)
* *------------------------+ *-------------------------------------+
* | | | |
* | | | (x0, y0) |
* | | | *---------------* |
* | | | | | |
* | | | | * (x, y) | |
* | | | | | |
* | | | *---------------* (x1, y1) |
* | | | |
* +------------------------+ +-------------------------------------+
*/
export type MetaData = {
/**
* - The `x` index in your virtual data model.
* property is only generated for `<td>`, `<th>` from `row_headers`.
*/
x?: number;
/**
* - The `y` index in your virtual data model.
* property is only generated for `<td>`, `<th>` from `row_headers`.
*/
y?: number;
/**
* - The `x` index of the viewport origin in
* your data model, e.g. what was passed to `x0` when your
* `dataListener` was invoked.
*/
x0?: number;
/**
* - The `y` index of the viewport origin in
* your data model, e.g. what was passed to `y0` when your
* `dataListener` was invoked.
*/
y0?: number;
/**
* - The `x` index of the viewport corner in
* your data model, e.g. what was passed to `x1` when your
* `dataListener` was invoked.
*/
x1?: number;
/**
* - The `y` index of the viewport corner in
* your data model, e.g. what was passed to `y1` when your
* `dataListener` was invoked.
*/
y1?: number;
/**
* - The `x` index in `DataResponse.data`, this
* property is only generated for `<td>`, and `<th>` from `column_headers`.
*/
dx?: number;
/**
* - The `y` index in `DataResponse.data`, this
* property is only generated for `<td>`, `<th>` from `row_headers`.
*/
dy?: number;
/**
* - The `y` index in
* `DataResponse.column_headers[x]`, this property is only generated for `<th>`
* from `column_headers`.
*/
column_header_y?: number;
/**
* - The `x` index in
* `DataResponse.row_headers[y]`, this property is only generated for `<th>`
* from `row_headers`.
*/
row_header_x?: number;
/**
* - The unique index of this column in a full
* `<table>`, which is `x` + (Total Row Header Columns).
*/
size_key: number;
/**
* - The `Array` for this `y` in
* `DataResponse.row_headers`, if it was provided.
*/
row_header?: (string | HTMLElement)[];
/**
* - The `Array` for this `x` in
* `DataResponse.column_headers`, if it was provided.
*/
column_header?: (string | HTMLElement)[];
/**
* - The value dispalyed in the cell or header.
*/
value?: (string | HTMLElement);
};
/**
* The `DataResponse` object describes a rectangular region of a virtual
* data set, and some associated metadata. `<regular-table>` will use this
* object to render the `<table>`, though it may make multiple requests for
* different regions to achieve a compelte render as it must estimate
* certain dimensions. You must construct a `DataResponse` object to
* implement a `DataListener`.
*
* Example:
* {
* "num_rows": 26,
* "num_columns": 3,
* "data": [
* [0, 1],
* ["A", "B"]
* ],
* "row_headers": [
* ["Rowgroup 1", "Row 1"],
* ["Rowgroup 1", "Row 2"]
* ],
* "column_headers": [
* ["Colgroup 1", "Column 1"],
* ["Colgroup 1", "Column 2"]
* ]
* }
*/
export type DataResponse = {
/**
* - A two dimensional
* `Array` of column group headers, in specificity order. No `<thead>`
* will be generated if this property is not provided.
*/
column_headers?: (string | HTMLElement)[][];
/**
* - A two dimensional
* `Array` of row group headers, in specificity order. No `<th>`
* elements within `<tbody>` will be generated if this property is not
* provided.
*/
row_headers?: (string | HTMLElement)[][];
/**
* - A two dimensional `Array`
* representing a rectangular section of the underlying data set from
* (x0, y0) to (x1, y1), arranged in columnar fashion such that
* `data[x][y]` returns the `y`th row of the `x`th column of the slice.
*/
data: (string | HTMLElement)[][];
/**
* - Total number of rows in the underlying
* data set.
*/
num_rows: number;
/**
* - Total number of columns in the
* underlying data set.
*/
num_columns: number;
};
/**
* The `DataListener` is similar to a normal event listener function.
* Unlike a normal event listener, it takes regular arguments (not an
* `Event`); and returns a `Promise` for a `DataResponse` object for this
* region (as opposed to returning `void` as a standard event listener).
*/
export type DataListener = (x0: number, y0: number, x1: number, y1: number) => Promise<DataResponse>;
/**
* Options for the draw method. `reset_scroll_position` will not prevent
* the viewport from moving as `draw()` may change the dimensions of the
* virtual_panel (and thus, absolute scroll offset). This calls
* `reset_scroll`, which will trigger `_on_scroll` and ultimately `draw()`
* again; however, this call to `draw()` will be for the same viewport
* and will not actually cause a render.
*/
export type DrawOptions = {
invalid_viewport?: boolean;
preserve_width?: boolean;
reset_scroll_position?: boolean;
swap?: boolean;
};
/**
* Public summary of table_model type.
*/
export type TableModel = {
header: ViewModel;
body: ViewModel;
num_columns: () => number;
};
/**
* Public summary of table_model.header and table_model.body base type.
*/
export type ViewModel = {
table: any;
cells: any[];
rows: any[];
num_columns: () => number;
num_rows: () => number;
};
//// END: index.d.ts
global {
namespace JSX {
interface IntrinsicElements {
"regular-table": Omit<DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>, "className"> & {
class?: string;
};
}
}
interface Document {
createElement(tagName: "regular-table", options?: ElementCreationOptions): RegularTableElement;
}
interface CustomElementRegistry {
get(name: 'regular-table'): typeof RegularTableElement;
}
}
} | the_stack |
import {GL} from '@loaders.gl/math'; // 'math.gl/geometry';
import assert from '../utils/assert';
/*
const DEFAULT_COLOR_VALUE = Color.WHITE;
const DEFAULT_SHOW_VALUE = true;
*/
const defined = x => x !== undefined;
// The size of this array equals the maximum instance count among all loaded tiles, which has the potential to be large.
const scratchVisited = [];
const scratchStack = [];
let marker = 0;
const scratchColorBytes = new Array(4);
const scratchColor = null; //new Color();
export default class Tile3DBatchTable {
constructor(batchTableJson, batchTableBinary, featuresLength) {
this.json = batchTableJson;
this.binary = batchTableBinary;
}
getExtension(extensionName) {
return this.json && this.json.extensions && this.json.extensions[extensionName];
}
// eslint-disable-next-line max-statements
initialize(batchTableJson, batchTableBinary, featuresLength) {
this.featuresLength = featuresLength;
this._translucentFeaturesLength = 0; // Number of features in the tile that are translucent
this._extensions = (batchTableJson && batchTableJson.extensions) || {};
const properties = initializeProperties(batchTableJson);
this._properties = properties;
this._batchTableHierarchy = initializeHierarchy(this, batchTableJson, batchTableBinary);
this._batchTableBinaryProperties = getBinaryProperties(featuresLength, properties, batchTableBinary);
// PERFORMANCE_IDEA: These parallel arrays probably generate cache misses in get/set color/show
// and use A LOT of memory. How can we use less memory?
this._showAlphaProperties = null; // [Show (0 or 255), Alpha (0 to 255)] property for each feature
this._batchValues = null; // Per-feature RGBA (A is based on the color's alpha and feature's show property)
this._batchValuesDirty = false;
this._batchTexture = null;
this._defaultTexture = null;
this._pickTexture = null;
this._pickIds = [];
this._content = content;
this._colorChangedCallback = colorChangedCallback;
// Dimensions for batch and pick textures
let textureDimensions;
let textureStep;
if (featuresLength > 0) {
// PERFORMANCE_IDEA: this can waste memory in the last row in the uncommon case
// when more than one row is needed (e.g., > 16K features in one tile)
const width = Math.min(featuresLength, ContextLimits.maximumTextureSize);
const height = Math.ceil(featuresLength / ContextLimits.maximumTextureSize);
const stepX = 1.0 / width;
const centerX = stepX * 0.5;
const stepY = 1.0 / height;
const centerY = stepY * 0.5;
textureDimensions = new Cartesian2(width, height);
textureStep = new Cartesian4(stepX, centerX, stepY, centerY);
}
this._textureDimensions = textureDimensions;
this._textureStep = textureStep;
}
memorySizeInBytes() {
return 0;
}
setShow(batchId, show) {
//>>includeStart('debug', pragmas.debug);
if (show && !defined(this._showAlphaProperties)) {
// Avoid allocating since the default is show = true
return;
}
const showAlphaProperties = getShowAlphaProperties(this);
const propertyOffset = batchId * 2;
const newShow = show ? 255 : 0;
if (showAlphaProperties[propertyOffset] !== newShow) {
showAlphaProperties[propertyOffset] = newShow;
const batchValues = getBatchValues(this);
// Compute alpha used in the shader based on show and color.alpha properties
const offset = (batchId * 4) + 3;
batchValues[offset] = show ? showAlphaProperties[propertyOffset + 1] : 0;
this._batchValuesDirty = true;
}
}
setAllShow(show) {
const featuresLength = this.featuresLength;
for (let i = 0; i < featuresLength; ++i) {
this.setShow(i, show);
}
}
getShow(batchId) {
//>>includeStart('debug', pragmas.debug);
this._checkBatchId(batchId, this.featuresLength);
//>>includeEnd('debug');
if (!defined(this._showAlphaProperties)) {
// Avoid allocating since the default is show = true
return true;
}
const offset = batchId * 2;
return (this._showAlphaProperties[offset] === 255);
}
setColor(batchId, color) {
//>>includeStart('debug', pragmas.debug);
this._checkBatchId(batchId, this.featuresLength);
Check.typeOf.object('color', color);
//>>includeEnd('debug');
if (Color.equals(color, DEFAULT_COLOR_VALUE) && !defined(this._batchValues)) {
// Avoid allocating since the default is white
return;
}
const newColor = color.toBytes(scratchColorBytes);
const newAlpha = newColor[3];
const batchValues = getBatchValues(this);
const offset = batchId * 4;
const showAlphaProperties = getShowAlphaProperties(this);
const propertyOffset = batchId * 2;
if ((batchValues[offset] !== newColor[0]) ||
(batchValues[offset + 1] !== newColor[1]) ||
(batchValues[offset + 2] !== newColor[2]) ||
(showAlphaProperties[propertyOffset + 1] !== newAlpha)) {
batchValues[offset] = newColor[0];
batchValues[offset + 1] = newColor[1];
batchValues[offset + 2] = newColor[2];
const wasTranslucent = (showAlphaProperties[propertyOffset + 1] !== 255);
// Compute alpha used in the shader based on show and color.alpha properties
const show = showAlphaProperties[propertyOffset] !== 0;
batchValues[offset + 3] = show ? newAlpha : 0;
showAlphaProperties[propertyOffset + 1] = newAlpha;
// Track number of translucent features so we know if this tile needs
// opaque commands, translucent commands, or both for rendering.
const isTranslucent = (newAlpha !== 255);
if (isTranslucent && !wasTranslucent) {
++this._translucentFeaturesLength;
} else if (!isTranslucent && wasTranslucent) {
--this._translucentFeaturesLength;
}
this._batchValuesDirty = true;
if (defined(this._colorChangedCallback)) {
this._colorChangedCallback(batchId, color);
}
}
}
setAllColor(color) {
// Check.typeOf.object('color', color);
for (let i = 0; i < this.featuresLength; ++i) {
this.setColor(i, color);
}
}
getColor(batchId, result) {
this._checkBatchId(batchId, this.featuresLength);
// Check.typeOf.object('result', result);
if (!defined(this._batchValues)) {
return Color.clone(DEFAULT_COLOR_VALUE, result);
}
const batchValues = this._batchValues;
const offset = batchId * 4;
const showAlphaProperties = this._showAlphaProperties;
const propertyOffset = batchId * 2;
return Color.fromBytes(batchValues[offset],
batchValues[offset + 1],
batchValues[offset + 2],
showAlphaProperties[propertyOffset + 1],
result);
}
getPickColor(batchId) {
this._checkBatchId(batchId, this.featuresLength);
return this._pickIds[batchId];
}
applyStyle(frameState, style) {
if (!style) {
this.setAllColor(DEFAULT_COLOR_VALUE);
this.setAllShow(true);
return;
}
const content = this._content;
const length = this.featuresLength;
for (let i = 0; i < length; ++i) {
const feature = content.getFeature(i);
const color = defined(style.color) ? style.color.evaluateColor(frameState, feature, scratchColor) : DEFAULT_COLOR_VALUE;
const show = defined(style.show) ? style.show.evaluate(frameState, feature) : DEFAULT_SHOW_VALUE;
this.setColor(i, color);
this.setShow(i, show);
}
}
isClass(batchId, className) {
this._checkBatchId(batchId, this.featuresLength);
assert(typeof className === 'string', className);
// PERFORMANCE_IDEA : cache results in the ancestor classes to speed up this check if this area becomes a hotspot
const hierarchy = this._batchTableHierarchy;
if (!defined(hierarchy)) {
return false;
}
// PERFORMANCE_IDEA : treat class names as integers for faster comparisons
const result = traverseHierarchy(hierarchy, batchId, (hierarchy, instanceIndex) => {
const classId = hierarchy.classIds[instanceIndex];
const instanceClass = hierarchy.classes[classId];
if (instanceClass.name === className) {
return true;
}
});
return defined(result);
}
isExactClass(batchId, className) {
assert(typeof className === 'string', className);
return this.getExactClassName(batchId) === className;
}
getExactClassName(batchId) {
this._checkBatchId(batchId, this.featuresLength);
const hierarchy = this._batchTableHierarchy;
if (!defined(hierarchy)) {
return undefined;
}
const classId = hierarchy.classIds[batchId];
const instanceClass = hierarchy.classes[classId];
return instanceClass.name;
}
hasProperty(batchId, name) {
this._checkBatchId(batchId, this.featuresLength);
assert(typeof name === 'string', name);
return (defined(this._properties[name])) || this._hasPropertyInHierarchy(batchId, name);
}
getPropertyNames(batchId, results) {
this._checkBatchId(batchId, this.featuresLength);
results = defined(results) ? results : [];
results.length = 0;
const propertyNames = Object.keys(this._properties);
results.push(...propertyNames);
if (this._batchTableHierarchy) {
this._getPropertyNamesInHierarchy(batchId, results);
}
return results;
}
getProperty(batchId, name) {
this._checkBatchId(batchId, this.featuresLength);
assert(typeof name === 'string', name);
if (defined(this._batchTableBinaryProperties)) {
const binaryProperty = this._batchTableBinaryProperties[name];
if (defined(binaryProperty)) {
return this.getBinaryProperty(binaryProperty, batchId);
}
}
const propertyValues = this._properties[name];
if (defined(propertyValues)) {
return clone(propertyValues[batchId], true);
}
if (defined(this._batchTableHierarchy)) {
const hierarchyProperty = this._getHierarchyProperty(batchId, name);
if (defined(hierarchyProperty)) {
return hierarchyProperty;
}
}
return undefined;
}
setProperty(batchId, name, value) {
const featuresLength = this.featuresLength;
this._checkBatchId(batchId, featuresLength);
assert(typeof name === 'string', name);
if (this._batchTableBinaryProperties) {
const binaryProperty = this._batchTableBinaryProperties[name];
if (binaryProperty) {
this.setBinaryProperty(binaryProperty, batchId, value);
return;
}
}
if (defined(this._batchTableHierarchy)) {
if (this._setHierarchyProperty(this, batchId, name, value)) {
return;
}
}
let propertyValues = this._properties[name];
if (!defined(propertyValues)) {
// Property does not exist. Create it.
this._properties[name] = new Array(featuresLength);
propertyValues = this._properties[name];
}
propertyValues[batchId] = clone(value, true);
}
getBinaryProperty(binaryProperty, index) {
const typedArray = binaryProperty.typedArray;
const componentCount = binaryProperty.componentCount;
if (componentCount === 1) {
return typedArray[index];
}
return binaryProperty.type.unpack(typedArray, index * componentCount);
}
setBinaryProperty(binaryProperty, index, value) {
const typedArray = binaryProperty.typedArray;
const componentCount = binaryProperty.componentCount;
if (componentCount === 1) {
typedArray[index] = value;
} else {
binaryProperty.type.pack(value, typedArray, index * componentCount);
this._hasPropertyInHierarchy(batchId, name){
if (!this._batchTableHierarchy) {
return false;
}
const result = traverseHierarchy(this._batchTableHierarchy, batchId, (hierarchy, instanceIndex) => {
const classId = hierarchy.classIds[instanceIndex];
const instances = hierarchy.classes[classId].instances;
if (defined(instances[name])) {
return true;
}
});
return defined(result);
}
_getPropertyNamesInHierarchy(batchId, results) {
traverseHierarchy(this._batchTableHierarchy, batchId, (hierarchy, instanceIndex) => {
const classId = hierarchy.classIds[instanceIndex];
const instances = hierarchy.classes[classId].instances;
for (const name in instances) {
if (instances.hasOwnProperty(name)) {
if (results.indexOf(name) === -1) {
results.push(name);
}
}
}
});
}
_getHierarchyProperty(batchId, name) {
return traverseHierarchy(this._batchTableHierarchy, batchId, (hierarchy, instanceIndex) => {
const classId = hierarchy.classIds[instanceIndex];
const instanceClass = hierarchy.classes[classId];
const indexInClass = hierarchy.classIndexes[instanceIndex];
const propertyValues = instanceClass.instances[name];
if (defined(propertyValues)) {
if (defined(propertyValues.typedArray)) {
return this.getBinaryProperty(propertyValues, indexInClass);
}
return clone(propertyValues[indexInClass], true);
}
});
}
_setHierarchyProperty(batchTable, batchId, name, value) {
const result = traverseHierarchy(this._batchTableHierarchy, batchId, (hierarchy, instanceIndex) => {
const classId = hierarchy.classIds[instanceIndex];
const instanceClass = hierarchy.classes[classId];
const indexInClass = hierarchy.classIndexes[instanceIndex];
const propertyValues = instanceClass.instances[name];
if (defined(propertyValues)) {
assert(instanceIndex === batchId, `Inherited property "${name}" is read-only.`);
if (defined(propertyValues.typedArray)) {
this.setBinaryProperty(propertyValues, indexInClass, value);
} else {
propertyValues[indexInClass] = clone(value, true);
}
return true;
}
});
return defined(result);
}
_checkBatchId(batchId, featuresLength) {
if (!Number.isFinite(batchId) || (batchId < 0) || (batchId > featuresLength)) {
throw new Error(`batchId is required and between zero and featuresLength - 1 (${featuresLength}).`);
}
}
}
function initializeProperties(jsonHeader) {
const properties = {};
if (!jsonHeader) {
return properties;
}
for (const propertyName in jsonHeader) {
if (jsonHeader.hasOwnProperty(propertyName)
&& propertyName !== 'HIERARCHY' // Deprecated HIERARCHY property
&& propertyName !== 'extensions'
&& propertyName !== 'extras') {
properties[propertyName] = clone(jsonHeader[propertyName], true);
}
}
return properties;
}
function getByteLength(batchTable) {
const dimensions = batchTable._textureDimensions;
return (dimensions.x * dimensions.y) * 4;
}
function getBatchValues(batchTable) {
if (!defined(batchTable._batchValues)) {
// Default batch texture to RGBA = 255: white highlight (RGB) and show/alpha = true/255 (A).
const byteLength = getByteLength(batchTable);
const bytes = new Uint8Array(byteLength);
bytes.fill(255);
batchTable._batchValues = bytes;
}
return batchTable._batchValues;
}
function getShowAlphaProperties(batchTable) {
if (!defined(batchTable._showAlphaProperties)) {
const byteLength = 2 * batchTable.featuresLength;
const bytes = new Uint8Array(byteLength);
// [Show = true, Alpha = 255]
bytes.fill(255);
batchTable._showAlphaProperties = bytes;
}
return batchTable._showAlphaProperties;
}
function getBinaryProperties(featuresLength, properties, binaryBody) {
let binaryProperties;
for (const name in properties) {
if (properties.hasOwnProperty(name)) {
const property = properties[name];
if ('byteOffset' in property) {
// This is a binary property
const componentType = property.componentType;
const type = property.type;
assert(Number.isFinite(property.componentType), 'componentType is required.');
if (!defined(type)) {
throw new Error('type is required.');
}
if (!defined(binaryBody)) {
throw new Error('Property ' + name + ' requires a batch table binary.');
}
const binaryAccessor = getBinaryAccessor(property);
const componentCount = binaryAccessor.componentsPerAttribute;
const classType = binaryAccessor.classType;
const byteOffset = property.byteOffset;
const typedArray = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + byteOffset, featuresLength);
if (!defined(binaryProperties)) {
binaryProperties = {};
}
// Store any information needed to access the binary data, including the typed array,
// componentCount (e.g. a VEC4 would be 4), and the type used to pack and unpack (e.g. Cartesian4).
binaryProperties[name] = {
typedArray,
componentCount,
type: classType
};
}
}
}
return binaryProperties;
}
function initializeHierarchy(batchTable, jsonHeader, binaryBody) {
if (!jsonHeader) {
return;
}
let hierarchy = batchTable.getExtension('3DTILES_batch_table_hierarchy');
const legacyHierarchy = jsonHeader.HIERARCHY;
if (legacyHierarchy) {
console.warn('3D Tile Parser: Batch table HIERARCHY property is deprecated. Use 3DTILES_batch_table_hierarchy extension instead.');
jsonHeader.extensions = jsonHeader.extensions || {};
jsonHeader.extensions['3DTILES_batch_table_hierarchy'] = legacyHierarchy;
hierarchy = legacyHierarchy;
}
if (!hierarchy) {
return null;
}
return initializeHierarchyValues(hierarchy, binaryBody);
}
// eslint-disable-next-line max-statements
function initializeHierarchyValues(hierarchyJson, binaryBody) {
const instancesLength = hierarchyJson.instancesLength;
const classes = hierarchyJson.classes;
const classIds = hierarchyJson.classIds;
const parentCounts = hierarchyJson.parentCounts;
const parentIds = hierarchyJson.parentIds;
const parentIdsLength = instancesLength;
if (defined(classIds.byteOffset)) {
classIds.componentType = defaultValue(classIds.componentType, GL.UNSIGNED_SHORT);
classIds.type = AttributeType.SCALAR;
const binaryAccessor = getBinaryAccessor(classIds);
classIds = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + classIds.byteOffset, instancesLength);
}
let parentIndexes;
if (defined(parentCounts)) {
if (defined(parentCounts.byteOffset)) {
parentCounts.componentType = defaultValue(parentCounts.componentType, GL.UNSIGNED_SHORT);
parentCounts.type = AttributeType.SCALAR;
const binaryAccessor = getBinaryAccessor(parentCounts);
parentCounts = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + parentCounts.byteOffset, instancesLength);
}
parentIndexes = new Uint16Array(instancesLength);
parentIdsLength = 0;
for (let i = 0; i < instancesLength; ++i) {
parentIndexes[i] = parentIdsLength;
parentIdsLength += parentCounts[i];
}
}
if (defined(parentIds) && defined(parentIds.byteOffset)) {
parentIds.componentType = defaultValue(parentIds.componentType, GL.UNSIGNED_SHORT);
parentIds.type = AttributeType.SCALAR;
const binaryAccessor = getBinaryAccessor(parentIds);
parentIds = binaryAccessor.createArrayBufferView(binaryBody.buffer, binaryBody.byteOffset + parentIds.byteOffset, parentIdsLength);
}
const classesLength = classes.length;
for (let i = 0; i < classesLength; ++i) {
const classInstancesLength = classes[i].length;
const properties = classes[i].instances;
const binaryProperties = getBinaryProperties(classInstancesLength, properties, binaryBody);
classes[i].instances = combine(binaryProperties, properties);
}
const classCounts = new Array(classesLength).fill(0);
const classIndexes = new Uint16Array(instancesLength);
for (let i = 0; i < instancesLength; ++i) {
const classId = classIds[i];
classIndexes[i] = classCounts[classId];
++classCounts[classId];
}
const hierarchy = {
classes,
classIds,
classIndexes,
parentCounts,
parentIndexes,
parentIds
};
validateHierarchy(hierarchy);
return hierarchy;
}
// HELPER CODE
function traverseHierarchyMultipleParents(hierarchy, instanceIndex, endConditionCallback) {
const classIds = hierarchy.classIds;
const parentCounts = hierarchy.parentCounts;
const parentIds = hierarchy.parentIds;
const parentIndexes = hierarchy.parentIndexes;
const instancesLength = classIds.length;
// Ignore instances that have already been visited. This occurs in diamond inheritance situations.
// Use a marker value to indicate that an instance has been visited, which increments with each run.
// This is more efficient than clearing the visited array every time.
const visited = scratchVisited;
visited.length = Math.max(visited.length, instancesLength);
const visitedMarker = ++marker;
const stack = scratchStack;
stack.length = 0;
stack.push(instanceIndex);
while (stack.length > 0) {
instanceIndex = stack.pop();
if (visited[instanceIndex] === visitedMarker) {
// This instance has already been visited, stop traversal
continue;
}
visited[instanceIndex] = visitedMarker;
const result = endConditionCallback(hierarchy, instanceIndex);
if (defined(result)) {
// The end condition was met, stop the traversal and return the result
return result;
}
const parentCount = parentCounts[instanceIndex];
const parentIndex = parentIndexes[instanceIndex];
for (let i = 0; i < parentCount; ++i) {
const parentId = parentIds[parentIndex + i];
// Stop the traversal when the instance has no parent (its parentId equals itself)
// else add the parent to the stack to continue the traversal.
if (parentId !== instanceIndex) {
stack.push(parentId);
}
}
}
}
function traverseHierarchySingleParent(hierarchy, instanceIndex, endConditionCallback) {
let hasParent = true;
while (hasParent) {
const result = endConditionCallback(hierarchy, instanceIndex);
if (defined(result)) {
// The end condition was met, stop the traversal and return the result
return result;
}
const parentId = hierarchy.parentIds[instanceIndex];
hasParent = parentId !== instanceIndex;
instanceIndex = parentId;
}
throw new Error('traverseHierarchySingleParent');
}
// Traverse over the hierarchy and process each instance with the endConditionCallback.
// When the endConditionCallback returns a value, the traversal stops and that value is returned.
function traverseHierarchy(hierarchy, instanceIndex, endConditionCallback) {
const parentCounts = hierarchy.parentCounts;
const parentIds = hierarchy.parentIds;
if (parentIds) {
return endConditionCallback(hierarchy, instanceIndex);
}
if (parentCounts > 0) {
return traverseHierarchyMultipleParents(hierarchy, instanceIndex, endConditionCallback);
}
return traverseHierarchySingleParent(hierarchy, instanceIndex, endConditionCallback);
}
// DEBUG CODE
function validateHierarchy(hierarchy) {
const scratchValidateStack = [];
const classIds = hierarchy.classIds;
const instancesLength = classIds.length;
for (let i = 0; i < instancesLength; ++i) {
validateInstance(hierarchy, i, stack);
}
}
function validateInstance(hierarchy, instanceIndex, stack) {
const parentCounts = hierarchy.parentCounts;
const parentIds = hierarchy.parentIds;
const parentIndexes = hierarchy.parentIndexes;
const classIds = hierarchy.classIds;
const instancesLength = classIds.length;
if (!defined(parentIds)) {
// No need to validate if there are no parents
return;
}
assert(instanceIndex < instancesLength,
`Parent index ${instanceIndex} exceeds the total number of instances: ${instancesLength}`);
assert(stack.indexOf(instanceIndex) === -1,
'Circular dependency detected in the batch table hierarchy.');
stack.push(instanceIndex);
const parentCount = defined(parentCounts) ? parentCounts[instanceIndex] : 1;
const parentIndex = defined(parentCounts) ? parentIndexes[instanceIndex] : instanceIndex;
for (let i = 0; i < parentCount; ++i) {
const parentId = parentIds[parentIndex + i];
// Stop the traversal when the instance has no parent (its parentId equals itself), else continue the traversal.
if (parentId !== instanceIndex) {
validateInstance(hierarchy, parentId, stack);
}
}
stack.pop(instanceIndex);
}
function getBatchValues(batchTable) {
if (!defined(batchTable._batchValues)) {
// Default batch texture to RGBA = 255: white highlight (RGB) and show/alpha = true/255 (A).
const byteLength = getByteLength(batchTable);
const bytes = new Uint8Array(byteLength);
bytes.fill(255);
batchTable._batchValues = bytes;
}
return batchTable._batchValues;
}
function getByteLength(batchTable) {
const dimensions = batchTable._textureDimensions;
return (dimensions.x * dimensions.y) * 4;
} | the_stack |
import ModuleEvent from "../event/ModuleEvent";
import ModuleCategories from "../enum/ModuleCategories";
import EventDispatcher from "./EventDispatcher";
import Patch from "./Patch";
import ModuleTypes from "../enum/ModuleTypes";
import Connection from "./Connection";
import AttributeTypes from "../enum/AttributeTypes";
import IModuleDefinition from "../config/IModuleDefinition";
class Module extends EventDispatcher
{
public parentPatch:Patch;
public definition:IModuleDefinition;
public id:string;
public audioNode:AudioNode;
public args:Array<any>;
public position:any;
public subPatch:Patch;
/**
* Creates a new module in a patch. This should not be done manually. todo prevent manual creation
* @param parentPatch
* @param definition
* @param id
* @param args
*/
constructor(parentPatch:Patch, definition:IModuleDefinition, id:string, args:Array<any>)
{
super();
this.parentPatch = parentPatch;
this.definition = definition;
this.id = id;
this.audioNode = null; // set later by the audiocontext manager (listens to added modules)
this.args = args; // store constructor arguments, so we can save them in the json
this.position = null; // will be set if a visualmodule is created for it. the only reason we set it is so we can use the value when we store it (toObject on Patch)
this.subPatch = null; // will be set if it's a subpatch
}
/**
* Returns the value for a given attribute id
* @param attributeId
* @returns {any}
*/
public getAttributeValue(attributeId:string):any
{
// first get the attribute
var attribute = this.getAttributeById(attributeId);
var value;
if(attribute)
{
switch(attribute.type)
{
case AttributeTypes.AUDIO_PARAM:
{
value = this.audioNode[attribute.id].value;
break;
}
case AttributeTypes.OPTION_LIST:
case AttributeTypes.FLOAT:
{
value = this.audioNode[attribute.id];
break;
}
default:
{
console.warn('Unhandled attribute type: ' + attribute.type);
}
}
return value;
}
else
{
console.error('No attribute found with id ' + attributeId + ' in module ' + this.definition.type);
}
}
/**
* Sets the audioNode for this module
* @param audioNode
*/
public setAudioNode(audioNode:AudioNode):void
{
this.audioNode = audioNode;
}
/**
* Returns an attribute by its id
* @param attributeId
* @returns {T}
*/
public getAttributeById(attributeId):any // todo type
{
return this.definition.attributes ? this.definition.attributes.find(attribute => attribute.id === attributeId) : null;
}
public setAttributeValue(attributeId:string, value:any):void
{
var attribute = this.getAttributeById(attributeId); // todo type
if(attribute)
{
switch(attribute.type)
{
case AttributeTypes.AUDIO_PARAM:
{
this.audioNode[attributeId].value = value; // todo shouldnt the ACM do this?
break;
}
case AttributeTypes.OPTION_LIST:
case AttributeTypes.FLOAT:
{
this.audioNode[attributeId] = value;
break;
}
default:
{
console.error('Unhandled attribute type: ' + attribute.type);
return;
}
}
this.dispatchEvent(ModuleEvent.ATTRIBUTE_CHANGED, {module: this, attribute: attribute});
}
else
{
console.error('Attribute not found: ' + attributeId);
}
}
/**
* Checks if there is an input for the given index.
* @param index
* @returns {boolean}
*/
public inputIndexIsValid(index:number):boolean
{
return !isNaN(index) && index < this.getNumberOfInputs() ? true : false;
}
/**
* Checks if there is an output for the give index.
* @param index
* @returns {boolean}
*/
public outputIndexIsValid(index):boolean
{
return !isNaN(index) && index < this.getNumberOfOutputs() ? true : false;
}
public getNumberOfInputs():number
{
return this.getNumberOfTransputs().in;
}
public getNumberOfOutputs():number
{
return this.getNumberOfTransputs().out;
}
public setAttributesByLoadedObject(moduleObject:any):void
{
if(!moduleObject.attributes) return;
for(var i = 0; i < moduleObject.attributes.length; i++)
{
var attribute = moduleObject.attributes[i];
this.setAttributeValue(attribute.id, attribute.value);
}
}
public getNumberOfTransputs():any
{
// TODO when loading a patch, this function gets called A LOT of times...why?
var numberOfInputs, numberOfOutputs;
switch(this.definition.category)
{
case ModuleCategories.NATIVE:
{
//console.log(this);
numberOfInputs = this.audioNode.numberOfInputs + this.getAudioParams().length;
numberOfOutputs = this.audioNode.numberOfOutputs
break;
}
case ModuleCategories.PROXY:
{
if(this.definition.type === ModuleTypes.SUBPATCH)
{
numberOfInputs = this.subPatch.getInputs().length;
numberOfOutputs = this.subPatch.getOutputs().length;
}
else
{
numberOfInputs = this.definition.in;
numberOfOutputs = this.definition.out;
}
break;
}
default:
{
console.error('Unhandled category: ' + this.definition.category);
return;
}
}
return {in: numberOfInputs, out: numberOfOutputs};
}
public getProxyTransputIndex():number
{
if(this.definition.type === ModuleTypes.INPUT)
{
return this.getProxyInputIndex();
}
else if(this.definition.type === ModuleTypes.OUTPUT)
{
return this.getProxyOutputIndex();
}
else
{
console.error('Module doesn\'t have a proxy (not an input or output)');
return -1;
}
}
/**
When called on an input module which is part of a subpatch, this returns the input that goes with it on its subpatch-module.
*/
public getProxyInputIndex():number
{
if(this.definition.type === ModuleTypes.INPUT)
{
// check if module is in rootpatch or a nested subpatch
var isRoot = this.parentPatch.parentModule ? false : true;
if(isRoot)
{
// root patch, has no proxy input
return -1;
}
else
{
// return the input-index is of this input
return this.parentPatch.getInputs().indexOf(this);
}
}
else
{
console.error('Only modules of type ' + ModuleTypes.INPUT + ' have a proxy input');
return -1;
}
}
/**
When called on an output module which is part of a subpatch, this returns the output that goes with it on its subpatch-module.
*/
public getProxyOutputIndex():number
{
if(this.definition.type === ModuleTypes.OUTPUT)
{
// check if module is in rootpatch or a nested subpatch
var isInRoot = this.parentPatch.parentModule ? false : true;
if(isInRoot)
{
// root patch, has no proxy input
return -1;
}
else
{
// return the input-index is of this input
return this.parentPatch.getOutputs().indexOf(this);
}
}
else
{
console.error('Only modules of type ' + ModuleTypes.OUTPUT + ' have a proxy output');
return -1;
}
}
public getNumberOfNodeInputs():number
{
return this.getNumberOfInputs() - this.getAudioParams().length;
}
public getAudioParamForInputIndex(inputIndex):any
{
var numberOfNodeInputs = this.getNumberOfNodeInputs();
if(inputIndex > numberOfNodeInputs - 1)
{
var audioParams = this.getAudioParams();
var paramIndex = inputIndex - numberOfNodeInputs;
return audioParams[paramIndex];
}
else
{
return null;
}
}
public getAudioParams():Array<any>
{
var results = [];
if(this.definition.attributes)
{
for(var i = 0; i < this.definition.attributes.length; i++)
{
if(this.definition.attributes[i].type === AttributeTypes.AUDIO_PARAM)
{
results.push(this.definition.attributes[i]);
}
}
}
return results;
}
public getConnectedModulesByProxy():Array<Module>
{
var results = [];
if(this.definition.type === ModuleTypes.INPUT)
{
// module is input, and either in the rootpatch, or in a subpatch, get the index of the proxy input on that subpatch
var inputIndex = this.getProxyInputIndex();
if(inputIndex === -1)
{
// input is in rootpatch, return empty array (no connected modules)
return results;
}
else
{
// input is in subpacth, get the subpatchmodule
var subPatchModule = this.parentPatch.parentModule;
// get the connections to that input
var connections = subPatchModule.getIncomingConnectionsForInput(inputIndex);
// loop through all connections
for(var i = 0; i < connections.length; i++)
{
var connection = connections[i];
if(connection.sourceModule.definition.type === ModuleTypes.INPUT)
{
// connection is connected to yet another input, call this function again and add the results
var modules = connection.sourceModule.getConnectedModulesByProxy();
for(var j = 0; j < modules.length; j++) results.push(modules[j])
}
else
{
// connection is connected to a regular module, add it to the results
results.push({module: connection.sourceModule, outputIndex: connection.sourceOutputIndex});
}
}
}
}
else if(this.definition.type === ModuleTypes.OUTPUT)
{
//if(isInRoot) return results; // todo WHATTTTTT?!
return results;
}
else
{
console.error('Only modules of type ' + ModuleTypes.INPUT + ' or ' + ModuleTypes.OUTPUT);
}
return results;
}
public getIncomingConnectionsForInput(inputIndex):Array<Connection>
{
var results = [];
for(var i = 0; i < this.parentPatch.connections.length; i++)
{
var connection = this.parentPatch.connections[i];
if(connection.destinationModule === this && connection.destinationInputIndex === inputIndex) results.push(connection)
}
return results;
}
public getOutgoingConnectionsForOutput(outputIndex):Array<Connection>
{
let results = [];
for(var i = 0; i < this.parentPatch.connections.length; i++)
{
var connection = this.parentPatch.connections[i];
if(connection.sourceModule === this && connection.sourceOutputIndex === outputIndex) results.push(connection)
}
return results;
}
public createBreadcrumb():Array<any>
{
let results = [];
var parentModule = this.parentPatch.parentModule;
while(parentModule)
{
results.push(parentModule.id);
parentModule = parentModule.parentPatch.parentModule;
}
return results.reverse();
}
public destruct():void
{
this.removeAllEventListeners();
this.parentPatch = null;
this.definition = null;
this.id = null;
this.audioNode = null;
this.args = null;
}
}
export default Module; | the_stack |
import { Button, Icon } from '@ridi/rsg';
import React from 'react';
import classNames from 'classnames';
import dateFnsFormat from 'date-fns/format';
import { connect } from 'react-redux';
import { RidiSelectState } from 'app/store';
import { EnvironmentState } from 'app/services/environment';
import { FetchStatusFlag, PageTitleText } from 'app/constants';
import { getIsIosInApp } from 'app/services/environment/selectors';
import { Actions as CommonUIActions } from 'app/services/commonUI';
import { ConnectedPageHeader, HelmetWithTitle } from 'app/components';
import { Actions, SubscriptionState, UserState } from 'app/services/user';
import { buildDateAndTimeFormat, buildOnlyDateFormat } from 'app/utils/formatDate';
import { SubscriptionListPlaceholder } from 'app/placeholder/SubscriptionListPlaceholder';
interface ManageSubscriptionStateProps {
userState: UserState;
environment: EnvironmentState;
subscriptionState?: SubscriptionState | null;
isIosInApp: boolean;
}
type ManageSubscriptionProps = ManageSubscriptionStateProps & ReturnType<typeof mapDispatchToProps>;
class ManageSubscription extends React.PureComponent<ManageSubscriptionProps> {
private handleUnsubscribeButtonClick = () => {
const { userState, dispatchUnsubscribeRequest } = this.props;
if (userState.unsubscriptionFetchStatus === FetchStatusFlag.FETCHING) {
return;
}
dispatchUnsubscribeRequest();
};
private handleCancelUnsubscriptionButtonClick = () => {
if (this.props.userState.unsubscriptionCancellationFetchStatus === FetchStatusFlag.FETCHING) {
return;
}
this.props.dispatchCancelUnsubscriptionRequest();
};
private handleChangePaymentButtonClick = (type: string) => {
const { subscriptionState } = this.props;
const { PAY_URL, STORE_URL } = this.props.environment;
const currentLocation = encodeURIComponent(location.href);
let locationUrl = `${PAY_URL}/settings/cards/change?returnUrl=${currentLocation}`;
if (subscriptionState) {
const { nextBillDate } = subscriptionState;
const today = dateFnsFormat(new Date(), 'yyyyMMdd');
const billDate = dateFnsFormat(new Date(nextBillDate), 'yyyyMMdd');
const currentHour = new Date().getHours();
// 결제일이랑 오늘날짜가 같고, 현재 시간이 23시~23시59분 사이라면 결제 불가 알림메시지
if (today === billDate && currentHour === 23) {
alert('결제일 23:00~23:59 시간에는 결제\n수단을 변경할 수 없습니다.');
return;
}
// 해지 예약 상태일 때, 결제 수단 변경 시 카드가 있다면
if (type === 'unsubscription') {
locationUrl = `${STORE_URL}/select/payments/ridi-pay?is_payment_method_change=true&return_url=${currentLocation}`;
}
// 리디캐시 자동충전 중인 상태의 카드일때 컨펌메시지
const { cardSubscription } = subscriptionState;
if (cardSubscription) {
const cardSubscriptionString = cardSubscription.join(',');
if (
cardSubscriptionString.includes('리디캐시 자동충전') &&
!confirm(
'리디캐시 자동충전이 설정된 카드입니다.\n결제 수단 변경 시 변경된 카드로 자동 충전됩니다.',
)
) {
return;
}
}
window.location.href = locationUrl;
}
};
public componentDidMount() {
if (!this.props.subscriptionState) {
this.props.dispatchLoadSubscriptionRequest();
}
this.props.dispatchUpdateGNBTabExpose(false);
}
public componentWillUnmount() {
this.props.dispatchUpdateGNBTabExpose(true);
}
public render() {
const { subscriptionState, environment, isIosInApp, userState } = this.props;
const { STORE_URL } = environment;
return (
<main className={classNames('SceneWrapper', 'PageManageSubscription')}>
<HelmetWithTitle titleName={PageTitleText.MANAGE_SUBSCRIPTION} />
<ConnectedPageHeader pageTitle={PageTitleText.MANAGE_SUBSCRIPTION} />
{subscriptionState ? (
<>
<ul className="SubscriptionInfo_List">
<li className="SubscriptionInfo">
<p className="SubscriptionInfo_Title">이용 기간</p>
<p className="SubscriptionInfo_Data">
{`${buildDateAndTimeFormat(userState.availableUntil)} 까지`}
</p>
</li>
{subscriptionState.isOptout ? (
<li className="SubscriptionInfo">
<p className="SubscriptionInfo_Title">구독 해지 일시</p>
<p className="SubscriptionInfo_Data">
{buildDateAndTimeFormat(subscriptionState.optoutDate)}
</p>
</li>
) : (
<>
<li className="SubscriptionInfo">
<p className="SubscriptionInfo_Title">다음 결제 예정일</p>
<p className="SubscriptionInfo_Data">
{buildOnlyDateFormat(subscriptionState.nextBillDate)}
</p>
</li>
<li className="SubscriptionInfo">
<p className="SubscriptionInfo_Title">결제 예정 금액</p>
<p className="SubscriptionInfo_Data">
{subscriptionState.formattedMonthlyPayPrice}
</p>
</li>
<li className="SubscriptionInfo">
<p className="SubscriptionInfo_Title SubscriptionInfo_CardInfoColumn">
결제 수단
</p>
<div className="SubscriptionInfo_Data SubscriptionInfo_CardInfoColumn">
{subscriptionState.paymentMethod}
<div className="SubscriptionInfo_CardInfoWrapper">
{subscriptionState.cardBrand && subscriptionState.maskedCardNo && (
<p className="SubscriptionInfo_CardInfo">
{`${subscriptionState.cardBrand} ${subscriptionState.maskedCardNo}`}
</p>
)}
{subscriptionState.isUsingRidipay && !isIosInApp ? (
<a
className="SubscriptionInfo_Link"
onClick={() => {
this.handleChangePaymentButtonClick('subscription');
}}
>
결제 수단 변경
<Icon name="arrow_5_right" className="SubscriptionInfo_Link_Icon" />
</a>
) : null}
{/* TODO: 추후 XPAY 유저가 없을 시 삭제 예정 */}
{subscriptionState.pgType === 'XPAY' &&
!subscriptionState.isUsingRidipay &&
!isIosInApp && (
<a
className="SubscriptionInfo_Link"
href={`${STORE_URL}/select/payments/xpay/change-to-ridi-pay?return_url=${encodeURIComponent(
location.href,
)}`}
>
결제 수단 변경
<Icon name="arrow_5_right" className="SubscriptionInfo_Link_Icon" />
</a>
)}
</div>
</div>
</li>
</>
)}
</ul>
<div className="ToggleSubscriptionButton_Wrapper">
{subscriptionState.isOptout ? (
subscriptionState.isOptoutCancellableWithPaymentMethodChange ? (
!isIosInApp && (
<Button
className="ToggleSubscriptionButton"
onClick={() => {
this.handleChangePaymentButtonClick('unsubscription');
}}
outline
>
구독 해지 예약 취소
</Button>
)
) : (
<Button
className="ToggleSubscriptionButton"
onClick={this.handleCancelUnsubscriptionButtonClick}
spinner={
this.props.userState.unsubscriptionCancellationFetchStatus ===
FetchStatusFlag.FETCHING
}
color="blue"
disabled={!subscriptionState.isOptoutCancellable}
>
구독 해지 예약 취소
</Button>
)
) : (
<Button
className="ToggleSubscriptionButton"
onClick={() => this.handleUnsubscribeButtonClick()}
outline
spinner={
this.props.userState.unsubscriptionFetchStatus === FetchStatusFlag.FETCHING
}
>
구독 해지 예약
</Button>
)}
</div>
{!subscriptionState.isOptout && (
<p className="UnsubscriptionInfoText">
지금 해지 예약하셔도 {buildOnlyDateFormat(userState.availableUntil)}까지 이용할 수
있습니다.
</p>
)}
{subscriptionState.isOptout &&
!subscriptionState.isOptoutCancellable &&
subscriptionState.optoutReasonKor && (
<p className="ReasonForNonCancellable">
<Icon className="ReasonForNonCancellable_Icon" name="exclamation_3" />
<strong>{subscriptionState.optoutReasonKor}</strong>
<br />
{subscriptionState.isOptoutCancellableWithPaymentMethodChange
? '카드 재등록 시 구독 해지 예약을 취소할 수 있습니다.'
: '이용 기간 만료 후 다시 구독해주세요.'}
</p>
)}
</>
) : (
<SubscriptionListPlaceholder />
)}
</main>
);
}
}
const mapStateToProps = (state: RidiSelectState): ManageSubscriptionStateProps => ({
userState: state.user,
environment: state.environment,
subscriptionState: state.user.subscription,
isIosInApp: getIsIosInApp(state),
});
const mapDispatchToProps = (dispatch: any) => ({
dispatchLoadSubscriptionRequest: () => dispatch(Actions.loadSubscriptionRequest()),
dispatchUnsubscribeRequest: () => dispatch(Actions.unsubscribeRequest()),
dispatchCancelUnsubscriptionRequest: () => dispatch(Actions.cancelUnsubscriptionRequest()),
dispatchUpdateGNBTabExpose: (isGnbTab: boolean) =>
dispatch(CommonUIActions.updateGNBTabExpose({ isGnbTab })),
});
const ConnectedManageSubscription = connect(
mapStateToProps,
mapDispatchToProps,
)(ManageSubscription);
export default ConnectedManageSubscription; | the_stack |
import { expect, use } from 'chai';
import * as chaiAsPromised from 'chai-as-promised';
import * as OriginSequelize from 'sequelize';
import { createSequelize } from '../utils/sequelize';
import {
Sequelize,
Model,
Table,
Column,
BelongsToMany,
ForeignKey,
HasOne,
HasMany,
BelongsTo,
DataType,
} from '../../src';
import { expectAutoGeneratedFunctions } from '../utils/association';
import { assertInstance } from '../utils/common';
import { AllowNull } from '../../src/model/column/column-options/allow-null';
import { PrimaryKey } from '../../src/model/column/primary-key/primary-key';
use(chaiAsPromised);
const Association: any = OriginSequelize['Association'];
/* Some base classes that we can override later */
class ConcreteModel extends Model {}
class BookModel extends ConcreteModel {
title: string;
pages: PageModel[];
authors: AuthorModel[];
}
class PageModel extends ConcreteModel {
content: string;
bookId: number;
book: BookModel;
}
class AuthorModel extends ConcreteModel {
name: string;
books: BookWithAuthorModel[];
}
class BookWithAuthorModel extends BookModel {
authors: AuthorModel[];
}
describe('association', () => {
let sequelize: Sequelize;
const jsForDummiesBook = {
title: 'JS for dummies',
};
const crimeAndPunishmentBook = {
title: 'Crime and Punishment',
};
const elisa = { name: 'elisa' };
const robin = { name: 'robin' };
const nelly = { name: 'nelly' };
const brom = { name: 'brom' };
before(() => {
sequelize = createSequelize(false);
});
describe('One-to-many', () => {
function oneToManyTestSuites(Book: typeof BookModel, Page: typeof PageModel): void {
const sherlockHolmesBook = {
title: 'Sherlock Holmes',
pages: [{ content: 'Watson' }, { content: 'Moriaty' }],
};
const page1 = {
content: 'written by Oscar Wilde',
book: {
title: 'The Picture of Dorian Gray',
},
};
const page2 = {
content: 'js1',
};
const page3 = {
content: 'js2',
};
const page4 = {
content: 'js3',
};
const page5 = {
content: 'js4',
};
before(() => sequelize.addModels([Page, Book]));
beforeEach(() => {
return sequelize.sync({ force: true });
});
it('should create models with specified relations', () => {
expect(Book)
.to.have.property('associations')
.that.has.property('pages')
.that.is.an.instanceOf(Association['HasMany'])
.and.has.property('foreignKey', 'bookId');
expect(Page)
.to.have.property('associations')
.that.has.property('book')
.that.is.an.instanceOf(Association['BelongsTo'])
.and.has.property('foreignKey', 'bookId');
});
it('should create models with generated functions on its prototype', () => {
expectAutoGeneratedFunctions(Book, { singular: 'page', plural: 'pages' });
expectAutoGeneratedFunctions(Page, { singular: 'book' });
});
describe('create()', () => {
it('should create instances and relation between', () =>
Promise.all([
Book.create(sherlockHolmesBook, { include: [Page] }).then((book) => {
assertInstance(book, sherlockHolmesBook);
}),
Page.create(page1, { include: [Book] }).then((page) => {
assertInstance(page, page1);
}),
]));
it('should create instances without relation', () =>
Book.create({
title: 'Sherlock Holmes',
pages: [{ content: 'Watson' }, { content: 'Moriaty' }],
}).then((book) => {
expect(book).to.have.property('id').that.is.not.null;
expect(book).not.to.have.property('pages');
}));
});
describe('findByPk()', () => {
it('should find instances with related instances', () =>
Promise.all([
Book.create(sherlockHolmesBook, { include: [Page] })
.then((book) => Book.findByPk(book.id, { include: [Page] }))
.then((book) => {
assertInstance(book, sherlockHolmesBook);
}),
Page.create(page1, { include: [Book] })
.then((page) => Page.findByPk(page.id, { include: [Book] }))
.then((page) => {
assertInstance(page, page1);
}),
]));
});
describe('findOne()', () => {
it('should find instances with related instances', () =>
Promise.all([
Book.create(sherlockHolmesBook, { include: [Page] })
.then((book) => Book.findOne({ include: [Page], where: { id: book.id } }))
.then((book) => {
assertInstance(book, sherlockHolmesBook);
}),
Page.create(page1, { include: [Book] })
.then((page) => Page.findOne({ include: [Book], where: { id: page.id } }))
.then((page) => {
assertInstance(page, page1);
}),
]));
});
describe('findAll()', () => {
it('should find instances with related instances', () =>
Promise.all([
Book.create(sherlockHolmesBook, { include: [Page] })
.then((book) => Book.findAll({ include: [Page], where: { id: book.id } }))
.then((books) => {
assertInstance(books[0], sherlockHolmesBook);
}),
Page.create(page1, { include: [Book] })
.then((page) => Page.findAll({ include: [Book], where: { id: page.id } }))
.then((pages) => {
assertInstance(pages[0], page1);
}),
]));
});
describe('$get', () => {
it('should get related instances of source instance', () =>
Book.create(sherlockHolmesBook, { include: [Page] })
.then((book) => Book.findByPk(book.id))
.then((book) =>
book.$get('pages').then((pages) => {
assertInstance(pages, sherlockHolmesBook.pages);
})
));
it('should get related instance of source instance', () =>
Page.create(page1, { include: [Book] })
.then((page) => Page.findByPk(page.id))
.then((page) =>
page.$get('book').then((book) => {
assertInstance(book, page1.book);
})
));
});
describe('$set', () => {
it('should set relation between specified instances and source instance', () =>
Promise.all([Book.create(jsForDummiesBook), Page.create(page2), Page.create(page3)]).then(
([book, ...pages]) =>
book
.$set('pages', pages)
.then(() => Book.findByPk(book.id, { include: [Page] }))
.then((_book) => {
assertInstance(_book, Object.assign({ pages: [page2, page3] }, jsForDummiesBook));
})
));
it('should override previous relations', () =>
Promise.all([
Book.create(jsForDummiesBook),
Page.create(page2),
Page.create(page3),
Page.create(page4),
Page.create(page5),
]).then(([book, pageA, pageB, pageC, pageD]) =>
book
.$set('pages', [pageA, pageB])
.then(() => Book.findByPk(book.id, { include: [Page] }))
.then((_book) => {
assertInstance(_book, Object.assign({ pages: [page2, page3] }, jsForDummiesBook));
})
// override previous pages
.then(() => book.$set('pages', [pageC, pageD]))
.then(() => Book.findByPk(book.id, { include: [Page] }))
.then((_book) => {
// and check, if there are overridden
assertInstance(_book, Object.assign({ pages: [page4, page5] }, jsForDummiesBook));
})
));
it('should set relation between specified instance and source instance', () =>
Promise.all([Page.create(page2), Book.create(jsForDummiesBook)]).then(([page, book]) =>
page
.$set('book', book)
.then(() => Page.findByPk(page.id, { include: [Book] }))
.then((_page) => {
assertInstance(_page, Object.assign({ book: jsForDummiesBook }, page2));
})
));
it('should override previous relation', () =>
Promise.all([
Page.create(page2),
Book.create(jsForDummiesBook),
Book.create(crimeAndPunishmentBook),
]).then(([page, bookA, bookB]) =>
page
.$set('book', bookA)
.then(() => Page.findByPk(page.id, { include: [Book] }))
.then((_page) => {
assertInstance(_page, Object.assign({ book: jsForDummiesBook }, page2));
})
.then(() => page.$set('book', bookB))
.then(() => Page.findByPk(page.id, { include: [Book] }))
.then((_page) => {
assertInstance(_page, Object.assign({ book: crimeAndPunishmentBook }, page2));
})
));
});
describe('$add', () => {
it('should add relation between specified instance and source instance', () =>
Promise.all([Book.create(jsForDummiesBook), Page.create(page2)]).then(([book, page]) =>
book
.$add('page', page)
.then(() => Book.findByPk(book.id, { include: [Page] }))
.then((_book) => {
assertInstance(_book, Object.assign({ pages: [page2] }, jsForDummiesBook));
})
));
it('should add relations between specified instance and source instance', () =>
Promise.all([Book.create(jsForDummiesBook), Page.create(page2), Page.create(page3)]).then(
([book, ...pages]) =>
book
.$add('pages', pages)
.then(() => Book.findByPk(book.id, { include: [Page] }))
.then((_book) => {
assertInstance(_book, Object.assign({ pages: [page2, page3] }, jsForDummiesBook));
})
));
it('should not override previous relations', () =>
Promise.all([Book.create(jsForDummiesBook), Page.create(page2), Page.create(page3)]).then(
([book, pageA, pageB]) =>
book
.$add('page', pageA)
.then(() => Book.findByPk(book.id, { include: [Page] }))
.then((_book) => {
assertInstance(_book, Object.assign({ pages: [page2] }, jsForDummiesBook));
})
// now we add another page
.then(() => book.$add('page', pageB))
.then(() => Book.findByPk(book.id, { include: [Page] }))
.then((_book) => {
// ... and check, if both pages exist
assertInstance(_book, Object.assign({ pages: [page2, page3] }, jsForDummiesBook));
})
));
});
describe('$create', () => {
it('should create new instance and add relation between new instance and source instance (has many)', () =>
Book.create(jsForDummiesBook).then((book) =>
book
.$create('page', page2)
.then((page) => {
assertInstance(page, page2);
})
.then(() => Book.findByPk(book.id, { include: [Page] }))
.then((_book) => {
assertInstance(_book, Object.assign({ pages: [page2] }, jsForDummiesBook));
})
));
it('should create new instance and add relation between new instance and source instance (belongs to)', () =>
Page.create(page3).then((page) =>
page
.$create('book', jsForDummiesBook)
.then(() => Page.findByPk(page.id, { include: [Book] }))
.then((_page) => {
assertInstance(_page, Object.assign({ book: jsForDummiesBook }, page3));
})
));
});
describe('$has', () => {
it('should return true due to relation between specified instances and source instance', () =>
Book.create(sherlockHolmesBook, { include: [Page] }).then((book) =>
Book.findByPk(book.id)
.then((_book) => _book.$has('pages', book.pages))
.then((result) => {
expect(result).to.be.true;
})
));
it('should return false due to no relation between specified instance and source instance', () =>
Promise.all([
Book.create(sherlockHolmesBook, { include: [Page] }),
Page.create(page3),
]).then(([book, page]) =>
Book.findByPk(book.id)
.then((_book) => _book.$has('pages', page))
.then((result) => {
expect(result).to.be.false;
})
));
});
describe('$count', () => {
it('should return number of specified relations', () =>
Book.create(sherlockHolmesBook, { include: [Page] }).then((book) =>
Book.findByPk(book.id)
.then((_book) => _book.$count('pages'))
.then((result) => {
expect(result).to.equal(sherlockHolmesBook.pages.length);
})
));
it('should return 0, since source instance has no relations', () =>
Book.create(sherlockHolmesBook).then((book) =>
Book.findByPk(book.id)
.then((_book) => _book.$count('pages'))
.then((result) => {
expect(result).to.equal(0);
})
));
});
describe('$remove', () => {
it('should remove relation between specified instance and source instance', () =>
Book.create(sherlockHolmesBook, { include: [Page] }).then((book) =>
Book.findByPk(book.id, { include: [Page] })
.then((_book) => {
assertInstance(_book, sherlockHolmesBook);
return _book.$remove('page', _book.pages[0]);
})
.then(() => Book.findByPk(book.id, { include: [Page] }))
.then((_book) => {
assertInstance(_book, {
title: sherlockHolmesBook.title,
pages: [sherlockHolmesBook.pages[1]],
});
})
));
it('should remove relations between specified instances and source instance', () =>
Book.create(sherlockHolmesBook, { include: [Page] }).then((book) =>
Book.findByPk(book.id, { include: [Page] })
.then((_book) => {
assertInstance(_book, sherlockHolmesBook);
return _book.$remove('pages', _book.pages);
})
.then(() => Book.findByPk(book.id, { include: [Page] }))
.then((_book) => {
assertInstance(_book, {
title: sherlockHolmesBook.title,
});
})
));
});
}
describe('resolve foreign keys automatically', () => {
@Table
class Book extends Model implements BookModel {
@Column
title: string;
authors: any[];
@HasMany(() => Page)
pages: Page[];
}
@Table
class Page extends Model implements PageModel {
@Column(DataType.TEXT)
content: string;
@ForeignKey(() => Book)
bookId: number;
@BelongsTo(() => Book)
book: Book;
}
oneToManyTestSuites(Book, Page);
});
describe('set foreign keys explicitly', () => {
@Table
class Book2 extends Model implements BookModel {
@Column
title: string;
authors: any[];
@HasMany(() => Page2, 'bookId')
pages: Page2[];
}
@Table
class Page2 extends Model implements PageModel {
@Column(DataType.TEXT)
content: string;
bookId: number;
@BelongsTo(() => Book2, 'bookId')
book: Book2;
}
oneToManyTestSuites(Book2, Page2);
});
function oneToManyWithOptionsTestSuites(
Book: typeof BookModel,
Page: typeof PageModel,
alternateName = false
): void {
const foreignKey = alternateName ? 'book_id' : 'bookId';
before(() => sequelize.addModels([Page, Book]));
beforeEach(() => {
return sequelize.sync({ force: true });
});
it('should create models with specified relations', () => {
expect(Book)
.to.have.property('associations')
.that.has.property('pages')
.that.is.an.instanceOf(Association['HasMany'])
.which.includes({ foreignKey })
.and.has.property('foreignKeyAttribute')
.which.includes({ allowNull: false, name: foreignKey });
expect(Book)
.to.have.property('associations')
.that.has.property('pages')
.that.has.property('options')
.with.property('onDelete', 'CASCADE');
expect(Page)
.to.have.property('associations')
.that.has.property('book')
.that.is.an.instanceOf(Association['BelongsTo'])
.which.includes({ foreignKey })
.and.has.property('foreignKeyAttribute')
.which.includes({ allowNull: false, name: foreignKey });
expect(Page)
.to.have.property('associations')
.that.has.property('book')
.that.has.property('options')
.with.property('onDelete', 'CASCADE');
});
describe('create()', () => {
it('should fail creating instances that require a primary key', () => {
const page = {
content: 'written by Oscar Wilde',
book: {
title: 'The Picture of Dorian Gray',
},
};
return Page.create(page, { include: [Book] }).catch((err) =>
expect(err.message).to.match(
new RegExp(
`^notNull Violation: (${Page.name}.${foreignKey}|${foreignKey}) cannot be null$`
)
)
);
});
it('should create instances that require a parent primary key', () => {
const book = {
title: 'Sherlock Holmes',
pages: [{ content: 'Watson' }, { content: 'Moriaty' }],
};
return Book.create(book, { include: [Page] }).then((actual: any) => {
expect(actual.id).to.be.gt(0);
expect(actual.title).to.eq(book.title);
expect(actual.pages).to.have.lengthOf(2);
expect(actual.pages[0].id).to.be.gt(0);
expect(actual.pages[0].content).to.eq(book.pages[0].content);
expect(actual.pages[1].id).to.be.gt(0);
expect(actual.pages[1].content).to.eq(book.pages[1].content);
});
});
});
}
describe('resolve foreign keys automatically with association options', () => {
@Table
class Book3 extends Model implements BookModel {
@Column
title: string;
authors: any[];
@HasMany(() => Page3, { foreignKey: { allowNull: false }, onDelete: 'CASCADE' })
pages: Page3[];
}
@Table
class Page3 extends Model implements PageModel {
@Column(DataType.TEXT)
content: string;
@ForeignKey(() => Book3)
bookId: number;
@BelongsTo(() => Book3, { foreignKey: { allowNull: false }, onDelete: 'CASCADE' })
book: Book3;
}
oneToManyWithOptionsTestSuites(Book3, Page3);
});
describe('set foreign keys explicitly with association options', () => {
@Table
class Book4 extends Model implements BookModel {
@Column
title: string;
authors: any[];
@HasMany(() => Page4, {
foreignKey: { allowNull: false, name: 'book_id' },
onDelete: 'CASCADE',
})
pages: Page4[];
}
@Table
class Page4 extends Model implements PageModel {
@Column(DataType.TEXT)
content: string;
@ForeignKey(() => Book4)
bookId: number;
@BelongsTo(() => Book4, {
foreignKey: { allowNull: false, name: 'book_id' },
onDelete: 'CASCADE',
})
book: Book4;
}
oneToManyWithOptionsTestSuites(Book4, Page4, true);
});
describe('set foreign keys explicitly via options', () => {
@Table
class Book5 extends Model implements BookModel {
@Column
title: string;
authors: any[];
@HasMany(() => Page5, { foreignKey: 'bookId' })
pages: Page5[];
}
@Table
class Page5 extends Model implements PageModel {
@Column(DataType.TEXT)
content: string;
bookId: number;
@BelongsTo(() => Book5, { foreignKey: 'bookId' })
book: Book5;
}
oneToManyTestSuites(Book5, Page5);
});
it('Should throw error when trying to resolve associations with uninitialized Models', () => {
const _sequelize = createSequelize(false);
@Table
class Friend extends Model {}
@Table
class User extends Model {
@HasOne(() => Friend, 'userId')
friend: Friend;
}
expect(() => _sequelize.addModels([User])).to.throw(
new RegExp('Friend has not been defined')
);
});
});
describe('Many-to-many', () => {
function manyToManyTestSuites(
Book: typeof BookModel,
Author: typeof AuthorModel,
AuthorBook?: typeof ConcreteModel
): void {
const models: Array<typeof ConcreteModel> = [Book, Author];
if (AuthorBook) {
models.push(AuthorBook);
}
const sherlockHolmesBook = {
title: 'Sherlock Holmes',
authors: [{ name: 'Sir Arthur Conan Doyle' }, { name: 'No Ghost' }],
};
const julesVerne = {
name: 'Jules Verne',
books: [
{ title: 'Journey to the Center of the Earth' },
{ title: 'Twenty Thousand Leagues Under the Sea' },
],
};
before(() => sequelize.addModels(models));
beforeEach(() => sequelize.sync({ force: true }));
it('should create models with specified relations', () => {
expect(Book)
.to.have.property('associations')
.that.has.property('authors')
.that.is.an.instanceOf(Association['BelongsToMany'])
.and.has.property('foreignKey', 'bookId');
expect(Author)
.to.have.property('associations')
.that.has.property('books')
.that.is.an.instanceOf(Association['BelongsToMany'])
.and.has.property('foreignKey', 'authorId');
});
it('should create models with generated functions on its prototype', () => {
expectAutoGeneratedFunctions(Book, { singular: 'author', plural: 'authors' });
expectAutoGeneratedFunctions(Author, { singular: 'book', plural: 'books' });
});
describe('create()', () => {
it('should create instances and relation between', () =>
Promise.all([
Book.create(sherlockHolmesBook, { include: [Author] }).then((book) => {
assertInstance(book, sherlockHolmesBook);
}),
Author.create(julesVerne, { include: [Book] }).then((author) => {
assertInstance(author, julesVerne);
}),
]));
it('should create instances without relation', () =>
Author.create(julesVerne).then((author) => {
assertInstance(author, { name: julesVerne.name });
}));
});
describe('findByPk()', () => {
it('should find instances with related instances', () =>
Promise.all([
Book.create(sherlockHolmesBook, { include: [Author] })
.then((book) => Book.findByPk(book.id, { include: [Author] }))
.then((book) => {
assertInstance(book, sherlockHolmesBook);
}),
Author.create(julesVerne, { include: [Book] })
.then((author) => Author.findByPk(author.id, { include: [Book] }))
.then((author) => {
assertInstance(author, julesVerne);
}),
]));
});
describe('findOne()', () => {
it('should find instances with related instances', () =>
Promise.all([
Book.create(sherlockHolmesBook, { include: [Author] })
.then((book) => Book.findOne({ include: [Author], where: { id: book.id } }))
.then((book) => {
assertInstance(book, sherlockHolmesBook);
}),
Author.create(julesVerne, { include: [Book] })
.then((author) => Author.findOne({ include: [Book], where: { id: author.id } }))
.then((author) => {
assertInstance(author, julesVerne);
}),
]));
});
describe('findAll()', () => {
it('should find instances with related instances', () =>
Promise.all([
Book.create(sherlockHolmesBook, { include: [Author] })
.then((book) => Book.findAll({ include: [Author], where: { id: book.id } }))
.then((books) => {
assertInstance(books[0], sherlockHolmesBook);
}),
Author.create(julesVerne, { include: [Book] })
.then((author) => Author.findAll({ include: [Book], where: { id: author.id } }))
.then((authors) => {
assertInstance(authors[0], julesVerne);
}),
]));
});
describe('$get', () => {
it('should get related instances of source instance', () =>
Promise.all([
Book.create(sherlockHolmesBook, { include: [Author] })
.then((book) => Book.findByPk(book.id))
.then((book) =>
book.$get('authors').then((authors) => {
assertInstance(authors, sherlockHolmesBook.authors);
})
),
Author.create(julesVerne, { include: [Book] })
.then((author) => Author.findByPk(author.id))
.then((author) =>
author.$get('books').then((books) => {
assertInstance(books, julesVerne.books);
})
),
]));
});
describe('$set', () => {
it('should set relation between specified instances and source instance', () =>
Promise.all([
Book.create(jsForDummiesBook),
Author.create(elisa),
Author.create(robin),
]).then(([book, ...authors]) =>
book
.$set('authors', authors)
.then(() => Book.findByPk(book.id, { include: [Author] }))
.then((_book) => {
assertInstance(_book, Object.assign({ authors: [elisa, robin] }, jsForDummiesBook));
})
));
it('should override previous relations', () =>
Promise.all([
Book.create(jsForDummiesBook),
Author.create(elisa),
Author.create(nelly),
Author.create(brom),
Author.create(robin),
]).then(([book, _elisa, _nelly, _brom, _robin]) =>
book
.$set('authors', [_elisa, _nelly])
.then(() => Book.findByPk(book.id, { include: [Author] }))
.then((_book) => {
assertInstance(_book, Object.assign({ authors: [elisa, nelly] }, jsForDummiesBook));
})
// override previous authors
.then(() => book.$set('authors', [_brom, _robin]))
.then(() => Book.findByPk(book.id, { include: [Author] }))
.then((_book) => {
// and check, if there are overridden
assertInstance(_book, Object.assign({ authors: [brom, robin] }, jsForDummiesBook));
})
));
});
describe('$add', () => {
it('should add relation between specified instance and source instance', () =>
Promise.all([Book.create(jsForDummiesBook), Author.create(elisa)]).then(
([book, _elisa]) =>
book
.$add('author', _elisa)
.then(() => Book.findByPk(book.id, { include: [Author] }))
.then((_book) => {
assertInstance(_book, Object.assign({ authors: [elisa] }, jsForDummiesBook));
})
));
it('should add relations between specified instance and source instance', () =>
Promise.all([
Book.create(jsForDummiesBook),
Author.create(elisa),
Author.create(brom),
]).then(([book, ...authors]) =>
book
.$add('authors', authors)
.then(() => Book.findByPk(book.id, { include: [Author] }))
.then((_book) => {
assertInstance(_book, Object.assign({ authors: [elisa, brom] }, jsForDummiesBook));
})
));
it('should not override previous relations', () =>
Promise.all([
Book.create(jsForDummiesBook),
Author.create(elisa),
Author.create(brom),
]).then(([book, _elisa, _brom]) =>
book
.$add('author', _elisa)
.then(() => Book.findByPk(book.id, { include: [Author] }))
.then((_book) => {
assertInstance(_book, Object.assign({ authors: [elisa] }, jsForDummiesBook));
})
// now we add another author
.then(() => book.$add('author', _brom))
.then(() => Book.findByPk(book.id, { include: [Author] }))
.then((_book) => {
// ... and check, if both authors exist
assertInstance(_book, Object.assign({ authors: [elisa, brom] }, jsForDummiesBook));
})
));
});
describe('$create', () => {
it('should create new instance and add relation between new instance and source instance (has many)', () =>
Book.create(jsForDummiesBook).then((book) =>
book
.$create('author', elisa)
.then((author) => {
assertInstance(author, elisa);
})
.then(() => Book.findByPk(book.id, { include: [Author] }))
.then((_book) => {
assertInstance(_book, Object.assign({ authors: [elisa] }, jsForDummiesBook));
})
));
it('should create new instance and add relation between new instance and source instance (belongs to)', () =>
Author.create(elisa).then((author) =>
author
.$create('book', jsForDummiesBook)
.then((book) => {
assertInstance(book, jsForDummiesBook);
})
.then(() => Author.findByPk(author.id, { include: [Book] }))
.then((_author) => {
assertInstance(_author, Object.assign({ books: [jsForDummiesBook] }, elisa));
})
));
});
describe('$has', () => {
it('should return true due to relation between specified instances and source instance', () =>
Book.create(sherlockHolmesBook, { include: [Author] }).then((book) =>
Book.findByPk(book.id)
.then((_book) => _book.$has('authors', book.authors))
.then((result) => {
expect(result).to.be.true;
})
));
it('should return false due to no relation between specified instance and source instance', () =>
Promise.all([
Book.create(sherlockHolmesBook, { include: [Author] }),
Author.create(elisa),
]).then(([book, author]) =>
Book.findByPk(book.id)
.then((_book) => _book.$has('authors', author))
.then((result) => {
expect(result).to.be.false;
})
));
});
describe('$count', () => {
it('should return number of specified relations', () =>
Book.create(sherlockHolmesBook, { include: [Author] }).then((book) =>
Book.findByPk(book.id)
.then((_book) => _book.$count('authors'))
.then((result) => {
expect(result).to.equal(sherlockHolmesBook.authors.length);
})
));
it('should return 0, since source instance has no relations', () =>
Author.create(elisa).then((author) =>
Author.findByPk(author.id)
.then((_author) => _author.$count('books'))
.then((result) => {
expect(result).to.equal(0);
})
));
});
describe('$remove', () => {
it('should remove relation between specified instance and source instance', () =>
Book.create(sherlockHolmesBook, { include: [Author] }).then((book) =>
Book.findByPk(book.id, { include: [Author] })
.then((_book) => {
assertInstance(_book, sherlockHolmesBook);
return _book.$remove('author', _book.authors[0]);
})
.then(() => Book.findByPk(book.id, { include: [Author] }))
.then((_book) => {
assertInstance(_book, {
title: sherlockHolmesBook.title,
authors: [sherlockHolmesBook.authors[1]],
});
})
));
it('should remove relations between specified instances and source instance', () =>
Author.create(julesVerne, { include: [Book] }).then((author) =>
Author.findByPk(author.id, { include: [Book] })
.then((_author) => {
assertInstance(_author, julesVerne);
return _author.$remove('books', _author.books);
})
.then(() => Author.findByPk(author.id, { include: [Book] }))
.then((_author) => {
assertInstance(_author, {
name: julesVerne.name,
});
})
));
});
}
describe('resolve foreign keys automatically', () => {
@Table
class Book extends BookModel {
@Column
title: string;
@BelongsToMany(() => Author, () => AuthorBook)
authors: Author[];
}
@Table
class AuthorBook extends Model {
@ForeignKey(() => Book)
bookId: number;
@ForeignKey(() => Author)
authorId: number;
}
@Table
class Author extends Model {
@Column
name: string;
@BelongsToMany(() => Book, () => AuthorBook)
books: Book[];
}
manyToManyTestSuites(Book, Author, AuthorBook);
});
describe('set foreign keys automatically via options', () => {
@Table
class Book4 extends BookModel {
@Column
title: string;
@BelongsToMany(() => Author4, {
through: () => AuthorBook4,
})
authors: Author4[];
}
@Table
class AuthorBook4 extends Model {
@ForeignKey(() => Book4)
bookId: number;
@ForeignKey(() => Author4)
authorId: number;
}
@Table
class Author4 extends Model {
@Column
name: string;
@BelongsToMany(() => Book4, {
through: () => AuthorBook4,
})
books: Book4[];
}
manyToManyTestSuites(Book4, Author4, AuthorBook4);
});
describe('set foreign keys explicitly', () => {
@Table
class Book2 extends BookModel {
@Column
title: string;
@BelongsToMany(() => Author2, 'AuthorBook2', 'bookId', 'authorId')
authors: Author2[];
}
@Table
class Author2 extends Model {
@Column
name: string;
@BelongsToMany(() => Book2, 'AuthorBook2', 'authorId', 'bookId')
books: Book2[];
}
manyToManyTestSuites(Book2, Author2);
});
describe('set foreign keys explicitly via options', () => {
@Table
class Book3 extends BookModel {
@Column
title: string;
@BelongsToMany(() => Author3, {
through: 'AuthorBook3',
foreignKey: 'bookId',
otherKey: 'authorId',
})
authors: Author3[];
}
@Table
class Author3 extends Model {
@Column
name: string;
@BelongsToMany(() => Book3, {
through: 'AuthorBook3',
foreignKey: 'authorId',
otherKey: 'bookId',
})
books: Book3[];
}
manyToManyTestSuites(Book3, Author3);
});
describe('set through model via through options', () => {
@Table
class Book66 extends Model {
@Column
title: string;
pages: any[];
@BelongsToMany(() => Author66, {
through: {
model: () => AuthorBook66,
},
})
authors: Author66[];
}
@Table
class AuthorBook66 extends Model {
@ForeignKey(() => Book66)
bookId: number;
@ForeignKey(() => Author66)
authorId: number;
}
@Table
class Author66 extends Model {
@Column
name: string;
@BelongsToMany(() => Book66, {
through: {
model: () => AuthorBook66,
},
})
books: Book66[];
}
manyToManyTestSuites(Book66, Author66, AuthorBook66);
});
describe('set through model string via through options', () => {
@Table
class Book66 extends Model {
@Column
title: string;
pages: any[];
@BelongsToMany(() => Author66, {
through: {
model: 'AuthorBook66',
},
foreignKey: 'bookId',
otherKey: 'authorId',
})
authors: Author66[];
}
@Table
class Author66 extends Model {
@Column
name: string;
@BelongsToMany(() => Book66, {
through: {
model: 'AuthorBook66',
},
foreignKey: 'authorId',
otherKey: 'bookId',
})
books: Book66[];
}
manyToManyTestSuites(Book66, Author66);
});
describe('ThroughOptions', () => {
@Table
class User77 extends Model {
@Column
name: string;
@BelongsToMany(() => User77, {
through: {
model: () => Subscription,
scope: {
targetType: 'user',
},
},
foreignKeyConstraint: true,
foreignKey: 'subscriberId',
otherKey: 'targetId',
constraints: false,
})
usersSubscribedTo: User77[];
}
@Table
class Subscription extends Model {
@PrimaryKey
@ForeignKey(() => User77)
@Column
subscriberId: number;
@PrimaryKey
@Column
targetId: number;
@Column
targetType: string;
}
before(() => sequelize.addModels([User77, Subscription]));
it('should set scope in pure sequelize association options', () => {
expect(User77['associations'].usersSubscribedTo['through'])
.to.have.property('scope')
.that.eqls({ targetType: 'user' });
});
});
it('Should throw error when trying to resolve associations with uninitialized Models', () => {
const _sequelize = createSequelize(false);
@Table
class UserFriend extends Model {}
@Table
class Friend extends Model {}
@Table
class User extends Model {
@BelongsToMany(() => Friend, () => UserFriend)
friend: Friend;
}
expect(() => _sequelize.addModels([User, Friend])).to.throw(
new RegExp('UserFriend has not been defined')
);
});
});
describe('One-to-one', () => {
const userWithAddress = {
name: 'Sherlock Holmes',
address: {
street: 'Bakerstreet',
city: 'London',
zipCode: '12345',
country: 'England',
},
};
const emancipatedAddress = {
street: 'Bakerstreet',
city: 'London',
zipCode: '12345',
country: 'England',
user: {
name: 'hng?',
},
};
const petersAddress = {
street: '738 Winter Garden DriveForest Hills',
city: 'New York',
zipCode: '12345',
country: 'United States',
};
const petersOtherAddress = {
street: '137 Chrystie Street',
city: 'New York',
zipCode: '12345',
country: 'United States',
};
class AbstractUser extends Model {
name: string;
address: AbstractAddress;
}
class AbstractAddress extends Model {
street: string;
zipCode: string;
city: string;
country: string;
userId: number;
user: AbstractUser;
}
function oneToOneTestSuites(User: typeof AbstractUser, Address: typeof AbstractAddress): void {
before(() => sequelize.addModels([User, Address]));
beforeEach(() => sequelize.sync({ force: true }));
it('should create models with specified relations', () => {
expect(User)
.to.have.property('associations')
.that.has.property('address')
.that.is.an.instanceOf(Association['HasOne'])
.and.has.property('foreignKey', 'userId');
expect(Address)
.to.have.property('associations')
.that.has.property('user')
.that.is.an.instanceOf(Association['BelongsTo'])
.and.has.property('foreignKey', 'userId');
});
it('should create models with generated functions on its prototype', () => {
expectAutoGeneratedFunctions(User, { singular: 'address' });
expectAutoGeneratedFunctions(Address, { singular: 'user' });
});
describe('create()', () => {
it('should create instances and relation between', () =>
Promise.all([
User.create(userWithAddress, { include: [Address] }).then((user) => {
assertInstance(user, userWithAddress);
}),
Address.create(emancipatedAddress, { include: [User] }).then((address) => {
assertInstance(address, emancipatedAddress);
}),
]));
it('should create instances without relation', () =>
User.create(userWithAddress).then((user) => {
expect(user).to.have.property('id').that.is.not.null;
expect(user).not.to.have.property('address');
}));
});
describe('findByPk()', () => {
it('should find instances with related instances', () =>
Promise.all([
User.create(userWithAddress, { include: [Address] })
.then((user) => User.findByPk(user.id, { include: [Address] }))
.then((user) => {
assertInstance(user, userWithAddress);
}),
Address.create(emancipatedAddress, { include: [User] })
.then((address) => Address.findByPk(address.id, { include: [User] }))
.then((address) => {
assertInstance(address, emancipatedAddress);
}),
]));
});
describe('findOne()', () => {
it('should find instances with related instances', () =>
Promise.all([
User.create(userWithAddress, { include: [Address] })
.then((user) => User.findOne({ include: [Address], where: { id: user.id } }))
.then((user) => {
assertInstance(user, userWithAddress);
}),
Address.create(emancipatedAddress, { include: [User] })
.then((address) => Address.findOne({ include: [User], where: { id: address.id } }))
.then((address) => {
assertInstance(address, emancipatedAddress);
}),
]));
});
describe('findAll()', () => {
it('should find instances with related instances', () =>
Promise.all([
User.create(userWithAddress, { include: [Address] })
.then((user) => User.findAll({ include: [Address], where: { id: user.id } }))
.then((users) => {
assertInstance(users[0], userWithAddress);
}),
Address.create(emancipatedAddress, { include: [User] })
.then((address) => Address.findAll({ include: [User], where: { id: address.id } }))
.then((addresses) => {
assertInstance(addresses[0], emancipatedAddress);
}),
]));
});
describe('$get', () => {
it('should get related instances of source instance', () =>
Promise.all([
User.create(userWithAddress, { include: [Address] })
.then((user) => User.findByPk(user.id))
.then((user) =>
user.$get('address').then((address) => {
assertInstance(address, userWithAddress.address);
})
),
Address.create(emancipatedAddress, { include: [User] })
.then((author) => Address.findByPk(author.id))
.then((author) =>
author.$get('user').then((user) => {
assertInstance(user, emancipatedAddress.user);
})
),
]));
});
describe('$set', () => {
it('should set relation between specified instances and source instance', () =>
Promise.all([User.create(elisa), Address.create(petersAddress)]).then(([user, address]) =>
user
.$set('address', address)
.then(() => User.findByPk(user.id, { include: [Address] }))
.then((_user) => {
assertInstance(_user, Object.assign({ address: petersAddress }, elisa));
})
));
it('should override previous relations', () =>
Promise.all([
User.create(elisa),
Address.create(petersAddress),
Address.create(petersOtherAddress),
]).then(([user, address1, address2]) =>
user
.$set('address', address1)
.then(() => User.findByPk(user.id, { include: [Address] }))
.then((_user) => {
assertInstance(_user, Object.assign({ address: petersAddress }, elisa));
})
// override previous authors
.then(() => user.$set('address', address2))
.then(() => User.findByPk(user.id, { include: [Address] }))
.then((_user) => {
// and check, if there are overridden
assertInstance(_user, Object.assign({ address: petersOtherAddress }, elisa));
})
));
});
describe('$create', () => {
it('should create new instance and add relation between new instance and source instance (has one)', () =>
User.create(elisa).then((user) =>
user
.$create('address', Object.assign({}, petersAddress))
.then((address) => {
assertInstance(address, petersAddress);
})
.then(() => User.findByPk(user.id, { include: [Address] }))
.then((_user) => {
assertInstance(_user, Object.assign({ address: petersAddress }, elisa));
})
));
it('should create new instance and add relation between new instance and source instance (belongs to)', () =>
Address.create(petersAddress).then((address) =>
address
.$create('user', Object.assign({}, elisa))
.then(() => Address.findByPk(address.id, { include: [User] }))
.then((_address) => {
assertInstance(_address, Object.assign({ user: elisa }, petersAddress));
})
));
});
}
describe('resolve foreign keys automatically', () => {
@Table
class User extends Model {
@Column
name: string;
@HasOne(() => Address)
address: any; // "any" because of order of execution (in separate classes this will work, I promise)
}
@Table
class Address extends Model {
@Column
street: string;
@Column
zipCode: string;
@Column
city: string;
@Column
country: string;
@ForeignKey(() => User)
userId: number;
@BelongsTo(() => User)
user: User;
}
oneToOneTestSuites(User, Address);
});
describe('set foreign keys explicitly', () => {
@Table
class User2 extends Model {
@Column
name: string;
@HasOne(() => Address2, 'userId')
address: any; // "any" because of order of execution (in separate classes this will work, I promise)
}
@Table
class Address2 extends Model {
@Column
street: string;
@Column
zipCode: string;
@Column
city: string;
@Column
country: string;
@BelongsTo(() => User2, 'userId')
user: User2;
userId: number;
}
oneToOneTestSuites(User2, Address2);
});
function oneToOneWithOptionsTestSuites(
User: typeof AbstractUser,
Address: typeof AbstractAddress,
alternateName = false,
onDeleteAction = 'CASCADE'
): void {
const foreignKey = alternateName ? 'user_id' : 'userId';
before(() => sequelize.addModels([User, Address]));
beforeEach(() => {
return sequelize.sync({ force: true });
});
it('should create models with specified relations', () => {
expect(User)
.to.have.property('associations')
.that.has.property('address')
.that.is.an.instanceOf(Association['HasOne'])
.which.includes({ foreignKey })
.and.has.property('foreignKeyAttribute')
.which.includes({ allowNull: false, name: foreignKey });
expect(User)
.to.have.property('associations')
.that.has.property('address')
.that.has.property('options')
.with.property('onDelete', onDeleteAction);
expect(Address)
.to.have.property('associations')
.that.has.property('user')
.that.is.an.instanceOf(Association['BelongsTo'])
.which.includes({ foreignKey })
.and.has.property('foreignKeyAttribute')
.which.includes({ allowNull: false, name: foreignKey });
expect(Address)
.to.have.property('associations')
.that.has.property('user')
.that.has.property('options')
.with.property('onDelete', onDeleteAction);
});
describe('create()', () => {
it('should fail creating instances that require a primary key', () => {
return Address.create(petersAddress, { include: [User] }).catch((err) =>
expect(err.message).to.match(
new RegExp(
`^notNull Violation: (${Address.name}.${foreignKey}|${foreignKey}) cannot be null$`
)
)
);
});
it('should create instances that require a parent primary key', () => {
return User.create(userWithAddress, { include: [Address] }).then((actual: any) => {
assertInstance(actual, userWithAddress);
});
});
});
}
describe('resolve foreign keys automatically with association options', () => {
const ON_DELETE_ACTION = 'SET NULL';
@Table
class User3 extends Model {
@Column
name: string;
@HasOne(() => Address3, { foreignKey: { allowNull: false }, onDelete: ON_DELETE_ACTION })
address: any;
}
@Table
class Address3 extends Model {
@Column
street: string;
@Column
zipCode: string;
@Column
city: string;
@Column
country: string;
@AllowNull(false)
@ForeignKey(() => User3)
@Column
userId: number;
@BelongsTo(() => User3, { foreignKey: { allowNull: false }, onDelete: ON_DELETE_ACTION })
user: User3;
}
oneToOneWithOptionsTestSuites(User3, Address3, false, ON_DELETE_ACTION);
});
describe('set foreign keys explicitly with association options', () => {
@Table
class User4 extends Model {
@Column
name: string;
@HasOne(() => Address4, {
foreignKey: { allowNull: false, name: 'user_id' },
onDelete: 'CASCADE',
})
address: any;
}
@Table
class Address4 extends Model {
@Column
street: string;
@Column
zipCode: string;
@Column
city: string;
@Column
country: string;
@BelongsTo(() => User4, {
foreignKey: { allowNull: false, name: 'user_id' },
onDelete: 'CASCADE',
})
user: User4;
userId: number;
}
oneToOneWithOptionsTestSuites(User4, Address4, true);
});
describe('set foreign keys explicitly via options', () => {
@Table
class User5 extends Model {
@Column
name: string;
@HasOne(() => Address5, { foreignKey: 'userId' })
address: any;
}
@Table
class Address5 extends Model {
@Column
street: string;
@Column
zipCode: string;
@Column
city: string;
@Column
country: string;
@BelongsTo(() => User5, { foreignKey: 'userId' })
user: User5;
userId: number;
}
oneToOneTestSuites(User5, Address5);
});
describe('set foreign keys explicitly with association options (allowNull: false on foreignKey)', () => {
@Table
class User6 extends Model {
@Column
name: string;
@HasOne(() => Address6, { foreignKey: { allowNull: false } })
address: any;
}
@Table
class Address6 extends Model {
@Column
street: string;
@Column
zipCode: string;
@Column
city: string;
@Column
country: string;
@ForeignKey(() => User6)
@AllowNull(false)
@Column({ field: 'user_id' })
userId: number;
@BelongsTo(() => User6, {
onDelete: 'CASCADE',
foreignKey: { allowNull: false },
})
user: User6;
}
oneToOneWithOptionsTestSuites(User6, Address6, false);
});
});
}); | the_stack |
import * as aws from 'aws-sdk';
import * as AWS from 'aws-sdk-mock';
import { hasAllTrafficEgress, SecurityGroupContextProviderPlugin } from '../../lib/context-providers/security-groups';
import { MockSdkProvider } from '../util/mock-sdk';
AWS.setSDK(require.resolve('aws-sdk'));
const mockSDK = new MockSdkProvider();
type AwsCallback<T> = (err: Error | null, val: T) => void;
afterEach(done => {
AWS.restore();
done();
});
describe('security group context provider plugin', () => {
test('errors when no matches are found', async () => {
// GIVEN
const provider = new SecurityGroupContextProviderPlugin(mockSDK);
AWS.mock('EC2', 'describeSecurityGroups', (_params: aws.EC2.DescribeSecurityGroupsRequest, cb: AwsCallback<aws.EC2.DescribeSecurityGroupsResult>) => {
cb(null, { SecurityGroups: [] });
});
// WHEN
await expect(
provider.getValue({
account: '1234',
region: 'us-east-1',
securityGroupId: 'sg-1234',
}),
).rejects.toThrow(/No security groups found/i);
});
test('looks up by security group id', async () => {
// GIVEN
const provider = new SecurityGroupContextProviderPlugin(mockSDK);
AWS.mock('EC2', 'describeSecurityGroups', (_params: aws.EC2.DescribeSecurityGroupsRequest, cb: AwsCallback<aws.EC2.DescribeSecurityGroupsResult>) => {
expect(_params).toEqual({ GroupIds: ['sg-1234'] });
cb(null, {
SecurityGroups: [
{
GroupId: 'sg-1234',
IpPermissionsEgress: [
{
IpProtocol: '-1',
IpRanges: [
{ CidrIp: '0.0.0.0/0' },
],
},
{
IpProtocol: '-1',
Ipv6Ranges: [
{ CidrIpv6: '::/0' },
],
},
],
},
],
});
});
// WHEN
const res = await provider.getValue({
account: '1234',
region: 'us-east-1',
securityGroupId: 'sg-1234',
});
// THEN
expect(res.securityGroupId).toEqual('sg-1234');
expect(res.allowAllOutbound).toEqual(true);
});
test('looks up by security group id and vpc id', async () => {
// GIVEN
const provider = new SecurityGroupContextProviderPlugin(mockSDK);
AWS.mock('EC2', 'describeSecurityGroups', (_params: aws.EC2.DescribeSecurityGroupsRequest, cb: AwsCallback<aws.EC2.DescribeSecurityGroupsResult>) => {
expect(_params).toEqual({
GroupIds: ['sg-1234'],
Filters: [
{
Name: 'vpc-id',
Values: ['vpc-1234567'],
},
],
});
cb(null, {
SecurityGroups: [
{
GroupId: 'sg-1234',
IpPermissionsEgress: [
{
IpProtocol: '-1',
IpRanges: [
{ CidrIp: '0.0.0.0/0' },
],
},
{
IpProtocol: '-1',
Ipv6Ranges: [
{ CidrIpv6: '::/0' },
],
},
],
},
],
});
});
// WHEN
const res = await provider.getValue({
account: '1234',
region: 'us-east-1',
securityGroupId: 'sg-1234',
vpcId: 'vpc-1234567',
});
// THEN
expect(res.securityGroupId).toEqual('sg-1234');
expect(res.allowAllOutbound).toEqual(true);
});
test('looks up by security group name', async () => {
// GIVEN
const provider = new SecurityGroupContextProviderPlugin(mockSDK);
AWS.mock('EC2', 'describeSecurityGroups', (_params: aws.EC2.DescribeSecurityGroupsRequest, cb: AwsCallback<aws.EC2.DescribeSecurityGroupsResult>) => {
expect(_params).toEqual({
Filters: [
{
Name: 'group-name',
Values: ['my-security-group'],
},
],
});
cb(null, {
SecurityGroups: [
{
GroupId: 'sg-1234',
IpPermissionsEgress: [
{
IpProtocol: '-1',
IpRanges: [
{ CidrIp: '0.0.0.0/0' },
],
},
{
IpProtocol: '-1',
Ipv6Ranges: [
{ CidrIpv6: '::/0' },
],
},
],
},
],
});
});
// WHEN
const res = await provider.getValue({
account: '1234',
region: 'us-east-1',
securityGroupName: 'my-security-group',
});
// THEN
expect(res.securityGroupId).toEqual('sg-1234');
expect(res.allowAllOutbound).toEqual(true);
});
test('looks up by security group name and vpc id', async () => {
// GIVEN
const provider = new SecurityGroupContextProviderPlugin(mockSDK);
AWS.mock('EC2', 'describeSecurityGroups', (_params: aws.EC2.DescribeSecurityGroupsRequest, cb: AwsCallback<aws.EC2.DescribeSecurityGroupsResult>) => {
expect(_params).toEqual({
Filters: [
{
Name: 'vpc-id',
Values: ['vpc-1234567'],
},
{
Name: 'group-name',
Values: ['my-security-group'],
},
],
});
cb(null, {
SecurityGroups: [
{
GroupId: 'sg-1234',
IpPermissionsEgress: [
{
IpProtocol: '-1',
IpRanges: [
{ CidrIp: '0.0.0.0/0' },
],
},
{
IpProtocol: '-1',
Ipv6Ranges: [
{ CidrIpv6: '::/0' },
],
},
],
},
],
});
});
// WHEN
const res = await provider.getValue({
account: '1234',
region: 'us-east-1',
securityGroupName: 'my-security-group',
vpcId: 'vpc-1234567',
});
// THEN
expect(res.securityGroupId).toEqual('sg-1234');
expect(res.allowAllOutbound).toEqual(true);
});
test('detects non all-outbound egress', async () => {
// GIVEN
const provider = new SecurityGroupContextProviderPlugin(mockSDK);
AWS.mock('EC2', 'describeSecurityGroups', (_params: aws.EC2.DescribeSecurityGroupsRequest, cb: AwsCallback<aws.EC2.DescribeSecurityGroupsResult>) => {
expect(_params).toEqual({ GroupIds: ['sg-1234'] });
cb(null, {
SecurityGroups: [
{
GroupId: 'sg-1234',
IpPermissionsEgress: [
{
IpProtocol: '-1',
IpRanges: [
{ CidrIp: '10.0.0.0/16' },
],
},
],
},
],
});
});
// WHEN
const res = await provider.getValue({
account: '1234',
region: 'us-east-1',
securityGroupId: 'sg-1234',
});
// THEN
expect(res.securityGroupId).toEqual('sg-1234');
expect(res.allowAllOutbound).toEqual(false);
});
test('errors when more than one security group is found', async () => {
// GIVEN
const provider = new SecurityGroupContextProviderPlugin(mockSDK);
AWS.mock('EC2', 'describeSecurityGroups', (_params: aws.EC2.DescribeSecurityGroupsRequest, cb: AwsCallback<aws.EC2.DescribeSecurityGroupsResult>) => {
expect(_params).toEqual({ GroupIds: ['sg-1234'] });
cb(null, {
SecurityGroups: [
{
GroupId: 'sg-1234',
IpPermissionsEgress: [
{
IpProtocol: '-1',
IpRanges: [
{ CidrIp: '10.0.0.0/16' },
],
},
],
},
{
GroupId: 'sg-1234',
IpPermissionsEgress: [
{
IpProtocol: '-1',
IpRanges: [
{ CidrIp: '10.0.0.0/16' },
],
},
],
},
],
});
});
// WHEN
await expect(
provider.getValue({
account: '1234',
region: 'us-east-1',
securityGroupId: 'sg-1234',
}),
).rejects.toThrow(/\More than one security groups found matching/i);
});
test('errors when securityGroupId and securityGroupName are specified both', async () => {
// GIVEN
const provider = new SecurityGroupContextProviderPlugin(mockSDK);
// WHEN
await expect(
provider.getValue({
account: '1234',
region: 'us-east-1',
securityGroupId: 'sg-1234',
securityGroupName: 'my-security-group',
}),
).rejects.toThrow(/\'securityGroupId\' and \'securityGroupName\' can not be specified both when looking up a security group/i);
});
test('errors when neither securityGroupId nor securityGroupName are specified', async () => {
// GIVEN
const provider = new SecurityGroupContextProviderPlugin(mockSDK);
// WHEN
await expect(
provider.getValue({
account: '1234',
region: 'us-east-1',
}),
).rejects.toThrow(/\'securityGroupId\' or \'securityGroupName\' must be specified to look up a security group/i);
});
test('identifies allTrafficEgress from SecurityGroup permissions', () => {
expect(
hasAllTrafficEgress({
IpPermissionsEgress: [
{
IpProtocol: '-1',
IpRanges: [
{ CidrIp: '0.0.0.0/0' },
],
},
{
IpProtocol: '-1',
Ipv6Ranges: [
{ CidrIpv6: '::/0' },
],
},
],
}),
).toBe(true);
});
test('identifies allTrafficEgress from SecurityGroup permissions when combined', () => {
expect(
hasAllTrafficEgress({
IpPermissionsEgress: [
{
IpProtocol: '-1',
IpRanges: [
{ CidrIp: '0.0.0.0/0' },
],
Ipv6Ranges: [
{ CidrIpv6: '::/0' },
],
},
],
}),
).toBe(true);
});
test('identifies lacking allTrafficEgress from SecurityGroup permissions', () => {
expect(
hasAllTrafficEgress({
IpPermissionsEgress: [
{
IpProtocol: '-1',
IpRanges: [
{ CidrIp: '10.0.0.0/16' },
],
},
],
}),
).toBe(false);
expect(
hasAllTrafficEgress({
IpPermissions: [
{
IpProtocol: 'TCP',
IpRanges: [
{ CidrIp: '0.0.0.0/0' },
],
},
],
}),
).toBe(false);
});
}); | the_stack |
import { TestToken } from "@connext/vector-contracts";
import {
DEFAULT_CHANNEL_TIMEOUT,
EngineEvents,
FullChannelState,
INodeService,
NodeError,
TransferNames,
} from "@connext/vector-types";
import { createlockHash, delay, getRandomBytes32, RestServerNodeService } from "@connext/vector-utils";
import { BigNumber, constants, Contract, providers, Wallet, utils } from "ethers";
import { formatEther, parseUnits } from "ethers/lib/utils";
import { Evt } from "evt";
import PriorityQueue from "p-queue";
import { env, getRandomIndex } from "../../utils";
import { config } from "./config";
import { logger } from "./setupServer";
const chainId = parseInt(Object.keys(env.chainProviders)[0]);
const provider = new providers.JsonRpcProvider(env.chainProviders[chainId]);
const wallet = Wallet.fromMnemonic(env.sugarDaddy).connect(provider);
const transferAmount = "1"; //utils.parseEther("0.00001").toString();
const agentBalance = utils.parseEther("0.0005").toString();
const routerBalance = utils.parseEther("0.15");
const walletQueue = new PriorityQueue({ concurrency: 1 });
let walletNonce;
const getWalletNonce = async () => {
if (!walletNonce) {
walletNonce = await wallet.getTransactionCount("pending");
}
return walletNonce;
};
const fundAddressToTarget = async (address: string, assetId: string, target: BigNumber): Promise<void> => {
const balance = await (assetId === constants.AddressZero
? provider.getBalance(address)
: new Contract(assetId, TestToken.abi, wallet).balanceOf(address));
if (balance.gte(target)) {
logger.debug(
{ balance: formatEther(balance), target: formatEther(target), assetId },
"Balance is greater than target, doing nothing",
);
// Nothing to deposit, return
return;
}
const diff = target.sub(balance);
logger.info({ assetId, value: formatEther(target), address }, "Funding address");
await fundAddress(address, assetId, diff);
};
const fundAddress = async (address: string, assetId: string, value: BigNumber): Promise<void> => {
// Make sure wallet has sufficient funds to deposit
const maxBalance = await (assetId === constants.AddressZero
? provider.getBalance(wallet.address)
: new Contract(assetId, TestToken.abi, wallet).balanceOf(wallet.address));
if (maxBalance.lt(value)) {
throw new Error(
`${wallet.address} has insufficient balance (${utils.formatEther(
maxBalance,
)}) of ${assetId} to deposit ${utils.formatEther(value)}`,
);
}
// Send funds to address using queue
const tx = await walletQueue.add(async () => {
logger.debug({ address, assetId, value: formatEther(value) }, "Funding onchain");
const gasPrice = (await provider.getGasPrice()).add(parseUnits("20", "wei"));
const nonce = await getWalletNonce();
const request: providers.TransactionResponse =
assetId === constants.AddressZero
? await wallet.sendTransaction({ to: address, value, gasPrice, nonce })
: await new Contract(assetId, TestToken.abi, wallet).transfer(address, value, { gasPrice, nonce });
logger.info({ nonce: request.nonce?.toString(), walletNonce }, "Sent");
walletNonce++;
await delay(1_000);
return request;
});
logger.debug({ hash: tx.hash, assetId, value: utils.formatEther(value) }, "Submitted deposit to chain");
await tx.wait();
const balance = await (assetId === constants.AddressZero
? provider.getBalance(address)
: new Contract(assetId, TestToken.abi, wallet).balanceOf(address));
logger.debug({ newBalance: formatEther(balance), address, assetId }, "Successfully funded");
};
// This class manages a single channel connected to roger.
// Many agents will be used throughout the test, and are
// managed cohesively in the `AgentContainer` class
export class Agent {
public channelAddress: string | undefined = undefined;
private constructor(
public readonly publicIdentifier: string,
public readonly signerAddress: string,
public readonly index: number,
private readonly rogerIdentifier: string,
private readonly nodeService: INodeService,
) {}
static async connect(
nodeService: INodeService,
rogerIdentifier: string,
index: number = getRandomIndex(),
minimumChannelBalance: { assetId: string; amount: BigNumber } = {
assetId: constants.AddressZero,
amount: BigNumber.from(agentBalance),
},
): Promise<Agent> {
// Create node on server at idx
// NOTE: can safely be called multiple times
const nodeRes = await nodeService.createNode({ index });
if (nodeRes.isError) {
throw nodeRes.getError()!;
}
if (nodeRes == undefined) {
throw Error("Node res undefined");
}
const { publicIdentifier, signerAddress } = nodeRes.getValue();
// Create the agent
const agent = new Agent(publicIdentifier, signerAddress, index, rogerIdentifier, nodeService);
// Get or setup the channel with the agent
await agent.setupChannel();
// Make sure there are sufficient funds in channel
await agent.fundChannelToTarget(minimumChannelBalance.assetId, minimumChannelBalance.amount);
return agent;
}
async createHashlockTransfer(
recipient: string,
assetId: string,
preImage: string = getRandomBytes32(),
routingId: string = getRandomBytes32(),
): Promise<{ channelAddress: string; transferId: string; routingId: string; preImage: string; start: number }> {
this.assertChannel();
// Create the transfer information
const lockHash = createlockHash(preImage);
// Create transfer
logger.debug({ recipient, sender: this.publicIdentifier, preImage, routingId }, "Creating transfer");
const createRes = await this.nodeService.conditionalTransfer({
publicIdentifier: this.publicIdentifier,
channelAddress: this.channelAddress!,
amount: transferAmount.toString(),
assetId,
recipient,
type: TransferNames.HashlockTransfer,
details: { lockHash, expiry: "0" },
meta: { routingId },
});
if (createRes.isError) {
logger.error({ creationError: createRes.getError() }, "Failed to create transfer");
process.exit(1);
// throw createRes.getError()!;
}
logger.info({ ...createRes.getValue() }, "Created transfer");
return { ...createRes.getValue(), preImage, routingId, start: Date.now() };
}
async resolveHashlockTransfer(
transferId: string,
preImage: string,
): Promise<{ channelAddress: string; transferId: string; routingId?: string; preImage: string }> {
this.assertChannel();
// Try to resolve the transfer
const resolveRes = await this.nodeService.resolveTransfer({
publicIdentifier: this.publicIdentifier,
channelAddress: this.channelAddress!,
transferResolver: { preImage },
transferId,
});
if (resolveRes.isError) {
throw resolveRes.getError()!;
}
logger.debug({ ...resolveRes.getValue() }, "Resolved transfer");
return { ...resolveRes.getValue()!, preImage };
}
async fundChannelToTarget(assetId: string, target: BigNumber): Promise<void> {
this.assertChannel();
// Get the channel to see if you need to deposit
const channel = await this.getChannel();
const assetIdx = channel.assetIds.findIndex((a) => a === assetId);
const balance = BigNumber.from(assetIdx === -1 ? "0" : channel.balances[assetIdx].amount[1]);
if (balance.gte(target)) {
// Nothing to deposit, return
return;
}
const diff = target.sub(balance);
await this.fundChannel(assetId, diff);
}
async fundChannel(assetId: string, value: BigNumber): Promise<void> {
this.assertChannel();
// Fund channel onchain
logger.info({ assetId, value: formatEther(value), channelAddress: this.channelAddress }, "Funding channel");
await fundAddress(this.channelAddress!, assetId, value);
// Reconcile deposit
const deposit = await this.nodeService.reconcileDeposit({
assetId,
channelAddress: this.channelAddress!,
publicIdentifier: this.publicIdentifier,
});
if (deposit.isError) {
throw deposit.getError()!;
}
logger.debug({ ...deposit.getValue() }, "Reconciled deposit");
}
async getChannel(): Promise<FullChannelState> {
// Try to get the channel
const channelRes = await this.nodeService.getStateChannelByParticipants({
publicIdentifier: this.publicIdentifier,
counterparty: this.rogerIdentifier,
chainId,
});
if (channelRes.isError) {
throw channelRes.getError()!;
}
return channelRes.getValue()! as FullChannelState;
}
private async setupChannel(): Promise<string> {
// Try to get the channel
let error: NodeError | undefined = undefined;
try {
const channel = await this.getChannel();
// no error, exists, set + return channel addr
this.channelAddress = channel.channelAddress;
return channel.channelAddress;
} catch (e) {
error = e;
}
if (error && error.message !== "Channel not found") {
// Unknown error, do not setup
throw error;
}
// Setup the channel, did not exist previously
const setup = await this.nodeService.setup({
counterpartyIdentifier: this.rogerIdentifier,
chainId,
timeout: DEFAULT_CHANNEL_TIMEOUT.toString(),
publicIdentifier: this.publicIdentifier,
});
if (setup.isError) {
throw setup.getError()!;
}
const { channelAddress } = setup.getValue();
logger.debug({ channelAddress }, "Setup channel");
this.channelAddress = channelAddress;
return channelAddress;
}
private assertChannel() {
// Ensure channel has been setup
if (!this.channelAddress) {
throw new Error(`No channel setup for ${this.signerAddress}`);
}
}
}
// This class manages multiple agents within the context of a test
type TransferInformation = {
preImage: string;
start: number;
end?: number;
error?: string;
};
export type TransferCompletedPayload = {
cancelled: boolean;
transferId: string;
routingId: string;
sendingAgent: string;
cancellationReason?: string;
};
export class AgentManager {
public readonly transferInfo: {
[routingId: string]: TransferInformation;
} = {};
public transfersCompleted: Evt<TransferCompletedPayload> = Evt.create<TransferCompletedPayload>();
private constructor(
public readonly roger: string,
public readonly routerIdentifier: string,
public readonly routerService: INodeService,
public readonly agents: Agent[] = [],
public readonly agentService: INodeService,
) {}
static async connect(
agentService: RestServerNodeService,
enableAutomaticResolution: boolean = true,
): Promise<AgentManager> {
// First, create + fund roger onchain
logger.debug({ url: env.rogerUrl });
const routerService = await RestServerNodeService.connect(
env.rogerUrl,
logger.child({ module: "Router" }),
undefined,
0,
);
const routerConfig = await routerService.getConfig();
if (routerConfig.isError) {
throw routerConfig.getError()!;
}
const { signerAddress: router, publicIdentifier: routerIdentifier } = routerConfig.getValue()[0];
// Fund roger
await fundAddressToTarget(router, constants.AddressZero, routerBalance);
// Create all agents needed
// First, get all nodes that are active on the server
const initialAgents = await agentService.getConfig();
if (initialAgents.isError) {
throw initialAgents.getError()!;
}
const registeredAgents = initialAgents.getValue();
let indices: number[] = [];
if (registeredAgents.length > config.numAgents) {
// Too many agents already registered on service
// only use a portion of the registered agents
indices = registeredAgents.slice(0, config.numAgents).map((r) => r.index);
} else {
// Must create more agents
const toCreate = config.numAgents - registeredAgents.length;
indices = registeredAgents.map((r) => r.index).concat(Array(toCreate).fill(0).map(getRandomIndex));
// indices = Array(config.numAgents).fill(0).map(getRandomIndex);
}
const agents = await Promise.all(indices.map((i) => Agent.connect(agentService, routerIdentifier, i)));
// Create the manager
const manager = new AgentManager(router, routerIdentifier, routerService, agents, agentService);
// Automatically resolve any created transfers
if (enableAutomaticResolution) {
manager.setupAutomaticResolve();
}
// Setup transfer completed payload
manager.setupCompletedCallback();
return manager;
}
private setupCompletedCallback(): void {
this.agents.map((agent) => {
this.agentService.on(
EngineEvents.CONDITIONAL_TRANSFER_RESOLVED,
async (data) => {
const {
channelAddress,
transfer: { meta, initiator, transferId },
} = data;
const { routingId } = meta ?? {};
// Make sure there is a routingID
if (!routingId) {
logger.warn({ ...(meta ?? {}) }, "No routingId");
return;
}
if (agent.channelAddress !== channelAddress) {
logger.error(
{ agent: agent.channelAddress, channelAddress },
"Agent does not match data, should not happen!",
);
process.exit(1);
}
if (initiator !== agent.signerAddress) {
logger.debug(
{ initiator, agent: agent.signerAddress, channelAddress, transferId, routingId },
"Not initiator, not resolved",
);
return;
}
// Transfer was completed, post to evt
const cancelled = Object.values(data.transfer.transferResolver)[0] === constants.HashZero;
this.transfersCompleted.post({
routingId,
sendingAgent: agent.publicIdentifier,
transferId,
cancelled,
cancellationReason: cancelled ? meta.cancellationReason : undefined,
});
},
(data) => this.agents.map((a) => a.channelAddress).includes(data.channelAddress),
agent.publicIdentifier,
);
});
}
private setupAutomaticResolve(): void {
this.agents.map((agent) => {
const ret = this.agentService.on(
EngineEvents.CONDITIONAL_TRANSFER_CREATED,
async (data) => {
logger.debug({ ...data, agent: agent.publicIdentifier }, "Got conditional transfer created event");
const {
channelAddress,
transfer: { meta, initiator, transferId },
} = data;
const { routingId } = meta ?? {};
// Make sure there is a routingID
if (!routingId) {
logger.warn({ ...(meta ?? {}) }, "No routingID");
return;
}
if (agent.channelAddress !== channelAddress) {
logger.error(
{ agent: agent.channelAddress, channelAddress },
"Agent does not match data, should not happen!",
);
process.exit(1);
}
if (agent.signerAddress === initiator) {
// Agent is initiator, nothing to resolve
logger.debug({ transfer: transferId, agent: agent.signerAddress }, "Agent is initiator, doing nothing");
return;
}
// Creation comes from router forwarding, agent is responder
// Find the preImage
const { preImage } = this.transferInfo[routingId] ?? {};
if (!preImage) {
logger.error(
{
channelAddress,
transferId,
routingId,
transferInfo: this.transferInfo,
preImage,
},
"No preImage",
);
process.exit(1);
}
// Resolve the transfer
try {
logger.debug({ agent: agent.signerAddress, preImage, transfer: transferId }, "Resolving transfer");
await agent.resolveHashlockTransfer(transferId, preImage);
logger.info({ transferId, channelAddress, agent: agent.publicIdentifier, routingId }, "Resolved transfer");
} catch (e) {
logger.error(
{ transferId, channelAddress, agent: agent.publicIdentifier, error: e.message },
"Failed to resolve transfer",
);
process.exit(1);
}
return ret;
},
(data) => this.agents.map((a) => a.channelAddress).includes(data.channelAddress),
agent.publicIdentifier,
);
});
}
// Should return function to kill cyclical transfers
async startCyclicalTransfers(): Promise<() => Promise<void>> {
// Register listener that will resolve transfers once it is
// created
this.agents.map((_agent) => {
this.agentService.on(
EngineEvents.CONDITIONAL_TRANSFER_RESOLVED,
async (data) => {
logger.debug(
{ transferId: data.transfer.transferId, channelAddress: data.channelAddress },
"Caught conditional transfer resolved event",
);
// Create a new transfer to a random agent
const { channelAddress, transfer } = data;
// Find the agent from the recipient in routing meta
const { routingId } = transfer.meta;
// Make sure there is a routingID
if (!routingId) {
logger.debug({}, "No routingId");
return;
}
// Add timestamp on resolution
this.transferInfo[routingId].end = Date.now();
// If it was cancelled, mark as failure
if (Object.values(data.transfer.transferResolver)[0] === constants.HashZero) {
logger.warn(
{
transferId: transfer.transferId,
channelAddress,
cancellationReason: transfer.meta.cancellationReason,
},
"Transfer cancelled",
);
this.transferInfo[routingId].error = transfer.meta.cancellationReason ?? "Cancelled";
}
const agent = this.agents.find((a) => a.channelAddress && a.channelAddress === data.channelAddress);
if (!agent) {
logger.error(
{ channelAddress, agents: this.agents.map((a) => a.channelAddress).join(",") },
"No agent found to resolve",
);
process.exit(1);
}
// Only create a new transfer IFF you resolved it
if (agent.signerAddress === transfer.initiator) {
logger.debug(
{
transfer: transfer.transferId,
initiator: transfer.initiator,
responder: transfer.responder,
agent: agent.signerAddress,
},
"Agent is initiator, doing nothing",
);
return;
}
// Create new transfer to continue cycle
const receiver = this.getRandomAgent(agent);
try {
const { preImage, routingId, start } = await agent.createHashlockTransfer(
receiver.publicIdentifier,
constants.AddressZero,
);
this.transferInfo[routingId] = { ...(this.transferInfo[routingId] ?? {}), preImage, start };
} catch (e) {
logger.error(
{ error: e.message, agent: agent.publicIdentifier, channelAddress },
"Failed to create new transfer",
);
process.exit(1);
}
},
(data) => {
const channels = this.agents.map((a) => a.channelAddress);
return channels.includes(data.channelAddress);
},
_agent.publicIdentifier,
);
});
// Create some transfers to start cycle
logger.info({ agents: this.agents.length, config: { ...config } }, "Starting transfers");
const sender = this.getRandomAgent();
for (const agent of this.agents) {
if (agent.publicIdentifier === sender.publicIdentifier) {
logger.debug({}, "Is sender, skipping");
continue;
}
const { preImage, routingId, start } = await sender.createHashlockTransfer(
agent.publicIdentifier,
constants.AddressZero,
);
this.transferInfo[routingId] = { ...(this.transferInfo[routingId] ?? {}), preImage, start };
}
const kill = () =>
new Promise<void>(async (resolve, reject) => {
try {
this.agentService.off(EngineEvents.CONDITIONAL_TRANSFER_CREATED);
this.agentService.off(EngineEvents.CONDITIONAL_TRANSFER_RESOLVED);
// Wait just in case
await delay(5_000);
this.printTransferSummary();
resolve();
} catch (e) {
reject(e.message);
}
});
return kill;
}
// Creates multiple transfers in a single channel
async createMultipleTransfersWithSameParties(): Promise<() => Promise<void>> {
// Create some transfers to start cycle
logger.info({ agents: this.agents.length, config: { ...config } }, "Starting transfer creation");
const agent = this.getRandomAgent();
const recipient = this.getRandomAgent(agent);
const transfers: { transferId: string; elapsed: number }[] = [];
this.agentService.on(
EngineEvents.CONDITIONAL_TRANSFER_CREATED,
async (data) => {
// Create a new transfer
const start = Date.now();
const { transferId } = await agent.createHashlockTransfer(recipient.publicIdentifier, constants.AddressZero);
transfers.push({ transferId, elapsed: Date.now() - start });
},
(data) => data.bobIdentifier === agent.publicIdentifier,
agent.publicIdentifier,
);
const start = Date.now();
const { transferId } = await agent.createHashlockTransfer(recipient.publicIdentifier, constants.AddressZero);
transfers.push({ transferId, elapsed: Date.now() - start });
const kill = () =>
new Promise<void>(async (resolve, reject) => {
try {
this.agentService.off(EngineEvents.CONDITIONAL_TRANSFER_CREATED);
// Wait just in case
await delay(5_000);
// print summary of transfers created
const number = transfers.length;
const first = transfers[0].elapsed;
const last = transfers[transfers.length - 1].elapsed;
const toLog = transfers
.map((info, idx) => {
if (idx % 20 === 0) {
return { active: idx, elapsed: info.elapsed };
}
return undefined;
})
.filter((x) => !!x);
logger.warn(
{ transfers: number, latestElapsed: last, firstElapsed: first, intermittent: toLog },
"Transfer summary",
);
resolve();
} catch (e) {
reject(e.message);
}
});
return kill;
}
public printTransferSummary(): void {
const times = Object.entries(this.transferInfo)
.map(([routingId, transfer]) => {
if (!transfer.end) {
return undefined;
}
return transfer.end - transfer.start;
})
.filter((x) => !!x) as number[];
const total = times.reduce((a, b) => a + b, 0);
const average = total / times.length;
const longest = times.sort((a, b) => b - a)[0];
const shortest = times.sort((a, b) => a - b)[0];
const errored = Object.entries(this.transferInfo)
.map(([routingId, transfer]) => {
if (transfer.error) {
return transfer.error;
}
return undefined;
})
.filter((x) => !!x);
logger.info(
{
errors: errored,
agents: this.agents.length,
average,
longest,
shortest,
created: Object.entries(this.transferInfo).length,
completed: times.length,
cancelled: errored.length,
},
"Transfer summary",
);
}
public getRandomAgent(excluding?: Agent): Agent {
const filtered = excluding
? this.agents.filter((n) => n.publicIdentifier !== excluding.publicIdentifier)
: [...this.agents];
if (filtered.length === 0) {
logger.error(
{ node: excluding, agents: this.agents.map((n) => n.publicIdentifier).join(",") },
"Could not get random counterparty",
);
throw new Error("Failed to get counterparty");
}
return filtered[Math.floor(Math.random() * filtered.length)];
}
} | the_stack |
import { Router } from 'express';
import asyncHandler from 'express-async-handler';
const router: Router = Router();
import { Operations, Repository } from '../business';
import { ErrorHelper, getProviders } from '../transitional';
import { AuditLogRecord } from '../entities/auditLogRecord/auditLogRecord';
import { daysInMilliseconds } from '../utils';
import { AuditEvents } from '../entities/auditLogRecord';
import { GitHubRepositoryPermission } from '../entities/repositoryMetadata/repositoryMetadata';
import { IGitHubIdentity, IndividualContext } from '../user';
import { IMail } from '../lib/mailProvider';
import { ReposAppRequest, UserAlertType } from '../interfaces';
const validDaysBeforeNow = 21;
interface IHaveUndoCandiates extends ReposAppRequest {
undoOperations: IUndoEntry[];
}
interface IUndoOutcome {
message?: string;
warnings?: string[];
localUrl?: string;
}
interface IUndoEntry {
title?: string;
operation: AuditLogRecord;
supported: boolean;
notSupportedMessage?: string;
eventDescription?: string;
undoDescription?: string;
undo?: () => Promise<IUndoOutcome>;
}
function filterToRecentEvents(eventList: AuditLogRecord[], now: Date, validAfter: Date) {
return eventList.filter(entry => {
if (!entry.created) {
return false;
}
const created = new Date(entry.created);
if (created > now) {
return false;
}
if (created < validAfter) {
return false;
}
return true;
});
}
function actorIdentityFromRecord(record: AuditLogRecord): string {
if (record.actorUsername && record.actorCorporateUsername) {
return `GitHub account ${record.actorUsername} linked to corporate user ${record.actorCorporateUsername}`;
} else if (record.actorUsername) {
return `GitHub account ${record.actorUsername}`;
} else {
return 'Unknown account';
}
}
function repositoryIdentityFromRecord(record: AuditLogRecord): string {
if (record.organizationName && record.repositoryName) {
return `GitHub repo ${record.repositoryName} in the GitHub organization ${record.organizationName}`;
} else if (record.repositoryName) {
return `GitHub repo ${record.repositoryName}`;
} else {
return 'Unknown repo';
}
}
function teamIdentityFromRecord(record: AuditLogRecord): string {
if (record.organizationName && record.teamName) {
return `GitHub team ${record.teamName} in the GitHub organization ${record.organizationName}`;
} else if (record.teamName) {
return `GitHub team ${record.teamName}`;
} else {
return 'unknown team name';
}
}
function finalizeUndoEvents(operations: Operations, identity: IGitHubIdentity, records: AuditLogRecord[]): IUndoEntry[] {
return records.map(record => {
const entry: IUndoEntry = {
operation: record,
supported: false,
};
switch (record.action) {
// Dropped collaborator admin on a repository
case AuditEvents.Repository.EditMember: {
entry.title = 'Repository permission edited';
if (record.additionalData?.changes?.permission?.from === 'admin') {
entry.title = 'Repo collaborator admin permission removed';
entry.supported = true;
entry.eventDescription = `${actorIdentityFromRecord(record)} edited their own permission to the ${repositoryIdentityFromRecord(record)}, removing their ability to administer settings and configure the repo.`;
entry.undoDescription = 'Undo will restore the ability of the GitHub user to administer the repository.';
entry.undo = undoRepoCollaboratorAdminRepoPermission.bind(null, operations, identity, entry);
}
break;
}
// Dropped own membership in a repo while an admin
case AuditEvents.Repository.RemoveMember:
case 'member.removed': {
entry.title = 'Removed collaborator from repo';
entry.title = 'Repo collaborator removed';
entry.supported = true;
entry.eventDescription = `${actorIdentityFromRecord(record)} removed themselves from the ${repositoryIdentityFromRecord(record)} while an admin, removing their ability to administer settings and configure the repo.`;
entry.undoDescription = 'Undo will restore the ability of the GitHub user to administer the repository.';
entry.undo = undoRepoCollaboratorAdminRepoPermission.bind(null, operations, identity, entry);
break;
};
case AuditEvents.Team.Edited: {
entry.title = 'Team permission edited'; // They dropped admin on a repository the team supports
if (record.additionalData?.changes?.repository?.permissions?.from?.admin === true) {
entry.title = 'Repo admin permission removed from a team';
entry.supported = true;
entry.eventDescription = `${actorIdentityFromRecord(record)} edited the ${teamIdentityFromRecord(record)} permission, removing the team's ability to administer settings and configure the repo.`;
entry.undoDescription = 'Undo will restore the ability of the team to administer the repository.';
entry.undo = undoTeamAdminRepoPermission.bind(null, operations, entry);
}
break;
}
default: {
break;
}
}
return entry;
});
}
function undoRepoCollaboratorAdminRepoPermission(operations: Operations, identity: IGitHubIdentity, entry: IUndoEntry) {
return undoRepoCollaboratorAdminRepoPermissionAsync(operations, identity, entry);
}
async function undoRepoCollaboratorAdminRepoPermissionAsync(operations: Operations, identity: IGitHubIdentity, entry: IUndoEntry): Promise<IUndoOutcome> {
const operation = entry.operation;
if (!operation) {
throw new Error('No operation');
}
if (operation.action !== AuditEvents.Repository.EditMember && operation.action !== 'member.removed' && operation.action !== AuditEvents.Repository.RemoveMember) {
throw new Error('Unsupported action');
}
if (operation.action === AuditEvents.Repository.EditMember && operation.additionalData?.changes?.permission?.from !== 'admin') {
throw new Error('This action record is not of the correct format for restoring administrative collaborator permissions');
}
if (!operation.organizationId) {
throw new Error('No organization ID stored in the record');
}
const organization = operations.getOrganizationById(Number(operation.organizationId));
if (!operation.repositoryId) {
throw new Error('No repository ID');
}
let repository: Repository = null;
try {
repository = await organization.getRepositoryById(Number(operation.repositoryId));
} catch (getRepositoryError) {
if (ErrorHelper.IsNotFound(getRepositoryError)) {
throw new Error(`The repository ${operation.repositoryName} could not be retrieved by ID ${operation.repositoryId}. Has this repository been deleted?`);
}
throw getRepositoryError;
}
// Documenting decision:
// Users sometimes are forcefully removed when they go on leave, have other
// account issues, etc. By allowing recovery to _different_ user accounts,
// we can reduce the friction on this operation. We should still warn...
const warnings = [];
if (operation.userId != /* loose */ identity.id || operation.userUsername.toLowerCase() !== identity.username.toLowerCase()) {
warnings.push(`The authentication GitHub user identity, login=${identity.username} and id=${identity.id}, is different from the previous operation user, login=${operation.userUsername} id=${operation.userId}.`);
}
// Restore the permission
try {
await repository.addCollaborator(identity.username, GitHubRepositoryPermission.Admin);
} catch (restoreError) {
throw restoreError;
}
return {
message: `The repo ${repository.name} in the ${organization.name} GitHub org has re-authorized ${identity.username} to administer the repository.`,
localUrl: `${repository.baseUrl}permissions`,
warnings,
};
}
function undoTeamAdminRepoPermission(operations: Operations, entry: IUndoEntry) {
return undoTeamAdminRepoPermissionAsync(operations, entry);
}
async function undoTeamAdminRepoPermissionAsync(operations: Operations, entry: IUndoEntry): Promise<IUndoOutcome> {
const operation = entry.operation;
if (!operation) {
throw new Error('No operation');
}
if (operation.action !== AuditEvents.Team.Edited) {
throw new Error('Unsupported action');
}
if (operation.additionalData?.changes?.repository?.permissions?.from?.admin !== true) {
throw new Error('This action record is not of the correct format for restoring administrative permissions');
}
if (!operation.organizationId) {
throw new Error('No organization ID stored in the record');
}
const organization = operations.getOrganizationById(Number(operation.organizationId));
if (!operation.repositoryId) {
throw new Error('No repository ID');
}
let repository: Repository = null;
try {
repository = await organization.getRepositoryById(Number(operation.repositoryId));
} catch (getRepositoryError) {
if (ErrorHelper.IsNotFound(getRepositoryError)) {
throw new Error(`The repository ${operation.repositoryName} could not be retrieved by ID ${operation.repositoryId}. Has this repository been deleted?`);
}
throw getRepositoryError;
}
if (!operation.teamId) {
throw new Error('No team ID');
}
const teamId = Number(operation.teamId);
const team = organization.team(teamId);
try {
await team.getDetails();
} catch (getTeamError) {
if (ErrorHelper.IsNotFound(getTeamError)) {
throw new Error(`The team ${operation.teamName} could not be retrieved by ID ${operation.teamId}. Has the team been deleted?`);
}
throw getTeamError;
}
// Restore the permission
try {
await repository.setTeamPermission(teamId, GitHubRepositoryPermission.Admin);
} catch (restoreError) {
throw restoreError;
}
return {
message: `The team ${team.name} in the ${organization.name} GitHub org has been given back administrative access to the repository ${repository.full_name}.`,
localUrl: `${repository.baseUrl}permissions`,
};
}
router.use(asyncHandler(async function (req: IHaveUndoCandiates, res, next) {
const { operations } = getProviders(req);
if (!operations.allowUndoSystem) {
res.status(404);
return next(new Error('This feature is unavailable in this application instance'));
}
const auditLogRecordProvider = operations.providers.auditLogRecordProvider;
if (!auditLogRecordProvider) {
return next(new Error('Undo capability is not available for this site'));
}
const ghi = req.individualContext.getGitHubIdentity();
if (!ghi || !ghi.username) {
return next(new Error('GitHub identity required'));
}
try {
const now = new Date();
const before = new Date(now.getTime() - daysInMilliseconds(validDaysBeforeNow));
const undoResults = await auditLogRecordProvider.queryAuditLogForThirdPartyIdUndoOperations(ghi.id.toString());
const candidateUndoOperations = filterToRecentEvents(undoResults, now, before);
req.undoOperations = finalizeUndoEvents(operations, ghi, candidateUndoOperations);
} catch (error) {
return next(error);
}
return next();
}));
router.post('/', asyncHandler(async (req: IHaveUndoCandiates, res, next) => {
const { operations } = getProviders(req);
const insights = operations.insights;
const link = req.individualContext.link;
const githubId = req.individualContext.getGitHubIdentity().id;
const undoOperations = req.undoOperations;
const recordId = req.body.id;
if (!recordId) {
res.status(400);
return next(new Error('Missing event ID'));
}
const matchingEvents = undoOperations.filter(op => op.operation?.recordId === recordId);
if (!matchingEvents.length) {
res.status(400);
return next(new Error('Not a valid candidate event'));
}
const record = matchingEvents[0];
const operation = record.operation;
let isOK = false;
if (operation.userCorporateId) {
if (operation.userCorporateId !== link.corporateId) {
res.status(400);
return next(new Error('This event cannot be undone for your account due to its linked corporate ID'));
}
isOK = true;
} else if (operation.actorId) {
if (operation.actorId !== githubId) {
res.status(400);
return next(new Error('This event cannot be undone for your account due to its GitHub account ID'));
}
isOK = true;
}
if (!isOK) {
res.status(400);
return next(new Error('Processing cannot continue'));
}
if (!record.supported) {
return next(new Error(`This action type (${operation.action}) is not currently supported for undo operations. Record ID: ${operation.recordId}`));
}
if (!record.undo) {
return next(new Error('This operation is not currently supported for undo'));
}
try {
const result = await record.undo();
req.individualContext.webContext.saveUserAlert(result.message || 'OK', 'Undo operation completed', UserAlertType.Success);
if (result.warnings && result.warnings.length) {
req.individualContext.webContext.saveUserAlert(result.warnings.join('; '), 'Operation warnings', UserAlertType.Warning);
}
insights?.trackMetric({ name: 'UndoOperations', value: 1 });
nextTickAsyncSendMail(operations, req.individualContext, record, result);
return res.redirect(result.localUrl || '/');
} catch (undoError) {
insights?.trackException({ exception: undoError });
return next(undoError);
}
}));
router.get('/', asyncHandler(async (req: IHaveUndoCandiates, res, next) => {
const { operations } = getProviders(req);
const insights = operations.insights;
insights?.trackMetric({ name: 'UndoPageViews', value: 1 });
return req.individualContext.webContext.render({
view: 'undo',
title: 'Undo',
state: {
undoOperations: req.undoOperations,
},
});
}));
function nextTickAsyncSendMail(operations: Operations, context: IndividualContext, undoEntry: IUndoEntry, undoOutcome: IUndoOutcome) {
const insights = operations.insights;
process.nextTick(() => {
sendUndoMailNotification(operations, context, undoEntry, undoOutcome).then(ok => {
insights?.trackEvent({ name: 'UndoMailSent', properties: { recordId: undoEntry.operation.recordId } });
}).catch(error => {
insights?.trackException({ exception: error });
insights?.trackEvent({ name: 'UndoMailSendFailed', properties: { recordId: undoEntry.operation.recordId } });
});
});
}
async function sendUndoMailNotification(operations: Operations, context: IndividualContext, undoEntry: IUndoEntry, undoOutcome: IUndoOutcome) {
const operationsMails = [operations.getOperationsMailAddress()];
const ghi = context.getGitHubIdentity();
const link = context.link;
const details = {
thirdPartyUsername: ghi.username,
undoEntry,
undoOutcome,
operation: undoEntry.operation,
link,
mailAddress: null,
};
if (operationsMails) {
try {
const mailToOperations: IMail = {
to: operationsMails,
subject: `GitHub undo operation completed for ${ghi.username}`,
content: await operations.emailRender('undo', {
reason: (`A user just used the undo function on the site. As the operations contact for this system, you are receiving this e-mail.
This mail was sent to: ${operationsMails.join(', ')}`),
headline: 'Undo operation complete',
notification: 'information',
app: `${operations.config.brand.companyName} GitHub`,
isMailToOperations: true,
isMailToUser: false,
details,
}),
};
await operations.sendMail(mailToOperations);
} catch (mailIssue) {
console.dir(mailIssue);
}
}
if (!link) {
throw new Error('No link for the individual context, no mail can be sent');
}
try {
const mailAddress = await operations.getMailAddressFromCorporateUsername(link.corporateUsername);
if (mailAddress) {
details.mailAddress = mailAddress;
const companyName = operations.config.brand.companyName;
const mailToCreator: IMail = {
to: mailAddress,
subject: `GitHub undo operation completed for ${mailAddress}`,
content: await operations.emailRender('undo', {
reason: (`You just used the undo feature on the GitHub management site. This mail confirms the operation.
This mail was sent to: ${mailAddress} and also the GitHub administrators for the system.`),
headline: 'Undo',
notification: 'information',
app: `${companyName} GitHub`,
isMailToUser: true,
isMailToOperations: false,
details,
operationsMail: operationsMails.join(','),
}),
};
await operations.sendMail(mailToCreator);
}
} catch (noLinkOrEmail) {
console.dir(noLinkOrEmail);
}
}
export default router; | the_stack |
import assert from 'assert';
import * as Tp from 'thingpedia';
import * as ThingTalk from 'thingtalk';
import { Ast, Runtime } from 'thingtalk';
import MonitorRunner from './monitor_runner';
import { Timer, AtTimer, OnTimer } from './timers';
import DeviceView from '../devices/device_view';
import NotificationFormatter from '../../dialogue-agent/notifications/formatter';
import RestartableAsyncIterable from '../util/restartable_async_iterable';
import type AppExecutor from './app_executor';
import type Engine from '../index';
function extendParams(output : Record<string, unknown>,
input : Record<string, unknown>) {
for (const key in input) {
if (Object.prototype.hasOwnProperty.call(output, key))
continue;
output[key] = input[key];
}
}
export interface OutputDelegate {
done() : void;
output(outputType : string, outputValue : Record<string, unknown>) : void;
error(error : Error) : void;
}
type MaybePromise<T> = T|Promise<T>;
type ActionFunction = (params : Record<string, unknown>, env : ExecWrapper) => MaybePromise<unknown>;
type QueryFunctionResult = AsyncIterable<Record<string, unknown>>;
type QueryFunction = (params : Record<string, unknown>, hints : Runtime.CompiledQueryHints, env : ExecWrapper) => MaybePromise<QueryFunctionResult>;
function recursivelyComputeOutputType(kind : string, expr : Ast.Expression) : string {
if (expr instanceof Ast.InvocationExpression)
return kind + ':' + expr.invocation.channel;
if (expr instanceof Ast.ChainExpression)
return expr.expressions.map((exp) => recursivelyComputeOutputType(kind, exp)).join('+');
if (expr instanceof Ast.AggregationExpression)
return expr.operator + '(' + recursivelyComputeOutputType(kind, expr.expression) + ')';
if ('expression' in expr) // projection, index, slice
return recursivelyComputeOutputType(kind, (expr as ({ expression : Ast.Expression } & Ast.Expression)).expression);
throw new TypeError('Invalid query expression ' + expr);
}
// eslint-disable-next-line @typescript-eslint/ban-types
function isPlainObject(x : unknown) : x is object {
return typeof x === 'object' && x !== null &&
typeof (x as any).then !== 'function' &&
typeof (x as any).next !== 'function' &&
(Object.getPrototypeOf(x) === Object.prototype ||
Object.getPrototypeOf(x) === null);
}
/**
* Wrap a ThingTalk statement and provide access to the Engine.
*
* This is an implementation of {@link external:thingtalk.ExecEnvironment}
* suitable for running with the Genie engine.
*
* @package
*/
export default class ExecWrapper extends Runtime.ExecEnvironment {
engine : Engine;
app : AppExecutor;
format : NotificationFormatter;
private _programId : ThingTalk.Builtin.Entity;
private _outputDelegate : OutputDelegate;
private _trigger : MonitorRunner|Timer|AtTimer|OnTimer|null;
private _execCache : Array<[string, string, Record<string, unknown>, Array<Promise<QueryFunctionResult>>]>;
private _hooks : Array<() => void|Promise<void>>;
constructor(engine : Engine, app : AppExecutor, output : OutputDelegate) {
super();
this.format = new NotificationFormatter(engine);
this.engine = engine;
this.app = app;
this._programId = new ThingTalk.Builtin.Entity(this.app.uniqueId!, null);
this._outputDelegate = output;
this._trigger = null;
this._execCache = [];
this._hooks = [];
}
setOutput(delegate : OutputDelegate) {
this._outputDelegate = delegate;
}
get program_id() {
return this._programId;
}
/**
* Retrieve the unique ID of the conversation associated with this execution
* environment.
*
* This roughly corresponds to the ID of the session or speaker where the user
* is issuing the command.
*/
get conversation() {
return this.app.metadata.conversation;
}
get locale() {
return this.engine.platform.locale;
}
get timezone() {
return this.engine.platform.timezone;
}
endProgram() {
if (this._trigger)
this._trigger.end();
// otherwise just wait for the query/action to end
}
stopTrigger() {
if (this._trigger)
this._trigger.stop();
}
private _wrapClearCache<T>(asyncIterable : AsyncIterator<T>) : AsyncIterator<T> {
const self = this;
return {
async next() {
const value = await asyncIterable.next();
self.clearGetCache();
return value;
}
};
}
loadContext() : never {
throw new Error('$context is not implemented');
//return this.engine.platform.loadContext(info);
}
invokeTimer(base : Date, interval : number, frequency : number) : AsyncIterator<{ __timestamp : number }> {
const trigger = new Timer(base.getTime(), interval, frequency);
this._trigger = trigger;
trigger.start();
return this._wrapClearCache(trigger);
}
invokeAtTimer(time : ThingTalk.Builtin.Time[], expiration_date : Date|undefined) : AsyncIterator<{ __timestamp : number }> {
const trigger = new AtTimer(time, expiration_date, this.timezone);
this._trigger = trigger;
trigger.start();
return this._wrapClearCache(trigger);
}
invokeOnTimer(date : Date[]) : AsyncIterator<{ __timestamp : number}> {
const trigger = new OnTimer(date);
this._trigger = trigger;
trigger.start();
return this._wrapClearCache(trigger);
}
invokeMonitor(kind : string,
attrs : Record<string, string>,
fname : string,
params : Record<string, unknown>,
hints : Runtime.CompiledQueryHints) : AsyncIterator<[string, Record<string, unknown> & { __timestamp : number }]> {
const trigger = new MonitorRunner(this, new DeviceView(this.engine.devices, kind, attrs), fname, params, hints);
this._trigger = trigger;
trigger.start();
return this._wrapClearCache(trigger);
}
private _findInCache(kindKey : string, fnameKey : string, params : Record<string, unknown>) : Array<Promise<QueryFunctionResult>>|undefined {
for (const cached of this._execCache) {
const [kind, fname, cachedparams, result] = cached;
if (kind === kindKey && fname === fnameKey &&
ThingTalk.Builtin.equality(cachedparams, params))
return result;
}
return undefined;
}
clearGetCache() {
this._execCache = [];
}
private _getDevices(kind : string, attrs : Record<string, string>) : Tp.BaseDevice[] {
const deviceView = new DeviceView(this.engine.devices, kind, attrs, false);
deviceView.start();
return deviceView.values();
}
addExitProcedureHook(hook : () => void|Promise<void>) {
this._hooks.push(hook);
}
async exitProcedure(procid : number, procname : string) {
await super.exitProcedure(procid, procname);
for (const hook of this._hooks)
await hook();
this._hooks = [];
}
async *invokeQuery(kind : string,
attrs : Record<string, string>,
fname : string,
params : Record<string, unknown>,
hints : Runtime.CompiledQueryHints) : AsyncIterable<[string, Record<string, unknown>]> {
const devices = this._getDevices(kind, attrs);
let promises : Array<Promise<QueryFunctionResult>>;
const cached = this._findInCache(kind, fname, params);
if (cached) {
promises = cached;
} else {
const js_function_name = 'get_' + fname;
promises = devices.map(async (d) => {
return new RestartableAsyncIterable(await (d as unknown as Record<string, QueryFunction>)[js_function_name](params, hints, this));
});
// cache now, rather than when the query completes, because ThingTalk might
// invoke multiple queries in parallel
this._execCache.push([kind, fname, params, promises]);
}
for (let i = 0; i < promises.length; i++) {
const list = await promises[i];
const device = devices[i];
const outputType = device.kind + ':' + fname;
for await (const element of list) {
extendParams(element, params);
if (device.uniqueId !== device.kind)
element.__device = new Tp.Value.Entity(device.uniqueId!, device.name);
yield [outputType, element];
}
}
}
async *invokeDBQuery(kind : string, attrs : Record<string, string>, query : Ast.Program) : AsyncIterable<[string, Record<string, unknown>]> {
const devices = this._getDevices(kind, attrs) as any[]; // FIXME
const command = query.statements[0];
assert(command instanceof Ast.ExpressionStatement);
for (const device of devices) {
const outputType = recursivelyComputeOutputType(device.kind, command.expression);
for await (const result of await device.query(query, this))
yield [outputType, result];
}
}
readState(stateId : number) {
return this.app.readState(stateId);
}
async writeState(stateId : number, state : unknown) {
await this.app.writeState(stateId, state);
}
async *invokeAction(kind : string,
attrs : Record<string, string>,
fname : string,
params : Record<string, unknown>) : AsyncIterable<[string, Record<string, unknown>]> {
const devices = this._getDevices(kind, attrs);
const js_function_name = 'do_' + fname;
for (const d of devices) {
const outputType = d.kind + ':action/' + fname;
let result = await (d as unknown as Record<string, ActionFunction>)[js_function_name](params, this);
if (typeof result !== 'undefined' && !isPlainObject(result)) {
console.error(`${outputType} returned a value that is not an object and not undefined; this is deprecated and might break in the future`);
result = undefined;
}
if (result === undefined)
result = {};
extendParams(result as Record<string, unknown>, params);
if (result) {
if (d.uniqueId !== d.kind)
(result as Record<string, unknown>).__device = new Tp.Value.Entity(d.uniqueId!, d.name);
yield [outputType, result as Record<string, unknown>];
} else {
if (d.uniqueId !== d.kind) {
const __device = new Tp.Value.Entity(d.uniqueId!, d.name);
yield [outputType, { __device }];
} else {
yield [outputType, {}];
}
}
}
}
get icon() {
return this.app.icon;
}
async reportError(message : string, error : Error & { code ?: string }) : Promise<void> {
// cancellation errors should bubble up
if (error.code === 'ECANCELLED')
throw error;
console.error(message, error);
this.app.setError(error);
await this._outputDelegate.error(error);
}
async output(outputType : string, outputValues : Record<string, unknown>) : Promise<void> {
await this._outputDelegate.output(outputType, outputValues);
}
async formatEvent(outputType : string, outputValue : Record<string, unknown>, hint : string) : Promise<string> {
const formatted = await this.format.formatNotification(null, this.app.program, outputType, outputValue);
return formatted.map((x) => x.toLocaleString(this.engine.platform.locale)).join('\n');
}
} | the_stack |
'use strict';
const getInVis = require('../../util/immutable-utils').getInVis;
// TODO: derived fields?
const SPAN_FIELD_OPEN = '<span class="field source" contenteditable="false">';
const SPAN_SIGNAL_OPEN = '<span class="signal" contenteditable="false">';
const SPAN_CLOSE = '</span>';
const DATUM = 'datum.';
const SPAN_PREFIX = '<span class="';
const SPAN_RE = new RegExp('(' + SPAN_FIELD_OPEN + '|' + SPAN_SIGNAL_OPEN + ').*' + SPAN_CLOSE);
import * as React from 'react';
import * as rangy from 'rangy';
import ContentEditable from 'react-contenteditable';
import { connect } from 'react-redux';
import {AnyAction} from 'redux';
import {ThunkDispatch} from 'redux-thunk';
import {updateMarkProperty} from '../../actions/markActions';
import {setSignalPush} from '../../actions/interactionActions';
import {PrimType} from '../../constants/primTypes';
import {State} from '../../store';
import {Schema} from '../../store/factory/Dataset';
import {FieldDraggingStateRecord, DraggingStateRecord, SignalDraggingStateRecord} from '../../store/factory/Inspector';
import {InteractionRecord} from '../../store/factory/Interaction';
import {WidgetRecord} from '../../store/factory/Widget';
import {debounce} from 'throttle-debounce';
import {AutoCompleteList} from './AutoCompleteList';
interface OwnProps {
type: 'expr' | 'tmpl';
dsId: number,
primId: number,
primType: PrimType,
value: string,
updateFn: (evt) => void
}
interface OwnState {
searchPrefix: string;
keyCode: number;
}
interface StateProps {
fields: string[];
signals: string[];
dragging: DraggingStateRecord;
}
interface DispatchProps {
setDsId: (data: number) => void;
setSignalPush: (signalName: string, push: boolean, id: number) => void;
}
function mapStateToProps(reduxState: State, ownProps: OwnProps): StateProps {
const schema: Schema = getInVis(reduxState, 'datasets.' + ownProps.dsId + '._schema');
const interactions: InteractionRecord[] = reduxState.getIn(['vis', 'present', 'interactions']).valueSeq().toArray();
const interactionSignals = [].concat.apply([], interactions.filter(interaction => interaction.signals.length).map(interaction => interaction.signals.map(signal => signal.signal)));
const widgets: WidgetRecord[] = reduxState.getIn(['vis', 'present', 'widgets']).valueSeq().toArray();
const widgetSignals = [].concat.apply([], widgets.filter(widget => widget.signals.length).map(widget => widget.signals.map(signal => signal.signal)));
return {
fields: schema ? schema.keySeq().toJS() : [],
signals: interactionSignals.concat(widgetSignals),
dragging: reduxState.getIn(['inspector', 'dragging'])
};
}
function mapDispatchToProps(dispatch: ThunkDispatch<State, null, AnyAction>, ownProps: OwnProps) {
return {
setDsId(data: number) {
dispatch(updateMarkProperty({property: 'from', value: {data}}, ownProps.primId));
},
setSignalPush(signalName, push, id) {
dispatch(setSignalPush({[signalName]: push}, id));
}
}
}
class BaseAutoComplete extends React.Component<OwnProps & StateProps & DispatchProps, OwnState> {
constructor(props) {
super(props);
this.state = {
searchPrefix: null,
keyCode: null
}
}
private ref;
private getSelectedRangeWithinEl() {
const el = this.ref?.htmlEl;
var selectedRange = null;
var sel = rangy.getSelection();
var elRange = rangy.createRange();
elRange.selectNodeContents(el);
if (sel.rangeCount) {
selectedRange = sel.getRangeAt(0).intersection(elRange);
}
elRange.detach();
if (!selectedRange) {
//set the caret after the node for this range
if (el.childNodes?.length) {
const lastChild = el.childNodes[el.childNodes.length - 1];
elRange.setStartAfter(lastChild);
elRange.setEndAfter(lastChild);
}
else {
elRange.selectNodeContents(el);
}
//apply this range to the selection object
sel.removeAllRanges();
sel.addRange(elRange);
return elRange;
}
return selectedRange;
}
private createElementFromHTML(htmlString) {
var div = document.createElement('div');
div.innerHTML = htmlString.trim();
return div.firstChild;
}
private insertNodeAtCaret = (window as any).insertNodeAtCaret = (html) => {
const node = this.createElementFromHTML(html);
const sel = rangy.getSelection();
const range = this.getSelectedRangeWithinEl();
if (range) {
range.collapse(false);
range.insertNode(node);
range.collapseAfter(node);
sel.setSingleRange(range);
}
}
private replaceMaintainingCaret = (search, replace) => {
if (this.ref) {
[...this.ref.htmlEl.childNodes].forEach(node => {
if (node.nodeValue) {
const startIndex = node.nodeValue.indexOf(search);
const endIndex = startIndex + search.length;
if (startIndex === -1) {
return;
}
const range = document.createRange();
//Set the range to contain search text
range.setStart(node, startIndex);
range.setEnd(node, endIndex);
//Delete search text
range.deleteContents();
//Insert replace text
this.insertNodeAtCaret(replace);
}
})
}
}
private getHeadToCaret = (window as any).getHeadToCaret = () => {
if (this.ref) {
const selRange = this.getSelectedRangeWithinEl();
const newRange = document.createRange();
newRange.selectNodeContents(this.ref.htmlEl);
newRange.setEnd(selRange.startContainer, selRange.startOffset);
const fragment = newRange.cloneContents();
const temp = document.createElement("body");
temp.appendChild(fragment);
const html = temp.innerHTML;
return html;
}
}
public toHtml(expr) {
if (this.props.type === 'expr') return this.exprToHtml(expr);
if (this.props.type === 'tmpl') return this.tmplToHtml(expr);
}
public fromHtml(html) {
if (this.props.type === 'expr') return this.htmlToExpr(html);
if (this.props.type === 'tmpl') return this.htmlToTmpl(html);
}
private decodeHtml(html) {
var txt = document.createElement("textarea");
txt.innerHTML = html;
return txt.value;
}
public htmlToTmpl(html) {
const tokens = [];
let searchStr = html;
let position = searchStr.search(SPAN_RE);
while (position !== -1) {
tokens.push({
type: 'literal',
str: searchStr.substring(0, position)
});
const next = position + SPAN_PREFIX.length;
const nextStr = searchStr.substring(next);
const end = nextStr.search(SPAN_CLOSE);
if (nextStr.startsWith('signal')) {
tokens.push({
type: 'signal',
str: nextStr.substring(SPAN_SIGNAL_OPEN.length - SPAN_PREFIX.length, end)
});
}
else if (nextStr.startsWith('field')) {
tokens.push({
type: 'field',
str: nextStr.substring(SPAN_FIELD_OPEN.length - SPAN_PREFIX.length, end)
});
}
searchStr = nextStr.substring(end + SPAN_CLOSE.length);
position = searchStr.search(SPAN_RE);
}
tokens.push({
type: 'literal',
str: searchStr
});
return tokens.map(token => {
switch (token.type) {
case 'literal':
return JSON.stringify(this.decodeHtml(token.str.replace(/(<([^>]+)>)/gi, "")));
case 'signal':
return token.str;
case 'field':
return DATUM + token.str;
};
}).join(' + ');
}
public tmplToHtml(tmpl: string) {
const unjoin = tmpl.split(' + ')
return unjoin.map(str => {
if (str.startsWith('"') && str.endsWith('"')) {
return JSON.parse(str);
}
else if (str.startsWith(DATUM)) {
return SPAN_FIELD_OPEN + str.substring(DATUM.length) + SPAN_CLOSE;
}
return SPAN_SIGNAL_OPEN + str + SPAN_CLOSE;
}).join('');
}
public exprToHtml(str: string) {
const fields = this.props.fields;
const signals = this.props.signals;
const fieldRe = new RegExp(fields.map(s => DATUM + s).join('|'), 'g');
const signalRe = new RegExp(signals.join('|'), 'g');
str = str.replace(fieldRe, (match) => {
if (match) {
return SPAN_FIELD_OPEN + match.substring(DATUM.length) + SPAN_CLOSE
}
return match;
});
str = str.replace(signalRe, (match) => {
if (match) {
return SPAN_SIGNAL_OPEN + match + SPAN_CLOSE
}
return match;
});
return str;
};
private htmlToExpr = (html: string) => {
this.props.fields.forEach(fieldName => {
const fieldTag = SPAN_FIELD_OPEN + fieldName + SPAN_CLOSE;
html = html.replace(fieldTag, DATUM + fieldName);
});
const tagsStripped = html.replace(/(<([^>]+)>)/gi, "");
return this.decodeHtml(tagsStripped);
}
private debounceUpdate = debounce(500, () => {
if (this.ref) {
this.props.updateFn(this.fromHtml(this.ref.htmlEl.innerHTML));
}
})
private processTokens = (value) => {
this.props.fields.forEach(field => {
if (value.includes(`:${field}:`)) {
this.replaceMaintainingCaret(`:${field}:`, SPAN_FIELD_OPEN + field + SPAN_CLOSE);
}
});
this.props.signals.forEach(signal => {
if (value.includes(`:${signal}:`)) {
this.replaceMaintainingCaret(`:${signal}:`, SPAN_SIGNAL_OPEN + signal + SPAN_CLOSE);
}
});
}
public handleChange = (evt) => {
let value = evt.target.value || evt.target.innerHTML || '';
this.processTokens(value);
const sub = this.getHeadToCaret();
if (sub.match(/:\w*$/g)) {
const searchPrefix = sub.substring(sub.lastIndexOf(':') + 1);
this.setState({searchPrefix});
}
else {
this.setState({searchPrefix: null});
}
this.debounceUpdate();
};
public handleDragOver = (evt) => {
if (evt.preventDefault) {
evt.preventDefault(); // Necessary. Allows us to drop.
}
return false;
};
public handleDrop = () => {
const props = this.props;
let dragging = props.dragging;
if ((dragging as FieldDraggingStateRecord).dsId) {
dragging = dragging as FieldDraggingStateRecord;
const fieldName = dragging.fieldDef.name;
this.insertNodeAtCaret(SPAN_FIELD_OPEN + fieldName + SPAN_CLOSE);
if (!props.dsId && dragging.dsId && props.primType === 'marks') {
props.setDsId(dragging.dsId);
}
}
else if ((dragging as SignalDraggingStateRecord).signal) {
dragging = dragging as SignalDraggingStateRecord;
if (dragging.interactionId) {
this.props.setSignalPush(dragging.signal, true, dragging.interactionId);
}
const signalName = dragging.signal;
this.insertNodeAtCaret(SPAN_SIGNAL_OPEN + signalName + SPAN_CLOSE);
}
this.debounceUpdate();
};
public onAutoCompleteSelect = (value) => {
this.replaceMaintainingCaret(":" + this.state.searchPrefix, ":" + value + ":");
if (this.ref) {
this.processTokens(this.ref.htmlEl.innerHTML)
}
this.setState({searchPrefix: null});
this.debounceUpdate();
}
private onKeyDown = (e) => {
if (this.state.searchPrefix !== null) {
if (e.keyCode === 38 || e.keyCode === 40) {
e.preventDefault(); // capture up and down keys when the autocompletelist is open
this.setState({keyCode: e.keyCode});
}
if (e.keyCode === 13) {
this.setState({keyCode: e.keyCode});
}
}
}
private onKeyUp = () => {
this.setState({keyCode: null});
}
private getDropdownPosition() {
if (this.ref) {
const bounds = this.ref.htmlEl.getBoundingClientRect();
return {
top: bounds.bottom,
left: bounds.left,
minWidth: bounds.width - 2,
}
}
return null;
}
public render() {
return (
<div className="autocomplete-wrap" onDragOver={this.handleDragOver} onDrop={this.handleDrop} onKeyDown={this.onKeyDown} onKeyUp={this.onKeyUp}>
<ContentEditable ref={(ref) => {this.ref = ref}} className='autocomplete' html={this.toHtml(this.props.value || '')}
disabled={false} onChange={this.handleChange} onKeyDown={(e) => {if (e.key === 'Enter' || e.keyCode === 13) e.preventDefault()}} />
<AutoCompleteList style={this.getDropdownPosition()} fields={this.props.fields} signals={this.props.signals} searchPrefix={this.state.searchPrefix} keyCode={this.state.keyCode} onSelected={this.onAutoCompleteSelect}></AutoCompleteList>
</div>
);
}
};
export const AutoComplete = connect(mapStateToProps, mapDispatchToProps)(BaseAutoComplete); | the_stack |
import ts from 'typescript';
import { UnionType } from 'typescript';
import path from 'path';
import fs from 'fs';
import * as util from './util';
import * as dom from './dom';
import { isEqual } from 'lodash';
import * as envMod from './env';
import { env } from './env';
export { dom, util };
export interface PlainObj<T = any> {
[key: string]: T;
}
export interface CreateOptions {
dist?: string;
flags?: CreateDtsFlags;
}
export enum ExportFlags {
None = 0,
ExportEqual = 1 << 0,
Export = 1 << 1,
}
const NODE_MODULES = 'node_modules';
const TYPE_ROOT = '@types/';
const DTS_EXT = '.d.ts';
const SyntaxKind = ts.SyntaxKind;
const nodeModulesRoots = [
util.formatUrl(path.resolve(process.cwd(), `./${NODE_MODULES}`)),
];
const cwdPkgInfo = tryGetPackageInfo(process.cwd());
if (cwdPkgInfo && cwdPkgInfo.dir) {
nodeModulesRoots.push(util.formatUrl(path.resolve(cwdPkgInfo.dir, `./${NODE_MODULES}`)));
}
const fromLibRE = /typescript\/lib\/lib(\.\w+)*\.d\.ts$/;
// get typedom flags
export enum GetTypeDomFlags {
None = 0,
TypeLiteralInline = 1 << 0,
}
// the flags using to create dts
export enum CreateDtsFlags {
None = 0,
IgnorePrivate = 1 << 0,
}
// default build flags
export const defaultBuildFlags = ts.NodeBuilderFlags.AllowNodeModulesRelativePaths
| ts.NodeBuilderFlags.GenerateNamesForShadowedTypeParams
| ts.NodeBuilderFlags.NoTruncation
| ts.NodeBuilderFlags.UseTypeOfFunction;
export interface ExportListObj {
name: string;
node: ts.Node;
originalNode: ts.Node;
}
// get name for anonymous type
export function getAnonymousName() {
return `T${env.uniqId++}`;
}
// get type dom from node
export function getTypeDom(node?: ts.Node, flags: GetTypeDomFlags = GetTypeDomFlags.None) {
if (!node) return;
switch (node.kind) {
case SyntaxKind.StringKeyword:
case SyntaxKind.StringLiteral:
return dom.type.string;
case SyntaxKind.NumberKeyword:
case SyntaxKind.NumericLiteral:
return dom.type.number;
case SyntaxKind.LiteralType:
return getLiteralTypeDom(node as ts.LiteralTypeNode);
case SyntaxKind.BooleanKeyword:
case SyntaxKind.TrueKeyword:
case SyntaxKind.FalseKeyword:
return dom.type.boolean;
case SyntaxKind.VoidKeyword:
return dom.type.void;
case SyntaxKind.ObjectKeyword:
return dom.type.object;
case SyntaxKind.ThisKeyword:
return dom.type.this;
case SyntaxKind.TypeQuery:
return getTypeQueryTypeDom(node as ts.TypeQueryNode);
case SyntaxKind.ArrayType:
return getArrayTypeDom(node as ts.ArrayTypeNode);
case SyntaxKind.TypeLiteral:
return getTypeLiteralTypeDom(node as ts.TypeLiteralNode, flags);
case SyntaxKind.TypeReference:
return getReferenceTypeDom(node as ts.TypeReferenceNode);
case SyntaxKind.UnionType:
return getUnionTypeDom(node as ts.UnionTypeNode);
case SyntaxKind.IntersectionType:
return getIntersectionTypeDom(node as ts.IntersectionTypeNode);
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructorType:
return getFunctionTypeDom(node as ts.FunctionTypeNode);
case SyntaxKind.ImportType:
return getImportTypeDom(node as ts.ImportTypeNode);
case SyntaxKind.ParenthesizedType:
return getTypeDom((node as ts.ParenthesizedTypeNode).type);
case SyntaxKind.TypeOperator:
return getOperatorTypeDom(node as ts.TypeOperatorNode);
case SyntaxKind.AnyKeyword:
case SyntaxKind.NullKeyword:
case SyntaxKind.UndefinedKeyword:
default:
return dom.type.any;
}
}
// get type dom from type
export function getTypeDomFromType(type: ts.Type) {
if (type.flags & ts.TypeFlags.String) {
return dom.type.string;
} else if (type.flags & ts.TypeFlags.Number) {
return dom.type.number;
} else if (type.flags & ts.TypeFlags.Boolean) {
return dom.type.boolean;
} else if (type.flags & ts.TypeFlags.NumberLiteral) {
return (<ts.NumberLiteralType> type).value;
} else if (type.flags & ts.TypeFlags.StringLiteral) {
return JSON.stringify((<ts.StringLiteralType> type).value);
} else if (type.flags & ts.TypeFlags.Any) {
return dom.type.any;
} else if (type.flags & ts.TypeFlags.Null) {
return dom.type.null;
} else if (type.flags & ts.TypeFlags.Undefined) {
return dom.type.undefined;
} else if (type.flags & ts.TypeFlags.Void) {
return dom.type.void;
} else if (type.flags & ts.TypeFlags.Union) {
return dom.create.union((<UnionType> type).types.map(t => getTypeDomFromType(t)));
} else if (type.flags & ts.TypeFlags.Intersection) {
return dom.create.intersection((<ts.IntersectionType> type).types.map(t => getTypeDomFromType(t)));
}
const typeNode = env.checker.typeToTypeNode(type, undefined, defaultBuildFlags);
return getTypeDom(typeNode) || dom.type.any;
}
export function getOperatorTypeDom(node: ts.TypeOperatorNode) {
if (node.operator === SyntaxKind.KeyOfKeyword) {
const refer = getTypeDom(node.type);
return refer === dom.type.any ? refer : dom.create.keyof(refer);
}
return dom.type.any;
}
export function getCallSignatureDeclarationTypeDom(node: ts.CallSignatureDeclaration) {
return dom.create.callSignature(
getFunctionParametersTypeDom(node.parameters),
getTypeDom(node.type) || dom.type.void,
);
}
export function getLiteralTypeDom(typeNode: ts.LiteralTypeNode) {
return getTypeDom(typeNode.literal as ts.TypeNode);
}
export function getFunctionTypeDom(typeNode: ts.FunctionTypeNode) {
return dom.create.functionType(
getFunctionParametersTypeDom(typeNode.parameters),
getTypeDom(typeNode.type) || dom.type.void,
);
}
export function getTypeQueryTypeDom(typeNode: ts.TypeQueryNode) {
const referTypeDom = getReferenceTypeDomFromEntity(typeNode.exprName);
return referTypeDom ? dom.create.typeof(referTypeDom) : dom.type.any;
}
export function getJSDocTypeLiteralTypeDom(node: ts.JSDocTypeLiteral) {
const decl = dom.create.objectType([]);
const tags = node.jsDocPropertyTags;
(tags || []).forEach(tag => {
if (tag.typeExpression) {
const typeNode = tag.typeExpression.type;
const propName = util.getText(tag.name);
let propTypeDom: dom.ClassMember;
if (ts.isJSDocTypeLiteral(typeNode)) {
// jsdoc typedef
propTypeDom = dom.create.property(propName, getJSDocTypeLiteralTypeDom(typeNode));
} else {
const type = env.checker.getTypeFromTypeNode(typeNode);
// convert type dom by type.
const typeDom = getTypeDomFromType(type);
propTypeDom = dom.create.property(propName, typeDom);
}
if (tag.isBracketed) {
// [xxxx]
propTypeDom.flags! |= dom.DeclarationFlags.Optional;
}
addMemberToObj(decl, propTypeDom);
}
});
return decl;
}
export function getTypeLiteralTypeDom(typeNode: ts.TypeLiteralNode, flags: GetTypeDomFlags = GetTypeDomFlags.None) {
const members = typeNode.members;
const objectType = dom.create.objectType([]);
members.forEach(member => {
if (!member.name) {
if (ts.isCallSignatureDeclaration(member)) {
const typeDom = getCallSignatureDeclarationTypeDom(member);
addMemberToObj(objectType, typeDom, { dropDuplicate: true });
}
return;
}
const name = util.getText(member.name);
if (checkIsPrivate(member.name, name)) {
return;
}
const typeDom = getPropTypeDomByNode(name, member);
addJsDocToTypeDom(typeDom, member.name);
addMemberToObj(objectType, typeDom, { dropDuplicate: true });
});
// return plain object type if it has no member
if (!objectType.members.length) {
objectType.members.push(dom.create.indexSignature('key', 'string', dom.type.any));
}
if (flags & GetTypeDomFlags.TypeLiteralInline) {
return objectType;
} else {
const interfaceDeclare = createInterfaceWithCache(objectType.members);
return dom.create.namedTypeReference(interfaceDeclare);
}
}
export function getIntersectionTypeDom(typeNode: ts.IntersectionTypeNode) {
return dom.create.intersection(typeNode.types.map(node => getTypeDom(node)));
}
export function getUnionTypeDom(typeNode: ts.UnionTypeNode) {
return dom.create.union(typeNode.types.map(node => getTypeDom(node)));
}
// create deps in top env
export function createDepsByFile(file: string) {
// add all deps to top env
const topEnv = envMod.getTopEnv();
const deps = topEnv.deps[file];
if (deps) {
return deps;
}
// create new env
const customEnv = create(file);
// add declaration to namespace
const namespace = dom.create.namespace(customEnv.exportDefaultName!);
namespace.members.push(dom.create.comment(path.relative(process.cwd(), file)));
customEnv.declaration.fragment.forEach(decl => {
decl.flags = dom.DeclarationFlags.Export;
(decl as dom.DeclarationBase).namespace = namespace;
namespace.members.push(decl);
});
topEnv.declaration.fragment.push(namespace);
return topEnv.deps[file] = { env: customEnv, namespace };
}
// get import type dom
export function getImportTypeDom(typeNode: ts.ImportTypeNode) {
if (ts.isLiteralTypeNode(typeNode.argument) && ts.isStringLiteral(typeNode.argument.literal)) {
const importPath = typeNode.argument.literal.text;
const modName = getModNameByPath(importPath);
let exportName: string | undefined;
if (modName) {
exportName = collectImportModule(modName, undefined, importPath);
} else {
const filePath = util.resolveUrl(importPath);
if (filePath && path.extname(filePath) === '.js') {
exportName = createDepsByFile(filePath).namespace.name;
}
}
if (exportName) {
const referenceType = dom.create.namedTypeReference(exportName);
if (typeNode.isTypeOf) {
return dom.create.typeof(referenceType);
}
return referenceType;
}
}
return dom.type.any;
}
export function getReturnTypeFromDeclaration(declaration: ts.SignatureDeclaration) {
if (declaration.type) {
return declaration.type;
}
const signature = env.checker.getSignatureFromDeclaration(declaration);
if (!signature) {
return;
}
const type = env.checker.getReturnTypeOfSignature(signature!);
return env.checker.typeToTypeNode(type, undefined, defaultBuildFlags);
}
export function createClassDeclaration(node: ts.ClassLikeDeclaration, className?: string) {
className = createNameByDecl(node, className);
const classDeclaration = dom.create.class(className);
addJsDocToTypeDom(classDeclaration, node);
if (node.heritageClauses) {
// inherit
node.heritageClauses.forEach(clause => {
if (clause.types.length && clause.token === ts.SyntaxKind.ExtendsKeyword) {
const expr = clause.types[0].expression;
let typeNode;
if (ts.isIdentifier(expr)) {
typeNode = getTypeNodeAtLocation(expr);
} else if (ts.isPropertyAccessExpression(expr)) {
typeNode = getTypeNodeAtLocation(expr.name);
}
if (typeNode && ts.isTypeQueryNode(typeNode)) {
const reference = getReferenceTypeDomFromEntity(typeNode.exprName);
if (reference) classDeclaration.baseType = dom.create.class(reference.name);
}
}
});
}
eachPropertiesTypeDom<ts.ClassElement>(node.members, (name, member) => {
if (ts.isConstructorDeclaration(member)) {
// constructor
const constructorTypeDom = dom.create.constructor(getFunctionParametersTypeDom(member.parameters));
addJsDocToTypeDom(constructorTypeDom, member);
if (member.body && member.body.statements.length) {
// check statement in constructor
findAssignToThis(member.body.statements)
.forEach(({ name, node }) => {
addMemberToObj(classDeclaration, getPropTypeDomByNode(name, node), { dropDuplicate: true });
});
}
addMemberToObj(classDeclaration, constructorTypeDom);
return;
}
// skip without property name
if (!name) {
return;
}
const typeDom = getPropTypeDomByNode(name, member);
addJsDocToTypeDom(typeDom, member);
addMemberToObj(classDeclaration, typeDom, { dropDuplicate: true });
});
return classDeclaration;
}
// find this.xxx =
export function findAssignToThis(statements: ts.NodeArray<ts.Statement>) {
const assignList: Array<{ name: string; node?: ts.TypeNode }> = [];
util.findAssignByName(statements, 'this', ({ key, node }) => {
const propName = util.getText(key);
if (checkIsPrivate(node, propName)) {
return;
}
assignList.push({
name: propName,
node: getTypeNodeAtLocation(key),
});
});
return assignList;
}
export function addJsDocToTypeDom(typeDom: dom.DeclarationBase, originalNode: ts.Node) {
const jsDocs = util.getJSDocs(originalNode);
typeDom.jsDocComment = jsDocs
? jsDocs.map(doc => dom.create.jsDocComment(doc.getText()))
: undefined;
}
export function eachPropertiesTypeDom<T extends ts.ClassElement | ts.ObjectLiteralElement>(
nodeList: ts.NodeArray<T>,
callback: (propName: string, d: T) => void,
) {
const propertyNameList: string[] = [];
nodeList.forEach(member => {
const propertyName = util.getText(member.name);
if (propertyNameList.includes(propertyName)) {
return;
}
if (checkIsPrivate(member, propertyName)) {
return;
}
propertyNameList.push(propertyName);
callback(propertyName, member);
});
return propertyNameList;
}
// get property type dom by ts.Node
export function getPropTypeDomByNode(name: string, node?: ts.Node, flags: dom.DeclarationFlags = dom.DeclarationFlags.None) {
let typeDom: dom.ClassMember | undefined;
// check optional
const checkOptional = (type?: ts.Node, node?: ts.Node) => {
if (
(type && type.kind === SyntaxKind.UndefinedKeyword) ||
(node && util.hasQuestionToken(node))
) {
flags |= dom.DeclarationFlags.Optional;
}
};
if (name === '...' || !node) {
// ignore ...
return dom.create.property(name, dom.type.any, flags);
}
if (util.modifierHas(node, SyntaxKind.StaticKeyword)) {
flags |= dom.DeclarationFlags.Static;
}
if (ts.isTypeNode(node) || ts.isToken(node)) {
checkOptional(node);
const d = getTypeDom(node) || dom.type.any;
if (dom.util.isFunctionType(d)) {
typeDom = dom.create.method(name, d.parameters, d.returnType, flags);
} else {
typeDom = dom.create.property(name, d, flags);
}
} else if (ts.isMethodDeclaration(node) || ts.isMethodSignature(node)) {
// method property
const typeNode = getReturnTypeFromDeclaration(node);
typeDom = dom.create.method(
name,
getFunctionParametersTypeDom(node.parameters),
typeNode ? getTypeDom(typeNode) : dom.type.any,
flags,
);
} else if (ts.isGetAccessorDeclaration(node) || ts.isGetAccessor(node)) {
// getter
const typeNode = getTypeNodeAtLocation(node);
checkOptional(typeNode, node);
typeDom = dom.create.property(name, getTypeDom(typeNode) || dom.type.any, flags);
} else if (ts.isPropertyDeclaration(node) || ts.isPropertySignature(node)) {
// property declaration
checkOptional(node.type, node);
typeDom = dom.create.property(name, getTypeDom(node.type) || dom.type.any, flags);
}
typeDom = typeDom || dom.create.property(name, dom.type.any, flags);
return typeDom;
}
// get reference module by symbol
export function getReferenceModule(symbol: ts.Symbol) {
const symbolDeclaration = util.getDeclarationBySymbol(symbol);
if (!symbolDeclaration) return false;
const declarationFile = symbolDeclaration.getSourceFile().fileName;
const isFromLib = declarationFile.match(fromLibRE);
const isFromNodeModule = nodeModulesRoots.find(r => declarationFile.startsWith(r));
if (isFromLib) {
// build-in module
return;
} else if (declarationFile === env.sourceFile.fileName) {
// current module
return symbolDeclaration;
} else if (!isFromNodeModule) {
// custom module
return symbolDeclaration;
}
// find in global modules
let declaration: ts.Node = symbolDeclaration;
while (declaration && !ts.isSourceFile(declaration)) {
if (util.isDeclareModule(declaration)) {
// declare module "xxx" {}
return declaration;
}
declaration = declaration.parent;
}
return symbolDeclaration.getSourceFile();
}
// get reference typeDom by name
export function getReferenceTypeDomFromEntity(node: ts.EntityName) {
let referType: dom.ReferTypes | undefined;
let referenceModule: ts.Declaration | false | undefined;
const symbol = env.checker.getSymbolAtLocation(node) || util.getSymbol(node);
if (!symbol) {
const decl = util.tryFindDeclarationByName(node.getSourceFile(), node);
if (!decl) return;
referenceModule = decl;
} else {
referenceModule = getReferenceModule(symbol);
if (referenceModule === false) {
// ignore false
return;
}
}
let interfaceName = util.getText(node);
const checkAssignEqual = (node: ts.Node, name: string) => {
const symbol = util.getSymbol(node)!;
if (!symbol || !symbol.exports) return false;
const exportAssignment = symbol.exports.get(ts.InternalSymbolName.ExportEquals);
return exportAssignment &&
util.getText((exportAssignment.valueDeclaration as ts.ExportAssignment).expression) === name;
};
if (referenceModule) {
if (util.isDeclareModule(referenceModule)) {
// import from ambient modules
referType = dom.ReferTypes.ambient;
const modName = util.getText(referenceModule.name);
interfaceName = collectImportModule(modName, checkAssignEqual(referenceModule, interfaceName) ? undefined : interfaceName);
} else if (ts.isSourceFile(referenceModule)) {
// import from other jsFile
referType = dom.ReferTypes.custom;
const modName = getModNameByPath(referenceModule.fileName);
if (modName) {
interfaceName = collectImportModule(
modName,
checkAssignEqual(referenceModule, interfaceName) ? undefined : interfaceName,
referenceModule.fileName,
);
} else {
return;
}
} else {
// declaration
referType = dom.ReferTypes.declaration;
const cache = env.declareCache.find(({ node }) => node === referenceModule);
if (!cache) {
interfaceName = getDeclName(interfaceName);
env.declareCache.push({ node: referenceModule, name: interfaceName });
const decl = createDeclarationTypeDom(interfaceName, referenceModule);
if (decl) env.declaration.fragment.push(decl);
} else {
interfaceName = cache.name;
}
}
} else {
referType = dom.ReferTypes.lib;
}
return dom.create.namedTypeReference(interfaceName, referType);
}
export function createDeclarationTypeDom(name: string, node: ts.Declaration) {
let decl: dom.NamespaceMember | undefined;
if (ts.isClassLike(node)) {
decl = createClassDeclaration(node, name);
} else if (ts.isFunctionLike(node)) {
decl = createFunctionDeclaration(node, name);
} else if (ts.isVariableDeclaration(node)) {
decl = createVariableDeclaration(node, name);
} else if (ts.isPropertyAccessExpression(node)) {
decl = createDeclByPropertyAccess(node, name);
} else if (ts.isJSDocTypedefTag(node)) {
decl = createDeclByTypedefTag(node, name);
} else {
return;
}
return decl;
}
export function createDeclByPropertyAccess(node: ts.PropertyAccessExpression, name?: string) {
name = createNameByDecl(node, name);
return dom.create.const(name, getPropertyAccessTypeDom(node));
}
export function createNameByDecl(decl: ts.NamedDeclaration, name?: string) {
return name || (decl.name ? getDeclName(util.getText(decl.name)) : getAnonymousName());
}
export function createDeclByTypedefTag(node: ts.JSDocTypedefTag, name?: string) {
if (!node.typeExpression) {
return;
}
name = createNameByDecl(node, name);
// env.checker.getExportSymbolOfSymbol()
if (ts.isJSDocTypeLiteral(node.typeExpression)) {
const { members } = getJSDocTypeLiteralTypeDom(node.typeExpression);
createInterfaceWithCache(members, name);
return;
} else {
return dom.create.alias(name, getTypeDom(node.typeExpression.type));
}
}
export function getPropertyAccessTypeDom(node: ts.PropertyAccessExpression) {
const symbol = env.checker.getSymbolAtLocation(node.name);
if (symbol && symbol.exports) {
const members: dom.ObjectTypeMember[] = [];
symbol.exports.forEach(obj => {
const declaration = util.getDeclarationBySymbol(obj);
members.push(dom.create.property(
obj.getName(),
getTypeDom(declaration && getTypeNodeAtLocation(declaration)) || dom.type.any,
));
});
return createInterfaceWithCache(members);
} else {
const typeNode = getTypeNodeAtLocation((node.parent as ts.BinaryExpression).right);
return getTypeDom(typeNode) || dom.type.any;
}
}
export function getReferenceTypeDom(typeNode: ts.TypeReferenceNode) {
const ref = getReferenceTypeDomFromEntity(typeNode.typeName);
if (!ref) return dom.type.any;
// generic
const typeArguments = util.getTypeArguments(typeNode);
if (typeArguments && typeArguments.length) {
ref.typeParameters = typeArguments.map(type => getTypeDom(type) || dom.type.any);
}
return transformBuildInRefer(ref) || ref;
}
export function transformBuildInRefer(ref: dom.NamedTypeReference) {
if (ref.referType !== dom.ReferTypes.lib) {
return;
}
// build-in interface
switch (ref.name) {
case 'String':
return dom.type.string;
case 'Number':
return dom.type.number;
case 'Boolean':
return dom.type.boolean;
case 'Function':
return dom.create.functionType([
dom.create.parameter(
'args',
dom.type.array(dom.type.any),
dom.ParameterFlags.Rest,
),
], dom.type.any);
case 'Array':
return dom.type.array(ref.typeParameters[0] || dom.type.any);
default:
break;
}
}
export function getArrayTypeDom(typeNode: ts.ArrayTypeNode) {
return dom.create.array(getTypeDom(typeNode.elementType));
}
export function getFunctionParametersTypeDom(parameters: ts.NodeArray<ts.ParameterDeclaration>) {
const nameCache: PlainObj<number> = {};
const params: dom.Parameter[] = parameters.map(param => {
let type = param.type;
if (!type) {
type = getTypeNodeAtLocation(param);
}
let flags = (param.initializer || util.hasQuestionToken(param))
? dom.ParameterFlags.Optional
: dom.ParameterFlags.None;
if (param.dotDotDotToken) {
// ...args
flags |= dom.ParameterFlags.Rest;
}
// prevent duplicate
let name = util.getText(param.name) || getAnonymousName();
if (nameCache[name] === undefined) {
nameCache[name] = 0;
} else {
nameCache[name]++;
name = `${name}_${nameCache[name]}`;
}
return dom.create.parameter(
name,
getTypeDom(type) || dom.type.any,
flags,
);
});
return params;
}
// check whether has @private tag in jsDoc or variable name start with _
export function checkIsPrivate(obj: ts.Node, name?: string) {
if (env.flags & CreateDtsFlags.IgnorePrivate) {
return true;
}
return !!util.findJsDocTag(obj, 'private') ||
(name && name.startsWith('_'));
}
// add member to obj
export function addMemberToObj(
obj: dom.ClassDeclaration | dom.InterfaceDeclaration | dom.ObjectType,
member: dom.ClassMember | dom.ObjectTypeMember,
opt: { preInsert?: boolean; dropDuplicate?: boolean; } = {},
) {
const declaration = obj as dom.ClassDeclaration;
if ((member as dom.PropertyDeclaration).name) {
const index = declaration.members.findIndex(m => {
return (m as dom.PropertyDeclaration).name === (member as dom.PropertyDeclaration).name;
});
if (index >= 0) {
if (opt.dropDuplicate) {
return;
}
obj.members.splice(index, 1);
}
}
if (opt.preInsert) {
declaration.members.unshift(member as dom.ClassMember);
} else {
declaration.members.push(member as dom.ClassMember);
}
}
// try to find definition of function prototype
export function tryCreateFunctionAsClass(fnName: string, node: ts.FunctionDeclaration) {
const block = node.parent;
// try to find @constructor in jsDoc comment
const isConstructor = util.findJsDocTag(node, 'constructor');
let isPrototypeClass = !!isConstructor;
// find prototype assignment
if (ts.isBlock(block) || ts.isSourceFile(block)) {
const classDeclare = dom.create.class(fnName);
const originalName = util.getText(node.name);
const prototypeExpression = `${originalName}.prototype`;
util.findAssignByName(block.statements, [ prototypeExpression, originalName ], ({ name, key, value, node }) => {
const propName = util.getText(key);
const keyIsPrototype = propName === 'prototype';
const isStaticProp = name === originalName && !keyIsPrototype;
const isPrototypeAssignment = name === originalName && keyIsPrototype;
if (isPrototypeAssignment || name === prototypeExpression) {
isPrototypeClass = true;
}
if (isPrototypeAssignment) {
// xxx.prototype = {}
const typeNode = getTypeNodeAtLocation(value);
const typeDom = getTypeDom(typeNode, GetTypeDomFlags.TypeLiteralInline);
const cleanAssignment = () => {
classDeclare.members.length = 0;
classDeclare.baseType = undefined;
};
if (dom.util.isObjectType(typeDom)) {
// xxx.prototype = {}
cleanAssignment();
typeDom.members.forEach(member => addMemberToObj(classDeclare, member));
} else if (dom.util.isNamedTypeReference(typeDom)) {
// xxx.prototype = new XXX();
cleanAssignment();
classDeclare.baseType = dom.create.class(typeDom.name);
}
} else {
// xxx.prototype.xx =, xxx.xx =
if (checkIsPrivate(node, propName)) {
return;
}
const typeNode = getTypeNodeAtLocation(value);
const typeDom = getPropTypeDomByNode(propName, typeNode);
if (isStaticProp) typeDom.flags = dom.DeclarationFlags.Static;
addJsDocToTypeDom(typeDom, node);
addMemberToObj(classDeclare, typeDom);
}
});
if (isPrototypeClass) {
if (node.body && node.body.statements.length) {
// find this assignment in constructor
findAssignToThis(node.body.statements).forEach(({ name, node }) => {
addMemberToObj(classDeclare, getPropTypeDomByNode(name, node));
});
}
// treat function as constructor
addMemberToObj(classDeclare, dom.create.constructor(getFunctionParametersTypeDom(node.parameters)), {
preInsert: true,
});
return classDeclare;
}
}
}
export function createFunctionDeclaration(node: ts.FunctionLike, fnName?: string) {
let typeDom;
fnName = createNameByDecl(node, fnName);
if (ts.isFunctionDeclaration(node)) {
typeDom = tryCreateFunctionAsClass(fnName, node);
}
if (!typeDom) {
const signature = env.checker.getSignatureFromDeclaration(node)!;
const returnType = env.checker.getReturnTypeOfSignature(signature);
const returnTypeNode = env.checker.typeToTypeNode(returnType, undefined, defaultBuildFlags);
typeDom = dom.create.function(
fnName,
getFunctionParametersTypeDom(node.parameters),
getTypeDom(returnTypeNode) || dom.type.any,
);
}
addJsDocToTypeDom(typeDom, node);
return typeDom;
}
// try get package info by file url
function tryGetPackageInfo(fileUrl: string) {
let pkgPath;
let currentDir = path.dirname(fileUrl);
while (!fs.existsSync(pkgPath = path.resolve(currentDir, './package.json'))) {
currentDir = path.dirname(currentDir);
if (currentDir === '/' || currentDir.endsWith(NODE_MODULES)) {
pkgPath = null;
break;
}
}
if (pkgPath) {
const pkgInfo = JSON.parse(fs.readFileSync(pkgPath).toString());
return {
dir: currentDir,
pkgInfo,
};
}
return;
}
export function getModNameByPath(fileName: string) {
if (env.ambientModNames.includes(fileName)) {
return fileName;
}
fileName = util.normalizeDtsUrl(fileName);
if (!fileName.endsWith(DTS_EXT) || !fs.existsSync(fileName)) {
return;
}
const result = tryGetPackageInfo(fileName)! || {};
const basename = path.basename(fileName, DTS_EXT);
const pkgName = result.pkgInfo && result.pkgInfo.name;
if (pkgName && nodeModulesRoots.find(r => fileName.startsWith(r))) {
const name = result.pkgInfo.name;
const modName = name.startsWith(TYPE_ROOT) ? name.substring(TYPE_ROOT.length) : name;
const modPath = fileName.substring(result.dir.length + 1);
if (
(result.pkgInfo.main && path.basename(result.pkgInfo.main, '.js') === path.basename(modPath, '.d.ts')) ||
(!result.pkgInfo.main && modPath === 'index.d.ts') ||
result.pkgInfo.types === modPath
) {
return modName;
}
return `${modName}/${modPath.substring(0, modPath.length - DTS_EXT.length)}`;
} else {
const dir = path.dirname(fileName);
const from = util.formatUrl(path.relative(path.dirname(env.dist), path.join(dir, basename)));
return from.startsWith('.') ? from : `./${from}`;
}
}
// collect import modules
function collectImportModule(
name: string,
exportName?: string,
realPath?: string,
) {
realPath = realPath || name;
const importObj = env.importCache[realPath] = env.importCache[realPath] || {
default: undefined,
list: [],
realPath,
from: name,
} as envMod.ImportCacheElement;
if (exportName) {
let existImportObj = importObj.list.find(({ name }) => name === exportName);
if (!existImportObj) {
existImportObj = { name: exportName, as: getDeclName(exportName) };
importObj.list.push(existImportObj);
}
return existImportObj.as!;
} else {
if (!importObj.default) {
importObj.default = getDeclName(util.formatName(name));
}
return importObj.default!;
}
}
export function getTypeNodeAtLocation(node: ts.Node, flag?: ts.NodeBuilderFlags) {
const type = env.checker.getTypeAtLocation(node);
return env.checker.typeToTypeNode(type, undefined, flag || defaultBuildFlags);
}
export function createVariableDeclaration(node: ts.VariableDeclaration, name?: string) {
name = createNameByDecl(node, name);
const typeNode = getTypeNodeAtLocation(node.name);
const typeDom = getTypeDom(typeNode);
return dom.create.const(name, typeDom);
}
// get decl name
export function getDeclName(name: string): string {
name = dom.reservedWords.includes(name) ? `_${name}` : name;
if (env.publicNames[name] === undefined) {
env.publicNames[name] = 0;
return name;
} else {
env.publicNames[name]++;
return getDeclName(`${name}_${env.publicNames[name]}`);
}
}
export function createInterfaceWithCache(members: dom.ObjectTypeMember[], name?: string) {
const interfaceDeclare = env.interfaceList.find(obj => isEqual(obj.members, members));
if (interfaceDeclare) {
return interfaceDeclare;
}
const nsi = createExportInterface(name || getAnonymousName());
nsi.members = members;
env.interfaceList.push(nsi);
return nsi;
}
export function createExportInterface(name: string) {
const interfaceType = dom.create.interface(name);
if (env.exportFlags & ExportFlags.ExportEqual) {
interfaceType.namespace = env.exportNamespace;
env.exportNamespace!.members.push(interfaceType);
} else {
env.declaration.fragment.push(interfaceType);
}
interfaceType.flags = dom.DeclarationFlags.Export;
return interfaceType;
}
export function createExportNameByFile(file: string) {
let name = path.basename(file, path.extname(file));
const pkgInfoPath = path.resolve(path.dirname(file), 'package.json');
if (fs.existsSync(pkgInfoPath)) {
const pkgInfo = JSON.parse(fs.readFileSync(pkgInfoPath).toString());
name = pkgInfo.name || name;
}
if (name === 'index') {
name = path.basename(path.dirname(file));
}
// add _ for prevent duplicate with global declaration
return getDeclName(`_${util.formatName(name, true)}`);
}
// create dts for file
export function create(file: string, options?: CreateOptions) {
// check cache
const cacheEnv = envMod.getEnv(file);
if (cacheEnv) {
return cacheEnv;
}
// start program
envMod.createEnv(file, options);
const declaration = env.declaration;
if (!env.sourceFile) {
declaration.fragment.push(dom.create.comment('source file create fail'));
return envMod.popEnv();
}
// check node
const { exportEqual, exportList } = util.findExports(env.sourceFile);
if (!exportEqual && !exportList.size) {
declaration.fragment.push(dom.create.comment('cannot find export module'));
return envMod.popEnv();
}
env.exportFlags = exportEqual
? ExportFlags.ExportEqual
: ExportFlags.Export;
let exportInterface: dom.InterfaceDeclaration | undefined;
env.exportDefaultName = createExportNameByFile(env.file);
env.exportNamespace = dom.create.namespace(env.exportDefaultName);
// export list
if (exportList.size) {
// add export name to publicNames
if (!exportEqual) {
exportList.forEach((_, name) => getDeclName(name));
}
exportList.forEach(({ node, originalNode }, name) => {
if (checkIsPrivate(node, name)) {
return;
}
const typeNode = getTypeNodeAtLocation(node);
let typeDom = getTypeDom(typeNode) || dom.type.any;
if (env.exportFlags & ExportFlags.Export) {
if (name === 'default') {
const name = getDeclName(util.getText(node) || getAnonymousName());
typeDom = dom.util.typeToDeclaration(name, typeDom);
if (dom.util.isCanBeExportDefault(typeDom)) {
typeDom.flags = dom.DeclarationFlags.ExportDefault;
} else {
if (dom.util.isConstDeclaration(typeDom)) {
// make export default simplify
const name = dom.util.isTypeofReference(typeDom.type)
? typeDom.type.type.name
: (
dom.util.isNamedTypeReference(typeDom.type)
? typeDom.type.name
: undefined
);
const tds = name ? env.declaration.fragment.filter(member => (
dom.util.isNamedDeclarationBase(member) && name === member.name
)) : undefined;
if (tds && tds.length === 1 && dom.util.isCanBeExportDefault(tds[0])) {
tds[0].flags! |= dom.DeclarationFlags.ExportDefault;
return;
}
}
env.declaration.export.push(dom.create.exportDefault(name));
}
} else {
typeDom = dom.util.typeToDeclaration(name, typeDom, dom.DeclarationFlags.Export);
}
addJsDocToTypeDom(typeDom, originalNode);
env.declaration.fragment.push(typeDom);
} else {
if (!exportInterface) {
exportInterface = dom.create.interface(getAnonymousName());
env.declaration.fragment.push(exportInterface);
}
const memberDom: dom.ObjectTypeMember = dom.create.property(name, typeDom);
addJsDocToTypeDom(memberDom, originalNode);
exportInterface.members.push(memberDom);
}
});
}
// export default
if (exportEqual) {
const typeNode = getTypeNodeAtLocation(exportEqual.node);
let typeDom = getTypeDom(typeNode) || dom.type.any;
typeDom = exportInterface ? dom.create.intersection([ typeDom, exportInterface ]) : typeDom;
typeDom = dom.create.const(env.exportDefaultName, typeDom);
declaration.fragment.push(typeDom);
// add export=
declaration.export.push(dom.create.exportEquals(env.exportDefaultName));
}
// add import list
Object.keys(env.importCache).forEach(k => {
const obj = env.importCache[k];
// import * as xx
if (obj.default) {
declaration.import.push(dom.create.importAll(obj.default, obj.from));
}
// import { xx } from 'xx';
if (obj.list.length) {
declaration.import.push(dom.create.importNamed(obj.list, obj.from));
}
});
// add export namespace
if (env.exportNamespace && env.exportNamespace.members.length) {
declaration.fragment.push(env.exportNamespace);
}
return envMod.popEnv();
} | the_stack |
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { AbstractClient } from "../../../common/abstract_client"
import { ClientConfig } from "../../../common/interface"
import {
CreateNetworkAclResponse,
NetworkAcl,
ModifyAddressTemplateAttributeResponse,
DisassociateDhcpIpWithAddressIpRequest,
SecurityGroupLimitSet,
CreateRoutesRequest,
DescribeHaVipsResponse,
SecurityGroupAssociationStatistics,
DeleteServiceTemplateResponse,
CreateServiceTemplateRequest,
DescribeIp6TranslatorQuotaResponse,
CreateCcnResponse,
DescribeVpnConnectionsRequest,
CreateAssistantCidrRequest,
DescribeNetworkInterfacesRequest,
DescribeVpcLimitsRequest,
ReleaseIp6AddressesBandwidthResponse,
DescribeVpcIpv6AddressesRequest,
SourceIpTranslationNatRule,
DisableCcnRoutesRequest,
ModifyNatGatewayDestinationIpPortTranslationNatRuleResponse,
ModifyIp6RuleResponse,
ModifyCcnRegionBandwidthLimitsTypeResponse,
DescribeVpnGatewaysResponse,
ServiceTemplateGroup,
CreateDhcpIpResponse,
DescribeIpGeolocationInfosRequest,
AddTemplateMemberResponse,
CreateDefaultSecurityGroupRequest,
DescribeServiceTemplateGroupsResponse,
DescribeVpcEndPointRequest,
DetachClassicLinkVpcRequest,
DescribeBandwidthPackageBillUsageResponse,
DeleteBandwidthPackageResponse,
ModifyNatGatewayAttributeRequest,
DescribeLocalGatewayRequest,
FlowLog,
DescribeVpcLimitsResponse,
IpField,
AddBandwidthPackageResourcesRequest,
AssignIpv6SubnetCidrBlockRequest,
CreateVpcResponse,
AssistantCidr,
ModifyNetworkAclEntriesRequest,
DescribeVpcPrivateIpAddressesRequest,
AddressTemplate,
IKEOptionsSpecification,
VpnGatewayQuota,
DescribeBandwidthPackageBillUsageRequest,
UnassignIpv6AddressesResponse,
CreateIp6TranslatorsResponse,
DescribeFlowLogsRequest,
DeleteTemplateMemberRequest,
CloneSecurityGroupRequest,
AssociateNatGatewayAddressRequest,
CreateDirectConnectGatewayRequest,
CreateVpcEndPointRequest,
ModifyBandwidthPackageAttributeRequest,
TransformAddressResponse,
DisassociateNetworkInterfaceSecurityGroupsRequest,
SecurityGroupPolicySet,
ModifyFlowLogAttributeRequest,
UnassignIpv6SubnetCidrBlockResponse,
ModifyVpcEndPointServiceAttributeRequest,
FilterObject,
DescribeIpGeolocationInfosResponse,
DescribeVpcTaskResultRequest,
AssociateNetworkAclSubnetsResponse,
DeleteNatGatewayDestinationIpPortTranslationNatRuleRequest,
ResetRoutesRequest,
CheckDefaultSubnetRequest,
CheckNetDetectStateRequest,
RouteTableAssociation,
ModifyCustomerGatewayAttributeRequest,
DescribeRouteTablesResponse,
DeleteVpcEndPointServiceWhiteListRequest,
DeleteVpcEndPointServiceRequest,
DeleteCcnResponse,
ServiceTemplate,
DescribeCcnAttachedInstancesRequest,
DescribeNatGatewaySourceIpTranslationNatRulesRequest,
DescribeNatGatewaysRequest,
ModifyFlowLogAttributeResponse,
DescribeBandwidthPackagesResponse,
DescribeDirectConnectGatewaysRequest,
DisassociateVpcEndPointSecurityGroupsRequest,
ModifyIp6TranslatorResponse,
CreateVpcEndPointServiceWhiteListResponse,
DescribeIpGeolocationDatabaseUrlResponse,
DeleteIp6TranslatorsResponse,
DescribeNatGatewaySourceIpTranslationNatRulesResponse,
DescribeVpcsRequest,
DescribeRouteConflictsResponse,
AcceptAttachCcnInstancesRequest,
DescribeGatewayFlowMonitorDetailResponse,
IpGeolocationInfo,
DeleteFlowLogRequest,
NetDetectState,
HaVipDisassociateAddressIpResponse,
DescribeTaskResultRequest,
ModifyAddressInternetChargeTypeResponse,
UnassignIpv6SubnetCidrBlockRequest,
DeleteVpcEndPointServiceResponse,
AssignIpv6CidrBlockRequest,
CreateSecurityGroupPoliciesResponse,
UnassignIpv6CidrBlockResponse,
ModifyVpnGatewayRoutesRequest,
HaVipAssociateAddressIpRequest,
DisassociateNatGatewayAddressResponse,
DeleteRoutesResponse,
DescribeCrossBorderComplianceRequest,
DescribeSecurityGroupAssociationStatisticsResponse,
ModifyAssistantCidrResponse,
CidrForCcn,
NatGatewayAddress,
DescribeVpcEndPointServiceResponse,
ModifyNetworkAclEntriesResponse,
ModifyVpcEndPointAttributeResponse,
DescribeFlowLogRequest,
DescribeIp6AddressesRequest,
AddIp6RulesRequest,
DescribeAccountAttributesResponse,
AssignPrivateIpAddressesResponse,
DescribeSecurityGroupsRequest,
RefreshDirectConnectGatewayRouteToNatGatewayRequest,
DescribeNatGatewayDestinationIpPortTranslationNatRulesRequest,
ModifyNetworkAclAttributeResponse,
CreateVpnGatewayRoutesRequest,
DisassociateNetworkAclSubnetsResponse,
SetCcnRegionBandwidthLimitsRequest,
ModifyAddressInternetChargeTypeRequest,
ModifyIp6AddressesBandwidthRequest,
CreateLocalGatewayRequest,
DescribeDirectConnectGatewaysResponse,
AddBandwidthPackageResourcesResponse,
Ip6RuleInfo,
CreateSecurityGroupWithPoliciesResponse,
DeleteAddressTemplateResponse,
ModifySubnetAttributeResponse,
ResetNatGatewayConnectionRequest,
ModifyCcnAttachedInstancesAttributeRequest,
DeleteAddressTemplateRequest,
CreateNatGatewaySourceIpTranslationNatRuleRequest,
NetworkInterface,
TransformAddressRequest,
ReplaceDirectConnectGatewayCcnRoutesRequest,
ReferredSecurityGroup,
ModifyAddressTemplateAttributeRequest,
CreateNatGatewayResponse,
DescribeIp6TranslatorQuotaRequest,
ModifySecurityGroupAttributeRequest,
ModifyNetDetectRequest,
DescribeNetDetectStatesResponse,
DescribeVpcResourceDashboardResponse,
AllocateIp6AddressesBandwidthResponse,
DescribeNetDetectStatesRequest,
DescribeNatGatewaysResponse,
DescribeFlowLogResponse,
DownloadCustomerGatewayConfigurationResponse,
DescribeBandwidthPackagesRequest,
DeleteDirectConnectGatewayCcnRoutesResponse,
DescribeAssistantCidrResponse,
InstanceStatistic,
CreateVpnConnectionRequest,
CcnRoute,
ModifyIpv6AddressesAttributeResponse,
DeleteSecurityGroupPoliciesRequest,
VpnConnection,
DescribeCcnsRequest,
ModifyNatGatewayAttributeResponse,
DescribeNetDetectsRequest,
CreateAddressTemplateGroupRequest,
DescribeNatGatewayDirectConnectGatewayRouteRequest,
DescribeCustomerGatewayVendorsResponse,
RouteConflict,
DeleteSubnetResponse,
Vpc,
CreateVpnGatewayResponse,
DescribeNatGatewayDestinationIpPortTranslationNatRulesResponse,
ProductQuota,
DescribeVpcIpv6AddressesResponse,
ResetAttachCcnInstancesResponse,
RejectAttachCcnInstancesRequest,
ModifyCcnRegionBandwidthLimitsTypeRequest,
VpnGatewayRoute,
DescribeVpcResourceDashboardRequest,
ModifyIp6RuleRequest,
ReplaceRouteTableAssociationRequest,
AssociateNetworkAclSubnetsRequest,
CheckAssistantCidrRequest,
RenewVpnGatewayRequest,
SecurityGroupPolicy,
NotifyRoutesRequest,
DeleteVpcRequest,
ModifyServiceTemplateAttributeResponse,
DescribeCcnsResponse,
TemplateLimit,
CreateSubnetResponse,
DescribeSecurityGroupPoliciesResponse,
DescribeGatewayFlowQosResponse,
ModifySecurityGroupPoliciesRequest,
NatGateway,
AssociateDhcpIpWithAddressIpRequest,
ReplaceRoutesRequest,
CreateCustomerGatewayResponse,
WithdrawNotifyRoutesRequest,
DeleteServiceTemplateGroupResponse,
DisassociateAddressRequest,
NetworkAclEntrySet,
DeleteVpnConnectionResponse,
DescribeBandwidthPackageResourcesRequest,
EnableCcnRoutesRequest,
Tag,
DescribeCcnAttachedInstancesResponse,
DefaultVpcSubnet,
DescribeIp6TranslatorsRequest,
CreateSubnetsResponse,
DescribeGatewayFlowMonitorDetailRequest,
InquiryPriceCreateVpnGatewayResponse,
DescribeSecurityGroupLimitsResponse,
CustomerGateway,
ModifyDirectConnectGatewayAttributeRequest,
ModifyBandwidthPackageAttributeResponse,
DetachNetworkInterfaceResponse,
ResetRoutesResponse,
DeleteNetworkAclRequest,
NatGatewayDestinationIpPortTranslationNatRule,
CloneSecurityGroupResponse,
ModifyDhcpIpAttributeRequest,
ModifyIp6TranslatorRequest,
CreateVpnConnectionResponse,
AddressTemplateSpecification,
VpcIpv6Address,
AssignIpv6AddressesRequest,
CreateServiceTemplateGroupResponse,
NetDetect,
VpnGatewayRouteModify,
MemberInfo,
ReplaceSecurityGroupPolicyRequest,
ModifyVpcEndPointServiceAttributeResponse,
ResourceDashboard,
DescribeVpcPrivateIpAddressesResponse,
HaVipAssociateAddressIpResponse,
DeleteCustomerGatewayResponse,
CreateVpnGatewayRoutesResponse,
CreateNetDetectRequest,
CreateAddressTemplateResponse,
CreateNatGatewayDestinationIpPortTranslationNatRuleResponse,
DeleteAddressTemplateGroupRequest,
DescribeNetworkInterfaceLimitRequest,
CreateBandwidthPackageRequest,
DescribeIp6AddressesResponse,
ModifyRouteTableAttributeRequest,
ModifyDirectConnectGatewayAttributeResponse,
DescribeVpnGatewaysRequest,
NetDetectIpState,
ModifyIp6AddressesBandwidthResponse,
CreateSubnetsRequest,
DescribeVpcEndPointServiceRequest,
ModifyServiceTemplateAttributeRequest,
AssociateAddressResponse,
ModifyCcnAttachedInstancesAttributeResponse,
CreateNetworkAclRequest,
DescribeAddressesRequest,
DescribeSecurityGroupPoliciesRequest,
ModifyNetworkInterfaceAttributeResponse,
CreateSecurityGroupResponse,
DisassociateNetworkInterfaceSecurityGroupsResponse,
DescribeVpcsResponse,
DescribeNetworkInterfaceLimitResponse,
AssignIpv6CidrBlockResponse,
CreateCcnRequest,
DeleteTemplateMemberResponse,
ModifyNatGatewaySourceIpTranslationNatRuleRequest,
RemoveIp6RulesRequest,
DescribeIpGeolocationDatabaseUrlRequest,
DescribeVpcEndPointResponse,
DisableGatewayFlowMonitorRequest,
EnableRoutesResponse,
DeleteVpnConnectionRequest,
NetworkAclEntry,
DescribeDhcpIpsRequest,
DescribeAssistantCidrRequest,
RenewVpnGatewayResponse,
DeleteDirectConnectGatewayResponse,
ModifyAddressesBandwidthRequest,
ResetVpnGatewayInternetMaxBandwidthRequest,
EndPoint,
DirectConnectGateway,
DescribeProductQuotaResponse,
Price,
HaVipDisassociateAddressIpRequest,
DescribeBandwidthPackageResourcesResponse,
DescribeCrossBorderComplianceResponse,
ModifyVpnGatewayAttributeResponse,
AssociateDirectConnectGatewayNatGatewayResponse,
EndPointService,
DescribeVpnGatewayCcnRoutesRequest,
DisassociateDirectConnectGatewayNatGatewayResponse,
CreateServiceTemplateGroupRequest,
DescribeClassicLinkInstancesResponse,
DescribeVpnGatewayCcnRoutesResponse,
DetachCcnInstancesRequest,
ModifyVpcEndPointServiceWhiteListRequest,
Filter,
CreateFlowLogResponse,
DeleteDirectConnectGatewayRequest,
CreateNatGatewaySourceIpTranslationNatRuleResponse,
DeleteNatGatewaySourceIpTranslationNatRuleResponse,
CcnAttachedInstance,
SecurityPolicyDatabase,
ResetVpnConnectionResponse,
CreateVpcEndPointServiceRequest,
Ipv6Address,
CreateNetworkInterfaceRequest,
BandwidthPackageBillBandwidth,
DeleteHaVipResponse,
DescribeFlowLogsResponse,
VpcPrivateIpAddress,
CvmInstance,
DescribeNetworkAclsRequest,
DescribeSubnetsRequest,
CreateSubnetRequest,
AddressTemplateGroup,
DownloadCustomerGatewayConfigurationRequest,
DeleteBandwidthPackageRequest,
HaVip,
ModifyAddressesBandwidthResponse,
LocalGateway,
RejectAttachCcnInstancesResponse,
SetCcnRegionBandwidthLimitsResponse,
DescribeAccountAttributesRequest,
RenewAddressesResponse,
DescribeCcnRoutesRequest,
ModifyDhcpIpAttributeResponse,
CreateAndAttachNetworkInterfaceRequest,
DeleteVpcEndPointResponse,
DeleteDhcpIpResponse,
ModifyGatewayFlowQosRequest,
DeleteNetDetectResponse,
AllocateAddressesRequest,
CrossBorderCompliance,
ModifyAssistantCidrRequest,
CreateIp6TranslatorsRequest,
AssociateDhcpIpWithAddressIpResponse,
ModifyGatewayFlowQosResponse,
ModifyNetworkInterfaceQosResponse,
ModifySecurityGroupAttributeResponse,
AssociateDirectConnectGatewayNatGatewayRequest,
AddressTemplateItem,
ModifyAddressAttributeResponse,
AttachClassicLinkVpcRequest,
GatewayFlowMonitorDetail,
DeleteNatGatewayDestinationIpPortTranslationNatRuleResponse,
DeleteVpnGatewayRequest,
ReplaceRouteTableAssociationResponse,
AttachCcnInstancesRequest,
DescribeDirectConnectGatewayCcnRoutesRequest,
CcnInstance,
DescribeLocalGatewayResponse,
ItemPrice,
DeleteNatGatewayRequest,
ModifyCustomerGatewayAttributeResponse,
ConflictItem,
InquiryPriceRenewVpnGatewayResponse,
AssignIpv6SubnetCidrBlockResponse,
CreateVpcEndPointResponse,
DeleteAssistantCidrResponse,
DescribeCcnRegionBandwidthLimitsResponse,
ModifyTemplateMemberRequest,
DescribeAddressesResponse,
GatewayQos,
ModifyIpv6AddressesAttributeRequest,
DescribeCustomerGatewayVendorsRequest,
DeleteLocalGatewayRequest,
ResetVpnGatewayInternetMaxBandwidthResponse,
AddressChargePrepaid,
DescribeVpnGatewayRoutesResponse,
DescribeNetworkAclsResponse,
DeleteFlowLogResponse,
AttachCcnInstancesResponse,
CreateDefaultVpcResponse,
ModifyVpcAttributeResponse,
ModifyVpnConnectionAttributeResponse,
PrivateIpAddressSpecification,
AlgType,
MigratePrivateIpAddressResponse,
DeleteRouteTableResponse,
DescribeVpcInstancesResponse,
AccountAttribute,
DeleteDirectConnectGatewayCcnRoutesRequest,
ModifyNatGatewaySourceIpTranslationNatRuleResponse,
CreateNatGatewayDestinationIpPortTranslationNatRuleRequest,
CreateFlowLogRequest,
InquirePriceCreateDirectConnectGatewayRequest,
AttachNetworkInterfaceResponse,
DisassociateNatGatewayAddressRequest,
DescribeServiceTemplatesResponse,
DescribeRouteTablesRequest,
ResetAttachCcnInstancesRequest,
CreateHaVipResponse,
DescribeSecurityGroupReferencesRequest,
DescribeTemplateLimitsResponse,
CheckDefaultSubnetResponse,
DisableRoutesRequest,
DisassociateDirectConnectGatewayNatGatewayRequest,
EnableRoutesRequest,
DescribeAddressTemplateGroupsResponse,
ReleaseAddressesRequest,
CreateDirectConnectGatewayCcnRoutesRequest,
CreateDirectConnectGatewayCcnRoutesResponse,
CreateRouteTableRequest,
MigrateNetworkInterfaceRequest,
DescribeCustomerGatewaysRequest,
RenewAddressesRequest,
DisableRoutesResponse,
ModifyAddressAttributeRequest,
DhcpIp,
DeleteAssistantCidrRequest,
ModifyTemplateMemberResponse,
SubnetInput,
DescribeNatGatewayDirectConnectGatewayRouteResponse,
EnableVpcEndPointConnectResponse,
CreateNetDetectResponse,
DeleteCcnRequest,
ModifyLocalGatewayResponse,
AssociateNetworkInterfaceSecurityGroupsResponse,
ModifyVpnGatewayAttributeRequest,
CreateNatGatewayRequest,
DeleteNetDetectRequest,
IPSECOptionsSpecification,
UnassignIpv6AddressesRequest,
CreateAndAttachNetworkInterfaceResponse,
ModifyCcnAttributeRequest,
DeleteSecurityGroupPoliciesResponse,
DisassociateDhcpIpWithAddressIpResponse,
CreateVpcEndPointServiceResponse,
ModifyNetworkAclAttributeRequest,
DeleteVpnGatewayResponse,
DescribeHaVipsRequest,
UnassignPrivateIpAddressesResponse,
Address,
VpnGateway,
EnableVpcEndPointConnectRequest,
EnableGatewayFlowMonitorResponse,
Resource,
DeleteDhcpIpRequest,
AllocateAddressesResponse,
BandwidthPackage,
ModifyVpcAttributeRequest,
DescribeIp6TranslatorsResponse,
CreateSecurityGroupPoliciesRequest,
ModifyVpnGatewayRoutesResponse,
ModifyRouteTableAttributeResponse,
DescribeSecurityGroupReferencesResponse,
AddIp6RulesResponse,
CreateAddressTemplateGroupResponse,
DescribeBandwidthPackageQuotaResponse,
DeleteServiceTemplateGroupRequest,
DeleteNatGatewayResponse,
CreateDirectConnectGatewayResponse,
ModifyVpcEndPointAttributeRequest,
DescribeTaskResultResponse,
DisassociateNetworkAclSubnetsRequest,
ModifyAddressTemplateGroupAttributeRequest,
ModifyServiceTemplateGroupAttributeRequest,
DeleteVpcEndPointRequest,
UnassignIpv6CidrBlockRequest,
CCN,
InquirePriceCreateDirectConnectGatewayResponse,
DeleteIp6TranslatorsRequest,
Ip6Translator,
DestinationIpPortTranslationNatRule,
CreateDefaultVpcRequest,
DescribeSubnetsResponse,
DescribeCustomerGatewaysResponse,
CheckAssistantCidrResponse,
InquiryPriceRenewVpnGatewayRequest,
EnableCcnRoutesResponse,
ModifyVpnGatewayCcnRoutesResponse,
DetachCcnInstancesResponse,
ModifyServiceTemplateGroupAttributeResponse,
DeleteSubnetRequest,
DescribeAddressTemplateGroupsRequest,
CheckNetDetectStateResponse,
DisassociateVpcEndPointSecurityGroupsResponse,
DescribeVpcTaskResultResponse,
AssociateNatGatewayAddressResponse,
RemoveBandwidthPackageResourcesRequest,
VpngwCcnRoutes,
ModifyVpnConnectionAttributeRequest,
DeleteNetworkInterfaceRequest,
InquiryPriceResetVpnGatewayInternetMaxBandwidthResponse,
RouteTable,
DescribeVpcEndPointServiceWhiteListRequest,
DeleteAddressTemplateGroupResponse,
ModifyNetworkInterfaceQosRequest,
ModifyLocalGatewayRequest,
DirectConnectGatewayCcnRoute,
DeleteHaVipRequest,
CreateLocalGatewayResponse,
MigratePrivateIpAddressRequest,
DescribeServiceTemplatesRequest,
RefreshDirectConnectGatewayRouteToNatGatewayResponse,
DeleteRouteTableRequest,
CreateVpnGatewayRequest,
DescribeVpcInstancesRequest,
DeleteVpcEndPointServiceWhiteListResponse,
CreateBandwidthPackageResponse,
ResetVpnConnectionRequest,
ReleaseAddressesResponse,
AuditCrossBorderComplianceResponse,
InquiryPriceResetVpnGatewayInternetMaxBandwidthRequest,
ReplaceSecurityGroupPolicyResponse,
EnableGatewayFlowMonitorRequest,
ModifyPrivateIpAddressesAttributeResponse,
ReplaceRoutesResponse,
ModifyHaVipAttributeResponse,
CcnBandwidthInfo,
DeleteSecurityGroupResponse,
CreateNetworkInterfaceResponse,
DescribeAddressQuotaRequest,
RemoveBandwidthPackageResourcesResponse,
AssignIpv6AddressesResponse,
CreateRoutesResponse,
DescribeSecurityGroupsResponse,
CreateVpcEndPointServiceWhiteListRequest,
DeleteNatGatewaySourceIpTranslationNatRuleRequest,
ModifyVpnGatewayCcnRoutesRequest,
DescribeGatewayFlowQosRequest,
ReplaceDirectConnectGatewayCcnRoutesResponse,
ModifySecurityGroupPoliciesResponse,
ModifyNatGatewayDestinationIpPortTranslationNatRuleRequest,
ServiceTemplateSpecification,
DetachNetworkInterfaceRequest,
Ip6Rule,
AttachClassicLinkVpcResponse,
CreateAddressTemplateRequest,
DescribeRouteConflictsRequest,
NatDirectConnectGatewayRoute,
Subnet,
AttachNetworkInterfaceRequest,
DescribeCcnRoutesResponse,
AllocateIp6AddressesBandwidthRequest,
SecurityGroup,
DisableGatewayFlowMonitorResponse,
DisassociateAddressResponse,
DirectConnectSubnet,
DescribeVpnGatewayRoutesRequest,
GetCcnRegionBandwidthLimitsResponse,
DeleteRoutesRequest,
AssociateAddressRequest,
CcnRegionBandwidthLimit,
VpcEndPointServiceUser,
CreateDefaultSecurityGroupResponse,
ClassicLinkInstance,
DeleteLocalGatewayResponse,
NetworkInterfaceAttachment,
ModifyNetworkInterfaceAttributeRequest,
RemoveIp6RulesResponse,
ModifyHaVipAttributeRequest,
ModifyAddressTemplateGroupAttributeResponse,
VpcLimit,
DetachClassicLinkVpcResponse,
MigrateNetworkInterfaceResponse,
UnassignPrivateIpAddressesRequest,
DeleteVpnGatewayRoutesRequest,
DescribeProductQuotaRequest,
ModifyNetDetectResponse,
CreateHaVipRequest,
Ipv6SubnetCidrBlock,
DescribeAddressQuotaResponse,
CreateCustomerGatewayRequest,
DeleteSecurityGroupRequest,
DescribeDhcpIpsResponse,
CreateRouteTableResponse,
GetCcnRegionBandwidthLimitsRequest,
DescribeDirectConnectGatewayCcnRoutesResponse,
ModifyPrivateIpAddressesAttributeRequest,
ResetNatGatewayConnectionResponse,
AssociateNetworkInterfaceSecurityGroupsRequest,
DeleteVpnGatewayRoutesResponse,
CreateSecurityGroupRequest,
ModifyCcnAttributeResponse,
DescribeSecurityGroupLimitsRequest,
DescribeClassicLinkInstancesRequest,
ReleaseIp6AddressesBandwidthRequest,
CreateServiceTemplateResponse,
DeleteNetworkInterfaceResponse,
DisableCcnRoutesResponse,
DescribeCcnRegionBandwidthLimitsRequest,
InquiryPriceCreateVpnGatewayRequest,
CreateAssistantCidrResponse,
CustomerGatewayVendor,
DescribeAddressTemplatesRequest,
ConflictSource,
CreateDhcpIpRequest,
DescribeVpnConnectionsResponse,
DeleteCustomerGatewayRequest,
DescribeAddressTemplatesResponse,
Quota,
WithdrawNotifyRoutesResponse,
DescribeNetworkInterfacesResponse,
DeleteNetworkAclResponse,
AssignPrivateIpAddressesRequest,
DescribeServiceTemplateGroupsRequest,
CreateSecurityGroupWithPoliciesRequest,
CreateVpcRequest,
DeleteServiceTemplateRequest,
DescribeSecurityGroupAssociationStatisticsRequest,
NotifyRoutesResponse,
Route,
ModifySubnetAttributeRequest,
ModifyVpcEndPointServiceWhiteListResponse,
DescribeBandwidthPackageQuotaRequest,
DeleteVpcResponse,
DescribeTemplateLimitsRequest,
AddTemplateMemberRequest,
DescribeVpcEndPointServiceWhiteListResponse,
AcceptAttachCcnInstancesResponse,
InstanceChargePrepaid,
AuditCrossBorderComplianceRequest,
DescribeNetDetectsResponse,
} from "./vpc_models"
/**
* vpc client
* @class
*/
export class Client extends AbstractClient {
constructor(clientConfig: ClientConfig) {
super("vpc.tencentcloudapi.com", "2017-03-12", clientConfig)
}
/**
* 本接口(DescribeVpcResourceDashboard)用于查看VPC资源信息。
*/
async DescribeVpcResourceDashboard(
req: DescribeVpcResourceDashboardRequest,
cb?: (error: string, rep: DescribeVpcResourceDashboardResponse) => void
): Promise<DescribeVpcResourceDashboardResponse> {
return this.request("DescribeVpcResourceDashboard", req, cb)
}
/**
* 本接口(DescribeCcnRegionBandwidthLimits)用于查询云联网各地域出带宽上限,该接口只返回已关联网络实例包含的地域
*/
async DescribeCcnRegionBandwidthLimits(
req: DescribeCcnRegionBandwidthLimitsRequest,
cb?: (error: string, rep: DescribeCcnRegionBandwidthLimitsResponse) => void
): Promise<DescribeCcnRegionBandwidthLimitsResponse> {
return this.request("DescribeCcnRegionBandwidthLimits", req, cb)
}
/**
* 本接口(DescribeCustomerGateways)用于查询对端网关列表。
*/
async DescribeCustomerGateways(
req: DescribeCustomerGatewaysRequest,
cb?: (error: string, rep: DescribeCustomerGatewaysResponse) => void
): Promise<DescribeCustomerGatewaysResponse> {
return this.request("DescribeCustomerGateways", req, cb)
}
/**
* 本接口(ReplaceSecurityGroupPolicy)用于替换单条安全组规则(SecurityGroupPolicy)。
单个请求中只能替换单个方向的一条规则, 必须要指定索引(PolicyIndex)。
*/
async ReplaceSecurityGroupPolicy(
req: ReplaceSecurityGroupPolicyRequest,
cb?: (error: string, rep: ReplaceSecurityGroupPolicyResponse) => void
): Promise<ReplaceSecurityGroupPolicyResponse> {
return this.request("ReplaceSecurityGroupPolicy", req, cb)
}
/**
* 本接口(CreateFlowLog)用于创建流日志
*/
async CreateFlowLog(
req: CreateFlowLogRequest,
cb?: (error: string, rep: CreateFlowLogResponse) => void
): Promise<CreateFlowLogResponse> {
return this.request("CreateFlowLog", req, cb)
}
/**
* 本接口(ModifyNatGatewayAttribute)用于修改NAT网关的属性。
*/
async ModifyNatGatewayAttribute(
req: ModifyNatGatewayAttributeRequest,
cb?: (error: string, rep: ModifyNatGatewayAttributeResponse) => void
): Promise<ModifyNatGatewayAttributeResponse> {
return this.request("ModifyNatGatewayAttribute", req, cb)
}
/**
* 查询EIP异步任务执行结果
*/
async DescribeTaskResult(
req: DescribeTaskResultRequest,
cb?: (error: string, rep: DescribeTaskResultResponse) => void
): Promise<DescribeTaskResultResponse> {
return this.request("DescribeTaskResult", req, cb)
}
/**
* 本接口(CreateNetworkAcl)用于创建新的<a href="https://cloud.tencent.com/document/product/215/20088">网络ACL</a>。
* 新建的网络ACL的入站和出站规则默认都是全部拒绝,在创建后通常您需要再调用ModifyNetworkAclEntries将网络ACL的规则设置为需要的规则。
*/
async CreateNetworkAcl(
req: CreateNetworkAclRequest,
cb?: (error: string, rep: CreateNetworkAclResponse) => void
): Promise<CreateNetworkAclResponse> {
return this.request("CreateNetworkAcl", req, cb)
}
/**
* 本接口(DescribeServiceTemplateGroups)用于查询协议端口模板集合
*/
async DescribeServiceTemplateGroups(
req: DescribeServiceTemplateGroupsRequest,
cb?: (error: string, rep: DescribeServiceTemplateGroupsResponse) => void
): Promise<DescribeServiceTemplateGroupsResponse> {
return this.request("DescribeServiceTemplateGroups", req, cb)
}
/**
* 本接口(DescribeRouteTables)用于查询路由表。
*/
async DescribeRouteTables(
req: DescribeRouteTablesRequest,
cb?: (error: string, rep: DescribeRouteTablesResponse) => void
): Promise<DescribeRouteTablesResponse> {
return this.request("DescribeRouteTables", req, cb)
}
/**
* 本接口 (CreateBandwidthPackage) 支持创建[设备带宽包](https://cloud.tencent.com/document/product/684/15245#bwptype)和[IP带宽包](https://cloud.tencent.com/document/product/684/15245#bwptype)。
*/
async CreateBandwidthPackage(
req: CreateBandwidthPackageRequest,
cb?: (error: string, rep: CreateBandwidthPackageResponse) => void
): Promise<CreateBandwidthPackageResponse> {
return this.request("CreateBandwidthPackage", req, cb)
}
/**
* 本接口(DeleteFlowLog)用于删除流日志
*/
async DeleteFlowLog(
req: DeleteFlowLogRequest,
cb?: (error: string, rep: DeleteFlowLogResponse) => void
): Promise<DeleteFlowLogResponse> {
return this.request("DeleteFlowLog", req, cb)
}
/**
* 本接口(CreateRouteTable)用于创建路由表。
* 创建了VPC后,系统会创建一个默认路由表,所有新建的子网都会关联到默认路由表。默认情况下您可以直接使用默认路由表来管理您的路由策略。当您的路由策略较多时,您可以调用创建路由表接口创建更多路由表管理您的路由策略。
* 创建路由表同时可以绑定标签, 应答里的标签列表代表添加成功的标签。
*/
async CreateRouteTable(
req: CreateRouteTableRequest,
cb?: (error: string, rep: CreateRouteTableResponse) => void
): Promise<CreateRouteTableResponse> {
return this.request("CreateRouteTable", req, cb)
}
/**
* 本接口(AssignIpv6CidrBlock)用于分配IPv6网段。
* 使用本接口前,您需要已有VPC实例,如果没有可通过接口<a href="https://cloud.tencent.com/document/api/215/15774" title="CreateVpc" target="_blank">CreateVpc</a>创建。
* 每个VPC只能申请一个IPv6网段
*/
async AssignIpv6CidrBlock(
req: AssignIpv6CidrBlockRequest,
cb?: (error: string, rep: AssignIpv6CidrBlockResponse) => void
): Promise<AssignIpv6CidrBlockResponse> {
return this.request("AssignIpv6CidrBlock", req, cb)
}
/**
* 本接口(DeleteNetworkAcl)用于删除网络ACL。
*/
async DeleteNetworkAcl(
req: DeleteNetworkAclRequest,
cb?: (error: string, rep: DeleteNetworkAclResponse) => void
): Promise<DeleteNetworkAclResponse> {
return this.request("DeleteNetworkAcl", req, cb)
}
/**
* 删除终端节点服务白名单。
*/
async DeleteVpcEndPointServiceWhiteList(
req: DeleteVpcEndPointServiceWhiteListRequest,
cb?: (error: string, rep: DeleteVpcEndPointServiceWhiteListResponse) => void
): Promise<DeleteVpcEndPointServiceWhiteListResponse> {
return this.request("DeleteVpcEndPointServiceWhiteList", req, cb)
}
/**
* 本接口(DescribeNatGatewayDestinationIpPortTranslationNatRules)用于查询NAT网关端口转发规则对象数组。
*/
async DescribeNatGatewayDestinationIpPortTranslationNatRules(
req: DescribeNatGatewayDestinationIpPortTranslationNatRulesRequest,
cb?: (
error: string,
rep: DescribeNatGatewayDestinationIpPortTranslationNatRulesResponse
) => void
): Promise<DescribeNatGatewayDestinationIpPortTranslationNatRulesResponse> {
return this.request("DescribeNatGatewayDestinationIpPortTranslationNatRules", req, cb)
}
/**
* 本接口(ModifyFlowLogAttribute)用于修改流日志属性
*/
async ModifyFlowLogAttribute(
req: ModifyFlowLogAttributeRequest,
cb?: (error: string, rep: ModifyFlowLogAttributeResponse) => void
): Promise<ModifyFlowLogAttributeResponse> {
return this.request("ModifyFlowLogAttribute", req, cb)
}
/**
* 修改弹性网卡服务质量
*/
async ModifyNetworkInterfaceQos(
req: ModifyNetworkInterfaceQosRequest,
cb?: (error: string, rep: ModifyNetworkInterfaceQosResponse) => void
): Promise<ModifyNetworkInterfaceQosResponse> {
return this.request("ModifyNetworkInterfaceQos", req, cb)
}
/**
* 本接口(DisassociateNetworkInterfaceSecurityGroups)用于弹性网卡解绑安全组。支持弹性网卡完全解绑安全组。
*/
async DisassociateNetworkInterfaceSecurityGroups(
req: DisassociateNetworkInterfaceSecurityGroupsRequest,
cb?: (error: string, rep: DisassociateNetworkInterfaceSecurityGroupsResponse) => void
): Promise<DisassociateNetworkInterfaceSecurityGroupsResponse> {
return this.request("DisassociateNetworkInterfaceSecurityGroups", req, cb)
}
/**
* 该接口用于调整具有带宽属性弹性公网IP的网络计费模式
* 支持BANDWIDTH_PREPAID_BY_MONTH和TRAFFIC_POSTPAID_BY_HOUR两种网络计费模式之间的切换。
* 每个弹性公网IP支持调整两次,次数超出则无法调整。
*/
async ModifyAddressInternetChargeType(
req: ModifyAddressInternetChargeTypeRequest,
cb?: (error: string, rep: ModifyAddressInternetChargeTypeResponse) => void
): Promise<ModifyAddressInternetChargeTypeResponse> {
return this.request("ModifyAddressInternetChargeType", req, cb)
}
/**
* 本接口(DescribeCcnAttachedInstances)用于查询云联网实例下已关联的网络实例。
*/
async DescribeCcnAttachedInstances(
req: DescribeCcnAttachedInstancesRequest,
cb?: (error: string, rep: DescribeCcnAttachedInstancesResponse) => void
): Promise<DescribeCcnAttachedInstancesResponse> {
return this.request("DescribeCcnAttachedInstances", req, cb)
}
/**
* 本接口(ResetRoutes)用于对某个路由表名称和所有路由策略(Route)进行重新设置。<br />
注意: 调用本接口是先删除当前路由表中所有路由策略, 再保存新提交的路由策略内容, 会引起网络中断。
*/
async ResetRoutes(
req: ResetRoutesRequest,
cb?: (error: string, rep: ResetRoutesResponse) => void
): Promise<ResetRoutesResponse> {
return this.request("ResetRoutes", req, cb)
}
/**
* 本接口(DescribeNetworkInterfaceLimit)根据CVM实例ID或弹性网卡ID查询弹性网卡配额,返回该CVM实例或弹性网卡能绑定的弹性网卡配额,以及弹性网卡可以分配的IP配额
*/
async DescribeNetworkInterfaceLimit(
req: DescribeNetworkInterfaceLimitRequest,
cb?: (error: string, rep: DescribeNetworkInterfaceLimitResponse) => void
): Promise<DescribeNetworkInterfaceLimitResponse> {
return this.request("DescribeNetworkInterfaceLimit", req, cb)
}
/**
* 本接口(DescribeNetDetects)用于查询网络探测列表。
*/
async DescribeNetDetects(
req: DescribeNetDetectsRequest,
cb?: (error: string, rep: DescribeNetDetectsResponse) => void
): Promise<DescribeNetDetectsResponse> {
return this.request("DescribeNetDetects", req, cb)
}
/**
* 本接口(DescribeVpcPrivateIpAddresses)用于查询VPC内网IP信息。<br />
只能查询已使用的IP信息,当查询未使用的IP时,本接口不会报错,但不会出现在返回结果里。
*/
async DescribeVpcPrivateIpAddresses(
req: DescribeVpcPrivateIpAddressesRequest,
cb?: (error: string, rep: DescribeVpcPrivateIpAddressesResponse) => void
): Promise<DescribeVpcPrivateIpAddressesResponse> {
return this.request("DescribeVpcPrivateIpAddresses", req, cb)
}
/**
* 本接口(DescribeGatewayFlowMonitorDetail)用于查询网关流量监控明细。
* 只支持单个网关实例查询。即入参 `VpnId`、 `DirectConnectGatewayId`、 `PeeringConnectionId`、 `NatId` 最多只支持传一个,且必须传一个。
* 如果网关有流量,但调用本接口没有返回数据,请在控制台对应网关详情页确认是否开启网关流量监控。
*/
async DescribeGatewayFlowMonitorDetail(
req: DescribeGatewayFlowMonitorDetailRequest,
cb?: (error: string, rep: DescribeGatewayFlowMonitorDetailResponse) => void
): Promise<DescribeGatewayFlowMonitorDetailResponse> {
return this.request("DescribeGatewayFlowMonitorDetail", req, cb)
}
/**
* 本接口(EnableGatewayFlowMonitor)用于开启网关流量监控。
*/
async EnableGatewayFlowMonitor(
req: EnableGatewayFlowMonitorRequest,
cb?: (error: string, rep: EnableGatewayFlowMonitorResponse) => void
): Promise<EnableGatewayFlowMonitorResponse> {
return this.request("EnableGatewayFlowMonitor", req, cb)
}
/**
* 本接口(UnassignIpv6Addresses)用于释放弹性网卡`IPv6`地址。<br />
本接口是异步完成,如需查询异步任务执行结果,请使用本接口返回的`RequestId`轮询`DescribeVpcTaskResult`接口。
*/
async UnassignIpv6Addresses(
req: UnassignIpv6AddressesRequest,
cb?: (error: string, rep: UnassignIpv6AddressesResponse) => void
): Promise<UnassignIpv6AddressesResponse> {
return this.request("UnassignIpv6Addresses", req, cb)
}
/**
* 将专线网关与NAT网关绑定,专线网关默认路由指向NAT网关
*/
async AssociateDirectConnectGatewayNatGateway(
req: AssociateDirectConnectGatewayNatGatewayRequest,
cb?: (error: string, rep: AssociateDirectConnectGatewayNatGatewayResponse) => void
): Promise<AssociateDirectConnectGatewayNatGatewayResponse> {
return this.request("AssociateDirectConnectGatewayNatGateway", req, cb)
}
/**
* 本接口(DeleteVpnConnection)用于删除VPN通道。
*/
async DeleteVpnConnection(
req: DeleteVpnConnectionRequest,
cb?: (error: string, rep: DeleteVpnConnectionResponse) => void
): Promise<DeleteVpnConnectionResponse> {
return this.request("DeleteVpnConnection", req, cb)
}
/**
* 是否接受终端节点连接请求。
*/
async EnableVpcEndPointConnect(
req: EnableVpcEndPointConnectRequest,
cb?: (error: string, rep: EnableVpcEndPointConnectResponse) => void
): Promise<EnableVpcEndPointConnectResponse> {
return this.request("EnableVpcEndPointConnect", req, cb)
}
/**
* 本接口(ModifyAddressTemplateGroupAttribute)用于修改IP地址模板集合
*/
async ModifyAddressTemplateGroupAttribute(
req: ModifyAddressTemplateGroupAttributeRequest,
cb?: (error: string, rep: ModifyAddressTemplateGroupAttributeResponse) => void
): Promise<ModifyAddressTemplateGroupAttributeResponse> {
return this.request("ModifyAddressTemplateGroupAttribute", req, cb)
}
/**
* 本接口(DescribeCustomerGatewayVendors)用于查询可支持的对端网关厂商信息。
*/
async DescribeCustomerGatewayVendors(
req?: DescribeCustomerGatewayVendorsRequest,
cb?: (error: string, rep: DescribeCustomerGatewayVendorsResponse) => void
): Promise<DescribeCustomerGatewayVendorsResponse> {
return this.request("DescribeCustomerGatewayVendors", req, cb)
}
/**
* 本接口 (DescribeAddresses) 用于查询一个或多个[弹性公网IP](https://cloud.tencent.com/document/product/213/1941)(简称 EIP)的详细信息。
* 如果参数为空,返回当前用户一定数量(Limit所指定的数量,默认为20)的 EIP。
*/
async DescribeAddresses(
req: DescribeAddressesRequest,
cb?: (error: string, rep: DescribeAddressesResponse) => void
): Promise<DescribeAddressesResponse> {
return this.request("DescribeAddresses", req, cb)
}
/**
* 本接口(DescribeVpcTaskResult)用于查询VPC任务执行结果。
*/
async DescribeVpcTaskResult(
req: DescribeVpcTaskResultRequest,
cb?: (error: string, rep: DescribeVpcTaskResultResponse) => void
): Promise<DescribeVpcTaskResultResponse> {
return this.request("DescribeVpcTaskResult", req, cb)
}
/**
* 该接口用于删除CDC的本地网关。
*/
async DeleteLocalGateway(
req: DeleteLocalGatewayRequest,
cb?: (error: string, rep: DeleteLocalGatewayResponse) => void
): Promise<DeleteLocalGatewayResponse> {
return this.request("DeleteLocalGateway", req, cb)
}
/**
* 本接口(ModifyNetworkAclEntries)用于修改(包括添加和删除)网络ACL的入站规则和出站规则。在NetworkAclEntrySet参数中:
* 若同时传入入站规则和出站规则,则重置原有的入站规则和出站规则,并分别导入传入的规则。
* 若仅传入入站规则,则仅重置原有的入站规则,并导入传入的规则,不影响原有的出站规则(若仅传入出站规则,处理方式类似入站方向)。
*/
async ModifyNetworkAclEntries(
req: ModifyNetworkAclEntriesRequest,
cb?: (error: string, rep: ModifyNetworkAclEntriesResponse) => void
): Promise<ModifyNetworkAclEntriesResponse> {
return this.request("ModifyNetworkAclEntries", req, cb)
}
/**
* 本接口(DetachCcnInstances)用于从云联网实例中解关联指定的网络实例。<br />
解关联网络实例后,相应的路由策略会一并删除。
*/
async DetachCcnInstances(
req: DetachCcnInstancesRequest,
cb?: (error: string, rep: DetachCcnInstancesResponse) => void
): Promise<DetachCcnInstancesResponse> {
return this.request("DetachCcnInstances", req, cb)
}
/**
* 本接口(AssociateNatGatewayAddress)用于NAT网关绑定弹性IP(EIP)。
*/
async AssociateNatGatewayAddress(
req: AssociateNatGatewayAddressRequest,
cb?: (error: string, rep: AssociateNatGatewayAddressResponse) => void
): Promise<AssociateNatGatewayAddressResponse> {
return this.request("AssociateNatGatewayAddress", req, cb)
}
/**
* 本接口(ModifyPrivateIpAddressesAttribute)用于修改弹性网卡内网IP属性。
*/
async ModifyPrivateIpAddressesAttribute(
req: ModifyPrivateIpAddressesAttributeRequest,
cb?: (error: string, rep: ModifyPrivateIpAddressesAttributeResponse) => void
): Promise<ModifyPrivateIpAddressesAttributeResponse> {
return this.request("ModifyPrivateIpAddressesAttribute", req, cb)
}
/**
* 修改终端节点属性。
*/
async ModifyVpcEndPointAttribute(
req: ModifyVpcEndPointAttributeRequest,
cb?: (error: string, rep: ModifyVpcEndPointAttributeResponse) => void
): Promise<ModifyVpcEndPointAttributeResponse> {
return this.request("ModifyVpcEndPointAttribute", req, cb)
}
/**
* 查询路由型VPN网关的目的路由
*/
async DescribeVpnGatewayRoutes(
req: DescribeVpnGatewayRoutesRequest,
cb?: (error: string, rep: DescribeVpnGatewayRoutesResponse) => void
): Promise<DescribeVpnGatewayRoutesResponse> {
return this.request("DescribeVpnGatewayRoutes", req, cb)
}
/**
* 修改VPN路由是否启用
*/
async ModifyVpnGatewayRoutes(
req: ModifyVpnGatewayRoutesRequest,
cb?: (error: string, rep: ModifyVpnGatewayRoutesResponse) => void
): Promise<ModifyVpnGatewayRoutesResponse> {
return this.request("ModifyVpnGatewayRoutes", req, cb)
}
/**
* 终端节点解绑安全组。
*/
async DisassociateVpcEndPointSecurityGroups(
req: DisassociateVpcEndPointSecurityGroupsRequest,
cb?: (error: string, rep: DisassociateVpcEndPointSecurityGroupsResponse) => void
): Promise<DisassociateVpcEndPointSecurityGroupsResponse> {
return this.request("DisassociateVpcEndPointSecurityGroups", req, cb)
}
/**
* 本接口(CreateDirectConnectGatewayCcnRoutes)用于创建专线网关的云联网路由(IDC网段)
*/
async CreateDirectConnectGatewayCcnRoutes(
req: CreateDirectConnectGatewayCcnRoutesRequest,
cb?: (error: string, rep: CreateDirectConnectGatewayCcnRoutesResponse) => void
): Promise<CreateDirectConnectGatewayCcnRoutesResponse> {
return this.request("CreateDirectConnectGatewayCcnRoutes", req, cb)
}
/**
* 接口用于删除带宽包资源,包括[弹性公网IP](https://cloud.tencent.com/document/product/213/1941)和[负载均衡](https://cloud.tencent.com/document/product/214/517)等
*/
async RemoveBandwidthPackageResources(
req: RemoveBandwidthPackageResourcesRequest,
cb?: (error: string, rep: RemoveBandwidthPackageResourcesResponse) => void
): Promise<RemoveBandwidthPackageResourcesResponse> {
return this.request("RemoveBandwidthPackageResources", req, cb)
}
/**
* 本接口(CloneSecurityGroup)用于根据存量的安全组,克隆创建出同样规则配置的安全组。仅克隆安全组及其规则信息,不会克隆安全组标签信息。
*/
async CloneSecurityGroup(
req: CloneSecurityGroupRequest,
cb?: (error: string, rep: CloneSecurityGroupResponse) => void
): Promise<CloneSecurityGroupResponse> {
return this.request("CloneSecurityGroup", req, cb)
}
/**
* 本接口(AssignPrivateIpAddresses)用于弹性网卡申请内网 IP。
* 一个弹性网卡支持绑定的IP地址是有限制的,更多资源限制信息详见<a href="/document/product/576/18527">弹性网卡使用限制</a>。
* 可以指定内网IP地址申请,内网IP地址类型不能为主IP,主IP已存在,不能修改,内网IP必须要弹性网卡所在子网内,而且不能被占用。
* 在弹性网卡上申请一个到多个辅助内网IP,接口会在弹性网卡所在子网网段内返回指定数量的辅助内网IP。
>?本接口为异步接口,可调用 [DescribeVpcTaskResult](https://cloud.tencent.com/document/api/215/59037) 接口查询任务执行结果,待任务执行成功后再进行其他操作。
>
*/
async AssignPrivateIpAddresses(
req: AssignPrivateIpAddressesRequest,
cb?: (error: string, rep: AssignPrivateIpAddressesResponse) => void
): Promise<AssignPrivateIpAddressesResponse> {
return this.request("AssignPrivateIpAddresses", req, cb)
}
/**
* 查询终端节点服务列表。
*/
async DescribeVpcEndPointService(
req: DescribeVpcEndPointServiceRequest,
cb?: (error: string, rep: DescribeVpcEndPointServiceResponse) => void
): Promise<DescribeVpcEndPointServiceResponse> {
return this.request("DescribeVpcEndPointService", req, cb)
}
/**
* 刷新专线直连nat路由,更新nat到专线的路由表
*/
async RefreshDirectConnectGatewayRouteToNatGateway(
req: RefreshDirectConnectGatewayRouteToNatGatewayRequest,
cb?: (error: string, rep: RefreshDirectConnectGatewayRouteToNatGatewayResponse) => void
): Promise<RefreshDirectConnectGatewayRouteToNatGatewayResponse> {
return this.request("RefreshDirectConnectGatewayRouteToNatGateway", req, cb)
}
/**
* 本接口(CreateAndAttachNetworkInterface)用于创建弹性网卡并绑定云服务器。
* 创建弹性网卡时可以指定内网IP,并且可以指定一个主IP,指定的内网IP必须在弹性网卡所在子网内,而且不能被占用。
* 创建弹性网卡时可以指定需要申请的内网IP数量,系统会随机生成内网IP地址。
* 一个弹性网卡支持绑定的IP地址是有限制的,更多资源限制信息详见<a href="/document/product/576/18527">弹性网卡使用限制</a>。
* 创建弹性网卡同时可以绑定已有安全组。
* 创建弹性网卡同时可以绑定标签, 应答里的标签列表代表添加成功的标签。
>?本接口为异步接口,可调用 [DescribeVpcTaskResult](https://cloud.tencent.com/document/api/215/59037) 接口查询任务执行结果,待任务执行成功后再进行其他操作。
>
*/
async CreateAndAttachNetworkInterface(
req: CreateAndAttachNetworkInterfaceRequest,
cb?: (error: string, rep: CreateAndAttachNetworkInterfaceResponse) => void
): Promise<CreateAndAttachNetworkInterfaceResponse> {
return this.request("CreateAndAttachNetworkInterface", req, cb)
}
/**
* 修改终端节点服务白名单属性。
*/
async ModifyVpcEndPointServiceWhiteList(
req: ModifyVpcEndPointServiceWhiteListRequest,
cb?: (error: string, rep: ModifyVpcEndPointServiceWhiteListResponse) => void
): Promise<ModifyVpcEndPointServiceWhiteListResponse> {
return this.request("ModifyVpcEndPointServiceWhiteList", req, cb)
}
/**
* 本接口(DescribeNatGateways)用于查询 NAT 网关。
*/
async DescribeNatGateways(
req: DescribeNatGatewaysRequest,
cb?: (error: string, rep: DescribeNatGatewaysResponse) => void
): Promise<DescribeNatGatewaysResponse> {
return this.request("DescribeNatGateways", req, cb)
}
/**
* 本接口(CreateSubnets)用于批量创建子网。
* 创建子网前必须创建好 VPC。
* 子网创建成功后,子网网段不能修改。子网网段必须在VPC网段内,可以和VPC网段相同(VPC有且只有一个子网时),建议子网网段在VPC网段内,预留网段给其他子网使用。
* 您可以创建的最小网段子网掩码为28(有16个IP地址),最大网段子网掩码为16(65,536个IP地址)。
* 同一个VPC内,多个子网的网段不能重叠。
* 子网创建后会自动关联到默认路由表。
* 创建子网同时可以绑定标签, 应答里的标签列表代表添加成功的标签。
*/
async CreateSubnets(
req: CreateSubnetsRequest,
cb?: (error: string, rep: CreateSubnetsResponse) => void
): Promise<CreateSubnetsResponse> {
return this.request("CreateSubnets", req, cb)
}
/**
* 本接口(SetCcnRegionBandwidthLimits)用于设置云联网(CCN)各地域出带宽上限,或者地域间带宽上限。
*/
async SetCcnRegionBandwidthLimits(
req: SetCcnRegionBandwidthLimitsRequest,
cb?: (error: string, rep: SetCcnRegionBandwidthLimitsResponse) => void
): Promise<SetCcnRegionBandwidthLimitsResponse> {
return this.request("SetCcnRegionBandwidthLimits", req, cb)
}
/**
* 本接口(ReplaceRouteTableAssociation)用于修改子网(Subnet)关联的路由表(RouteTable)。
* 一个子网只能关联一个路由表。
*/
async ReplaceRouteTableAssociation(
req: ReplaceRouteTableAssociationRequest,
cb?: (error: string, rep: ReplaceRouteTableAssociationResponse) => void
): Promise<ReplaceRouteTableAssociationResponse> {
return this.request("ReplaceRouteTableAssociation", req, cb)
}
/**
* 本接口(DescribeTemplateLimits)用于查询参数模板配额列表。
*/
async DescribeTemplateLimits(
req?: DescribeTemplateLimitsRequest,
cb?: (error: string, rep: DescribeTemplateLimitsResponse) => void
): Promise<DescribeTemplateLimitsResponse> {
return this.request("DescribeTemplateLimits", req, cb)
}
/**
* 本接口(CheckNetDetectState)用于验证网络探测。
*/
async CheckNetDetectState(
req: CheckNetDetectStateRequest,
cb?: (error: string, rep: CheckNetDetectStateResponse) => void
): Promise<CheckNetDetectStateResponse> {
return this.request("CheckNetDetectState", req, cb)
}
/**
* 本接口(DescribeDhcpIps)用于查询DhcpIp列表
*/
async DescribeDhcpIps(
req: DescribeDhcpIpsRequest,
cb?: (error: string, rep: DescribeDhcpIpsResponse) => void
): Promise<DescribeDhcpIpsResponse> {
return this.request("DescribeDhcpIps", req, cb)
}
/**
* 本接口(InquiryPriceResetVpnGatewayInternetMaxBandwidth)调整VPN网关带宽上限询价。
*/
async InquiryPriceResetVpnGatewayInternetMaxBandwidth(
req: InquiryPriceResetVpnGatewayInternetMaxBandwidthRequest,
cb?: (error: string, rep: InquiryPriceResetVpnGatewayInternetMaxBandwidthResponse) => void
): Promise<InquiryPriceResetVpnGatewayInternetMaxBandwidthResponse> {
return this.request("InquiryPriceResetVpnGatewayInternetMaxBandwidth", req, cb)
}
/**
* 本接口(DeleteDirectConnectGatewayCcnRoutes)用于删除专线网关的云联网路由(IDC网段)
*/
async DeleteDirectConnectGatewayCcnRoutes(
req: DeleteDirectConnectGatewayCcnRoutesRequest,
cb?: (error: string, rep: DeleteDirectConnectGatewayCcnRoutesResponse) => void
): Promise<DeleteDirectConnectGatewayCcnRoutesResponse> {
return this.request("DeleteDirectConnectGatewayCcnRoutes", req, cb)
}
/**
* 本接口(RejectAttachCcnInstances)用于跨账号关联实例时,云联网所有者拒绝关联操作。
*/
async RejectAttachCcnInstances(
req: RejectAttachCcnInstancesRequest,
cb?: (error: string, rep: RejectAttachCcnInstancesResponse) => void
): Promise<RejectAttachCcnInstancesResponse> {
return this.request("RejectAttachCcnInstances", req, cb)
}
/**
* 本接口(MigrateNetworkInterface)用于弹性网卡迁移。
本接口是异步完成,如需查询异步任务执行结果,请使用本接口返回的`RequestId`轮询`DescribeVpcTaskResult`接口。
*/
async MigrateNetworkInterface(
req: MigrateNetworkInterfaceRequest,
cb?: (error: string, rep: MigrateNetworkInterfaceResponse) => void
): Promise<MigrateNetworkInterfaceResponse> {
return this.request("MigrateNetworkInterface", req, cb)
}
/**
* 本接口(ModifyAddressesBandwidth)用于调整[弹性公网IP](https://cloud.tencent.com/document/product/213/1941)(简称EIP)带宽,支持后付费EIP, 预付费EIP和带宽包EIP
*/
async ModifyAddressesBandwidth(
req: ModifyAddressesBandwidthRequest,
cb?: (error: string, rep: ModifyAddressesBandwidthResponse) => void
): Promise<ModifyAddressesBandwidthResponse> {
return this.request("ModifyAddressesBandwidth", req, cb)
}
/**
* 本接口(CreateNatGatewayDestinationIpPortTranslationNatRule)用于创建NAT网关端口转发规则。
*/
async CreateNatGatewayDestinationIpPortTranslationNatRule(
req: CreateNatGatewayDestinationIpPortTranslationNatRuleRequest,
cb?: (error: string, rep: CreateNatGatewayDestinationIpPortTranslationNatRuleResponse) => void
): Promise<CreateNatGatewayDestinationIpPortTranslationNatRuleResponse> {
return this.request("CreateNatGatewayDestinationIpPortTranslationNatRule", req, cb)
}
/**
* 本接口(CreateSubnet)用于创建子网。
* 创建子网前必须创建好 VPC。
* 子网创建成功后,子网网段不能修改。子网网段必须在VPC网段内,可以和VPC网段相同(VPC有且只有一个子网时),建议子网网段在VPC网段内,预留网段给其他子网使用。
* 您可以创建的最小网段子网掩码为28(有16个IP地址),最大网段子网掩码为16(65,536个IP地址)。
* 同一个VPC内,多个子网的网段不能重叠。
* 子网创建后会自动关联到默认路由表。
* 创建子网同时可以绑定标签, 应答里的标签列表代表添加成功的标签。
*/
async CreateSubnet(
req: CreateSubnetRequest,
cb?: (error: string, rep: CreateSubnetResponse) => void
): Promise<CreateSubnetResponse> {
return this.request("CreateSubnet", req, cb)
}
/**
* 该接口用于给IPv6地址初次分配公网带宽
*/
async AllocateIp6AddressesBandwidth(
req: AllocateIp6AddressesBandwidthRequest,
cb?: (error: string, rep: AllocateIp6AddressesBandwidthResponse) => void
): Promise<AllocateIp6AddressesBandwidthResponse> {
return this.request("AllocateIp6AddressesBandwidth", req, cb)
}
/**
* 本接口(DeleteDhcpIp)用于删除DhcpIp。
>?本接口为异步接口,可调用 [DescribeVpcTaskResult](https://cloud.tencent.com/document/api/215/59037) 接口查询任务执行结果,待任务执行成功后再进行其他操作。
>
*/
async DeleteDhcpIp(
req: DeleteDhcpIpRequest,
cb?: (error: string, rep: DeleteDhcpIpResponse) => void
): Promise<DeleteDhcpIpResponse> {
return this.request("DeleteDhcpIp", req, cb)
}
/**
* 本接口(ModifyAddressTemplateAttribute)用于修改IP地址模板
*/
async ModifyAddressTemplateAttribute(
req: ModifyAddressTemplateAttributeRequest,
cb?: (error: string, rep: ModifyAddressTemplateAttributeResponse) => void
): Promise<ModifyAddressTemplateAttributeResponse> {
return this.request("ModifyAddressTemplateAttribute", req, cb)
}
/**
* 本接口(AcceptAttachCcnInstances)用于跨账号关联实例时,云联网所有者接受并同意关联操作。
*/
async AcceptAttachCcnInstances(
req: AcceptAttachCcnInstancesRequest,
cb?: (error: string, rep: AcceptAttachCcnInstancesResponse) => void
): Promise<AcceptAttachCcnInstancesResponse> {
return this.request("AcceptAttachCcnInstances", req, cb)
}
/**
* 删除模版对象中的IP地址、协议端口、IP地址组、协议端口组。当前仅支持北京、泰国、北美地域请求。
*/
async DeleteTemplateMember(
req: DeleteTemplateMemberRequest,
cb?: (error: string, rep: DeleteTemplateMemberResponse) => void
): Promise<DeleteTemplateMemberResponse> {
return this.request("DeleteTemplateMember", req, cb)
}
/**
* 本接口(DeleteServiceTemplateGroup)用于删除协议端口模板集合
*/
async DeleteServiceTemplateGroup(
req: DeleteServiceTemplateGroupRequest,
cb?: (error: string, rep: DeleteServiceTemplateGroupResponse) => void
): Promise<DeleteServiceTemplateGroupResponse> {
return this.request("DeleteServiceTemplateGroup", req, cb)
}
/**
* 本接口(DescribeGatewayFlowQos)用于查询网关来访IP流控带宽。
*/
async DescribeGatewayFlowQos(
req: DescribeGatewayFlowQosRequest,
cb?: (error: string, rep: DescribeGatewayFlowQosResponse) => void
): Promise<DescribeGatewayFlowQosResponse> {
return this.request("DescribeGatewayFlowQos", req, cb)
}
/**
* 修改模版对象中的IP地址、协议端口、IP地址组、协议端口组。当前仅支持北京、泰国、北美地域请求。
*/
async ModifyTemplateMember(
req: ModifyTemplateMemberRequest,
cb?: (error: string, rep: ModifyTemplateMemberResponse) => void
): Promise<ModifyTemplateMemberResponse> {
return this.request("ModifyTemplateMember", req, cb)
}
/**
* 将专线网关与NAT网关解绑,解绑之后,专线网关将不能通过NAT网关访问公网
*/
async DisassociateDirectConnectGatewayNatGateway(
req: DisassociateDirectConnectGatewayNatGatewayRequest,
cb?: (error: string, rep: DisassociateDirectConnectGatewayNatGatewayResponse) => void
): Promise<DisassociateDirectConnectGatewayNatGatewayResponse> {
return this.request("DisassociateDirectConnectGatewayNatGateway", req, cb)
}
/**
* 1. 该接口用于查询账户下的IPV6转换实例及其绑定的转换规则信息
2. 支持过滤查询
*/
async DescribeIp6Translators(
req: DescribeIp6TranslatorsRequest,
cb?: (error: string, rep: DescribeIp6TranslatorsResponse) => void
): Promise<DescribeIp6TranslatorsResponse> {
return this.request("DescribeIp6Translators", req, cb)
}
/**
* 本接口(ResetAttachCcnInstances)用于跨账号关联实例申请过期时,重新申请关联操作。
*/
async ResetAttachCcnInstances(
req: ResetAttachCcnInstancesRequest,
cb?: (error: string, rep: ResetAttachCcnInstancesResponse) => void
): Promise<ResetAttachCcnInstancesResponse> {
return this.request("ResetAttachCcnInstances", req, cb)
}
/**
* 本接口(DeleteSecurityGroupPolicies)用于用于删除安全组规则(SecurityGroupPolicy)。
* SecurityGroupPolicySet.Version 用于指定要操作的安全组的版本。传入 Version 版本号若不等于当前安全组的最新版本,将返回失败;若不传 Version 则直接删除指定PolicyIndex的规则。
*/
async DeleteSecurityGroupPolicies(
req: DeleteSecurityGroupPoliciesRequest,
cb?: (error: string, rep: DeleteSecurityGroupPoliciesResponse) => void
): Promise<DeleteSecurityGroupPoliciesResponse> {
return this.request("DeleteSecurityGroupPolicies", req, cb)
}
/**
* 本接口(CreateVpc)用于创建私有网络(VPC)。
* 用户可以创建的最小网段子网掩码为28(有16个IP地址),最大网段子网掩码为16(65,536个IP地址),如果需要规划VPC网段请参见[网络规划](https://cloud.tencent.com/document/product/215/30313)。
* 同一个地域能创建的VPC资源个数也是有限制的,详见 <a href="https://cloud.tencent.com/doc/product/215/537" title="VPC使用限制">VPC使用限制</a>,如果需要申请更多资源,请提交[工单申请](https://console.cloud.tencent.com/workorder/category)。
* 创建VPC同时可以绑定标签, 应答里的标签列表代表添加成功的标签。
*/
async CreateVpc(
req: CreateVpcRequest,
cb?: (error: string, rep: CreateVpcResponse) => void
): Promise<CreateVpcResponse> {
return this.request("CreateVpc", req, cb)
}
/**
* 该接口用于修改IPV6转换规则,当前仅支持修改转换规则名称,IPV4地址和IPV4端口号
*/
async ModifyIp6Rule(
req: ModifyIp6RuleRequest,
cb?: (error: string, rep: ModifyIp6RuleResponse) => void
): Promise<ModifyIp6RuleResponse> {
return this.request("ModifyIp6Rule", req, cb)
}
/**
* 接口用于添加带宽包资源,包括[弹性公网IP](https://cloud.tencent.com/document/product/213/1941)和[负载均衡](https://cloud.tencent.com/document/product/214/517)等
*/
async AddBandwidthPackageResources(
req: AddBandwidthPackageResourcesRequest,
cb?: (error: string, rep: AddBandwidthPackageResourcesResponse) => void
): Promise<AddBandwidthPackageResourcesResponse> {
return this.request("AddBandwidthPackageResources", req, cb)
}
/**
* 本接口(AssignIpv6SubnetCidrBlock)用于分配IPv6子网段。
* 给子网分配 `IPv6` 网段,要求子网所属 `VPC` 已获得 `IPv6` 网段。如果尚未分配,请先通过接口 `AssignIpv6CidrBlock` 给子网所属 `VPC` 分配一个 `IPv6` 网段。否则无法分配 `IPv6` 子网段。
* 每个子网只能分配一个IPv6网段。
*/
async AssignIpv6SubnetCidrBlock(
req: AssignIpv6SubnetCidrBlockRequest,
cb?: (error: string, rep: AssignIpv6SubnetCidrBlockResponse) => void
): Promise<AssignIpv6SubnetCidrBlockResponse> {
return this.request("AssignIpv6SubnetCidrBlock", req, cb)
}
/**
* 本接口(DescribeVpnGatewayCcnRoutes)用于查询VPN网关云联网路由
*/
async DescribeVpnGatewayCcnRoutes(
req: DescribeVpnGatewayCcnRoutesRequest,
cb?: (error: string, rep: DescribeVpnGatewayCcnRoutesResponse) => void
): Promise<DescribeVpnGatewayCcnRoutesResponse> {
return this.request("DescribeVpnGatewayCcnRoutes", req, cb)
}
/**
* 本接口 (AllocateAddresses) 用于申请一个或多个[弹性公网IP](https://cloud.tencent.com/document/product/213/1941)(简称 EIP)。
* EIP 是专为动态云计算设计的静态 IP 地址。借助 EIP,您可以快速将 EIP 重新映射到您的另一个实例上,从而屏蔽实例故障。
* 您的 EIP 与腾讯云账户相关联,而不是与某个实例相关联。在您选择显式释放该地址,或欠费超过24小时之前,它会一直与您的腾讯云账户保持关联。
* 一个腾讯云账户在每个地域能申请的 EIP 最大配额有所限制,可参见 [EIP 产品简介](https://cloud.tencent.com/document/product/213/5733),上述配额可通过 DescribeAddressQuota 接口获取。
*/
async AllocateAddresses(
req: AllocateAddressesRequest,
cb?: (error: string, rep: AllocateAddressesResponse) => void
): Promise<AllocateAddressesResponse> {
return this.request("AllocateAddresses", req, cb)
}
/**
* 本接口(CheckAssistantCidr)用于检查辅助CIDR是否与存量路由、对等连接(对端VPC的CIDR)等资源存在冲突。如果存在重叠,则返回重叠的资源。(接口灰度中,如需使用请提工单。)
* 检测辅助CIDR是否与当前VPC的主CIDR和辅助CIDR存在重叠。
* 检测辅助CIDR是否与当前VPC的路由的目的端存在重叠。
* 检测辅助CIDR是否与当前VPC的对等连接,对端VPC下的主CIDR或辅助CIDR存在重叠。
*/
async CheckAssistantCidr(
req: CheckAssistantCidrRequest,
cb?: (error: string, rep: CheckAssistantCidrResponse) => void
): Promise<CheckAssistantCidrResponse> {
return this.request("CheckAssistantCidr", req, cb)
}
/**
* 本接口(DescribeVpcIpv6Addresses)用于查询 `VPC` `IPv6` 信息。
只能查询已使用的`IPv6`信息,当查询未使用的IP时,本接口不会报错,但不会出现在返回结果里。
*/
async DescribeVpcIpv6Addresses(
req: DescribeVpcIpv6AddressesRequest,
cb?: (error: string, rep: DescribeVpcIpv6AddressesResponse) => void
): Promise<DescribeVpcIpv6AddressesResponse> {
return this.request("DescribeVpcIpv6Addresses", req, cb)
}
/**
* 该接口用于查询IPV6地址信息
*/
async DescribeIp6Addresses(
req: DescribeIp6AddressesRequest,
cb?: (error: string, rep: DescribeIp6AddressesResponse) => void
): Promise<DescribeIp6AddressesResponse> {
return this.request("DescribeIp6Addresses", req, cb)
}
/**
* 本接口(RenewVpnGateway)用于预付费(包年包月)VPN网关续费。目前只支持IPSEC网关。
*/
async RenewVpnGateway(
req: RenewVpnGatewayRequest,
cb?: (error: string, rep: RenewVpnGatewayResponse) => void
): Promise<RenewVpnGatewayResponse> {
return this.request("RenewVpnGateway", req, cb)
}
/**
* 本接口(DescribeVpcs)用于查询私有网络列表。
*/
async DescribeVpcs(
req: DescribeVpcsRequest,
cb?: (error: string, rep: DescribeVpcsResponse) => void
): Promise<DescribeVpcsResponse> {
return this.request("DescribeVpcs", req, cb)
}
/**
* 本接口(AttachCcnInstances)用于将网络实例加载到云联网实例中,网络实例包括VPC和专线网关。<br />
每个云联网能够关联的网络实例个数是有限的,详请参考产品文档。如果需要扩充请联系在线客服。
*/
async AttachCcnInstances(
req: AttachCcnInstancesRequest,
cb?: (error: string, rep: AttachCcnInstancesResponse) => void
): Promise<AttachCcnInstancesResponse> {
return this.request("AttachCcnInstances", req, cb)
}
/**
* 本接口 (AssociateAddress) 用于将[弹性公网IP](https://cloud.tencent.com/document/product/213/1941)(简称 EIP)绑定到实例或弹性网卡的指定内网 IP 上。
* 将 EIP 绑定到实例(CVM)上,其本质是将 EIP 绑定到实例上主网卡的主内网 IP 上。
* 将 EIP 绑定到主网卡的主内网IP上,绑定过程会把其上绑定的普通公网 IP 自动解绑并释放。
* 将 EIP 绑定到指定网卡的内网 IP上(非主网卡的主内网IP),则必须先解绑该 EIP,才能再绑定新的。
* 将 EIP 绑定到NAT网关,请使用接口[AssociateNatGatewayAddress](https://cloud.tencent.com/document/product/215/36722)
* EIP 如果欠费或被封堵,则不能被绑定。
* 只有状态为 UNBIND 的 EIP 才能够被绑定。
*/
async AssociateAddress(
req: AssociateAddressRequest,
cb?: (error: string, rep: AssociateAddressResponse) => void
): Promise<AssociateAddressResponse> {
return this.request("AssociateAddress", req, cb)
}
/**
* 本接口(DeleteCustomerGateway)用于删除对端网关。
*/
async DeleteCustomerGateway(
req: DeleteCustomerGatewayRequest,
cb?: (error: string, rep: DeleteCustomerGatewayResponse) => void
): Promise<DeleteCustomerGatewayResponse> {
return this.request("DeleteCustomerGateway", req, cb)
}
/**
* 本接口(DeleteSubnet)用于用于删除子网(Subnet)。
* 删除子网前,请清理该子网下所有资源,包括云服务器、负载均衡、云数据、noSql、弹性网卡等资源。
*/
async DeleteSubnet(
req: DeleteSubnetRequest,
cb?: (error: string, rep: DeleteSubnetResponse) => void
): Promise<DeleteSubnetResponse> {
return this.request("DeleteSubnet", req, cb)
}
/**
* 本接口(AttachClassicLinkVpc)用于创建私有网络和基础网络设备互通。
* 私有网络和基础网络设备必须在同一个地域。
* 私有网络和基础网络的区别详见vpc产品文档-<a href="https://cloud.tencent.com/document/product/215/30720">私有网络与基础网络</a>。
>?本接口为异步接口,可调用 [DescribeVpcTaskResult](https://cloud.tencent.com/document/api/215/59037) 接口查询任务执行结果,待任务执行成功后再进行其他操作。
>
*/
async AttachClassicLinkVpc(
req: AttachClassicLinkVpcRequest,
cb?: (error: string, rep: AttachClassicLinkVpcResponse) => void
): Promise<AttachClassicLinkVpcResponse> {
return this.request("AttachClassicLinkVpc", req, cb)
}
/**
* 本接口(DisassociateNatGatewayAddress)用于NAT网关解绑弹性IP。
*/
async DisassociateNatGatewayAddress(
req: DisassociateNatGatewayAddressRequest,
cb?: (error: string, rep: DisassociateNatGatewayAddressResponse) => void
): Promise<DisassociateNatGatewayAddressResponse> {
return this.request("DisassociateNatGatewayAddress", req, cb)
}
/**
* 该接口用于查询CDC的本地网关。
*/
async DescribeLocalGateway(
req: DescribeLocalGatewayRequest,
cb?: (error: string, rep: DescribeLocalGatewayResponse) => void
): Promise<DescribeLocalGatewayResponse> {
return this.request("DescribeLocalGateway", req, cb)
}
/**
* 本接口(MigratePrivateIpAddress)用于弹性网卡内网IP迁移。
* 该接口用于将一个内网IP从一个弹性网卡上迁移到另外一个弹性网卡,主IP地址不支持迁移。
* 迁移前后的弹性网卡必须在同一个子网内。
本接口是异步完成,如需查询异步任务执行结果,请使用本接口返回的`RequestId`轮询`DescribeVpcTaskResult`接口。
*/
async MigratePrivateIpAddress(
req: MigratePrivateIpAddressRequest,
cb?: (error: string, rep: MigratePrivateIpAddressResponse) => void
): Promise<MigratePrivateIpAddressResponse> {
return this.request("MigratePrivateIpAddress", req, cb)
}
/**
* 本接口(DescribeFlowLogs)用于查询获取流日志集合
*/
async DescribeFlowLogs(
req: DescribeFlowLogsRequest,
cb?: (error: string, rep: DescribeFlowLogsResponse) => void
): Promise<DescribeFlowLogsResponse> {
return this.request("DescribeFlowLogs", req, cb)
}
/**
* 本接口(DeleteDirectConnectGateway)用于删除专线网关。
<li>如果是 NAT 网关,删除专线网关后,NAT 规则以及 ACL 策略都被清理了。</li>
<li>删除专线网关后,系统会删除路由表中跟该专线网关相关的路由策略。</li>
本接口是异步完成,如需查询异步任务执行结果,请使用本接口返回的`RequestId`轮询`QueryTask`接口
*/
async DeleteDirectConnectGateway(
req: DeleteDirectConnectGatewayRequest,
cb?: (error: string, rep: DeleteDirectConnectGatewayResponse) => void
): Promise<DeleteDirectConnectGatewayResponse> {
return this.request("DeleteDirectConnectGateway", req, cb)
}
/**
* 本接口(DescribeDirectConnectGatewayCcnRoutes)用于查询专线网关的云联网路由(IDC网段)
*/
async DescribeDirectConnectGatewayCcnRoutes(
req: DescribeDirectConnectGatewayCcnRoutesRequest,
cb?: (error: string, rep: DescribeDirectConnectGatewayCcnRoutesResponse) => void
): Promise<DescribeDirectConnectGatewayCcnRoutesResponse> {
return this.request("DescribeDirectConnectGatewayCcnRoutes", req, cb)
}
/**
* 本接口(CreateNetworkInterface)用于创建弹性网卡。
* 创建弹性网卡时可以指定内网IP,并且可以指定一个主IP,指定的内网IP必须在弹性网卡所在子网内,而且不能被占用。
* 创建弹性网卡时可以指定需要申请的内网IP数量,系统会随机生成内网IP地址。
* 一个弹性网卡支持绑定的IP地址是有限制的,更多资源限制信息详见<a href="/document/product/576/18527">弹性网卡使用限制</a>。
* 创建弹性网卡同时可以绑定已有安全组。
* 创建弹性网卡同时可以绑定标签, 应答里的标签列表代表添加成功的标签。
>?本接口为异步接口,可调用 [DescribeVpcTaskResult](https://cloud.tencent.com/document/api/215/59037) 接口查询任务执行结果,待任务执行成功后再进行其他操作。
>
*/
async CreateNetworkInterface(
req: CreateNetworkInterfaceRequest,
cb?: (error: string, rep: CreateNetworkInterfaceResponse) => void
): Promise<CreateNetworkInterfaceResponse> {
return this.request("CreateNetworkInterface", req, cb)
}
/**
* 接口支持删除共享带宽包,包括[设备带宽包](https://cloud.tencent.com/document/product/684/15246#.E8.AE.BE.E5.A4.87.E5.B8.A6.E5.AE.BD.E5.8C.85)和[IP带宽包](https://cloud.tencent.com/document/product/684/15246#ip-.E5.B8.A6.E5.AE.BD.E5.8C.85)
*/
async DeleteBandwidthPackage(
req: DeleteBandwidthPackageRequest,
cb?: (error: string, rep: DeleteBandwidthPackageResponse) => void
): Promise<DeleteBandwidthPackageResponse> {
return this.request("DeleteBandwidthPackage", req, cb)
}
/**
* 本接口(ModifySecurityGroupPolicies)用于重置安全组出站和入站规则(SecurityGroupPolicy)。
<ul>
<li>该接口不支持自定义索引 PolicyIndex。</li>
<li>在 SecurityGroupPolicySet 参数中:<ul>
<li> 如果指定 SecurityGroupPolicySet.Version 为0, 表示清空所有规则,并忽略 Egress 和 Ingress。</li>
<li> 如果指定 SecurityGroupPolicySet.Version 不为0, 在添加出站和入站规则(Egress 和 Ingress)时:<ul>
<li>Protocol 字段支持输入 TCP, UDP, ICMP, ICMPV6, GRE, ALL。</li>
<li>CidrBlock 字段允许输入符合 cidr 格式标准的任意字符串。(展开)在基础网络中,如果 CidrBlock 包含您的账户内的云服务器之外的设备在腾讯云的内网 IP,并不代表此规则允许您访问这些设备,租户之间网络隔离规则优先于安全组中的内网规则。</li>
<li>Ipv6CidrBlock 字段允许输入符合 IPv6 cidr 格式标准的任意字符串。(展开)在基础网络中,如果Ipv6CidrBlock 包含您的账户内的云服务器之外的设备在腾讯云的内网 IPv6,并不代表此规则允许您访问这些设备,租户之间网络隔离规则优先于安全组中的内网规则。</li>
<li>SecurityGroupId 字段允许输入与待修改的安全组位于相同项目中的安全组 ID,包括这个安全组 ID 本身,代表安全组下所有云服务器的内网 IP。使用这个字段时,这条规则用来匹配网络报文的过程中会随着被使用的这个ID所关联的云服务器变化而变化,不需要重新修改。</li>
<li>Port 字段允许输入一个单独端口号,或者用减号分隔的两个端口号代表端口范围,例如80或8000-8010。只有当 Protocol 字段是 TCP 或 UDP 时,Port 字段才被接受。</li>
<li>Action 字段只允许输入 ACCEPT 或 DROP。</li>
<li>CidrBlock, Ipv6CidrBlock, SecurityGroupId, AddressTemplate 四者是排他关系,不允许同时输入,Protocol + Port 和 ServiceTemplate 二者是排他关系,不允许同时输入。</li>
</ul></li></ul></li>
</ul>
*/
async ModifySecurityGroupPolicies(
req: ModifySecurityGroupPoliciesRequest,
cb?: (error: string, rep: ModifySecurityGroupPoliciesResponse) => void
): Promise<ModifySecurityGroupPoliciesResponse> {
return this.request("ModifySecurityGroupPolicies", req, cb)
}
/**
* 本接口(DescribeNetDetectStates)用于查询网络探测验证结果列表。
*/
async DescribeNetDetectStates(
req: DescribeNetDetectStatesRequest,
cb?: (error: string, rep: DescribeNetDetectStatesResponse) => void
): Promise<DescribeNetDetectStatesResponse> {
return this.request("DescribeNetDetectStates", req, cb)
}
/**
* 本接口(DescribeCcns)用于查询云联网(CCN)列表。
*/
async DescribeCcns(
req: DescribeCcnsRequest,
cb?: (error: string, rep: DescribeCcnsResponse) => void
): Promise<DescribeCcnsResponse> {
return this.request("DescribeCcns", req, cb)
}
/**
* 1. 该接口用于释放IPV6转换实例,支持批量。
2. 如果IPV6转换实例建立有转换规则,会一并删除。
*/
async DeleteIp6Translators(
req: DeleteIp6TranslatorsRequest,
cb?: (error: string, rep: DeleteIp6TranslatorsResponse) => void
): Promise<DeleteIp6TranslatorsResponse> {
return this.request("DeleteIp6Translators", req, cb)
}
/**
* 本接口(DeleteCcn)用于删除云联网。
* 删除后,云联网关联的所有实例间路由将被删除,网络将会中断,请务必确认
* 删除云联网是不可逆的操作,请谨慎处理。
*/
async DeleteCcn(
req: DeleteCcnRequest,
cb?: (error: string, rep: DeleteCcnResponse) => void
): Promise<DeleteCcnResponse> {
return this.request("DeleteCcn", req, cb)
}
/**
* 创建终端节点服务。
*/
async CreateVpcEndPointService(
req: CreateVpcEndPointServiceRequest,
cb?: (error: string, rep: CreateVpcEndPointServiceResponse) => void
): Promise<CreateVpcEndPointServiceResponse> {
return this.request("CreateVpcEndPointService", req, cb)
}
/**
* 本接口(HaVipDisassociateAddressIp)用于将高可用虚拟IP(HAVIP)已绑定的弹性公网IP(EIP)解除绑定。<br />
本接口是异步完成,如需查询异步任务执行结果,请使用本接口返回的`RequestId`轮询`DescribeVpcTaskResult`接口。
*/
async HaVipDisassociateAddressIp(
req: HaVipDisassociateAddressIpRequest,
cb?: (error: string, rep: HaVipDisassociateAddressIpResponse) => void
): Promise<HaVipDisassociateAddressIpResponse> {
return this.request("HaVipDisassociateAddressIp", req, cb)
}
/**
* 本接口(ModifyVpnGatewayCcnRoutes)用于修改VPN网关云联网路由
*/
async ModifyVpnGatewayCcnRoutes(
req: ModifyVpnGatewayCcnRoutesRequest,
cb?: (error: string, rep: ModifyVpnGatewayCcnRoutesResponse) => void
): Promise<ModifyVpnGatewayCcnRoutesResponse> {
return this.request("ModifyVpnGatewayCcnRoutes", req, cb)
}
/**
* 本接口(DetachNetworkInterface)用于弹性网卡解绑云服务器。
本接口是异步完成,如需查询异步任务执行结果,请使用本接口返回的`RequestId`轮询`DescribeVpcTaskResult`接口。
*/
async DetachNetworkInterface(
req: DetachNetworkInterfaceRequest,
cb?: (error: string, rep: DetachNetworkInterfaceResponse) => void
): Promise<DetachNetworkInterfaceResponse> {
return this.request("DetachNetworkInterface", req, cb)
}
/**
* 本接口(ModifyServiceTemplateGroupAttribute)用于修改协议端口模板集合。
*/
async ModifyServiceTemplateGroupAttribute(
req: ModifyServiceTemplateGroupAttributeRequest,
cb?: (error: string, rep: ModifyServiceTemplateGroupAttributeResponse) => void
): Promise<ModifyServiceTemplateGroupAttributeResponse> {
return this.request("ModifyServiceTemplateGroupAttribute", req, cb)
}
/**
* 本接口(DeleteAssistantCidr)用于删除辅助CIDR。(接口灰度中,如需使用请提工单。)
*/
async DeleteAssistantCidr(
req: DeleteAssistantCidrRequest,
cb?: (error: string, rep: DeleteAssistantCidrResponse) => void
): Promise<DeleteAssistantCidrResponse> {
return this.request("DeleteAssistantCidr", req, cb)
}
/**
* 本接口(DeleteVpnGatewayCcnRoutes)用于删除VPN网关路由
*/
async DeleteVpnGatewayRoutes(
req: DeleteVpnGatewayRoutesRequest,
cb?: (error: string, rep: DeleteVpnGatewayRoutesResponse) => void
): Promise<DeleteVpnGatewayRoutesResponse> {
return this.request("DeleteVpnGatewayRoutes", req, cb)
}
/**
* 本接口(ModifyDhcpIpAttribute)用于修改DhcpIp属性
*/
async ModifyDhcpIpAttribute(
req: ModifyDhcpIpAttributeRequest,
cb?: (error: string, rep: ModifyDhcpIpAttributeResponse) => void
): Promise<ModifyDhcpIpAttributeResponse> {
return this.request("ModifyDhcpIpAttribute", req, cb)
}
/**
* 本接口(ModifyCcnRegionBandwidthLimitsType)用于修改后付费云联网实例修改带宽限速策略。
*/
async ModifyCcnRegionBandwidthLimitsType(
req: ModifyCcnRegionBandwidthLimitsTypeRequest,
cb?: (error: string, rep: ModifyCcnRegionBandwidthLimitsTypeResponse) => void
): Promise<ModifyCcnRegionBandwidthLimitsTypeResponse> {
return this.request("ModifyCcnRegionBandwidthLimitsType", req, cb)
}
/**
* 本接口 (DescribeBandwidthPackageResources) 用于根据共享带宽包唯一ID查询共享带宽包内的资源列表,支持按条件过滤查询结果和分页查询。
*/
async DescribeBandwidthPackageResources(
req: DescribeBandwidthPackageResourcesRequest,
cb?: (error: string, rep: DescribeBandwidthPackageResourcesResponse) => void
): Promise<DescribeBandwidthPackageResourcesResponse> {
return this.request("DescribeBandwidthPackageResources", req, cb)
}
/**
* 修改CCN关联实例属性,目前仅修改备注description
*/
async ModifyCcnAttachedInstancesAttribute(
req: ModifyCcnAttachedInstancesAttributeRequest,
cb?: (error: string, rep: ModifyCcnAttachedInstancesAttributeResponse) => void
): Promise<ModifyCcnAttachedInstancesAttributeResponse> {
return this.request("ModifyCcnAttachedInstancesAttribute", req, cb)
}
/**
* 本接口(DeleteNatGatewaySourceIpTranslationNatRule)用于删除NAT网关端口SNAT转发规则。
*/
async DeleteNatGatewaySourceIpTranslationNatRule(
req: DeleteNatGatewaySourceIpTranslationNatRuleRequest,
cb?: (error: string, rep: DeleteNatGatewaySourceIpTranslationNatRuleResponse) => void
): Promise<DeleteNatGatewaySourceIpTranslationNatRuleResponse> {
return this.request("DeleteNatGatewaySourceIpTranslationNatRule", req, cb)
}
/**
* 本接口(DeleteNetworkInterface)用于删除弹性网卡。
* 弹性网卡上绑定了云服务器时,不能被删除。
* 删除指定弹性网卡,弹性网卡必须先和子机解绑才能删除。删除之后弹性网卡上所有内网IP都将被退还。
本接口是异步完成,如需查询异步任务执行结果,请使用本接口返回的`RequestId`轮询`DescribeVpcTaskResult`接口。
*/
async DeleteNetworkInterface(
req: DeleteNetworkInterfaceRequest,
cb?: (error: string, rep: DeleteNetworkInterfaceResponse) => void
): Promise<DeleteNetworkInterfaceResponse> {
return this.request("DeleteNetworkInterface", req, cb)
}
/**
* 该接口用于修改CDC的本地网关。
*/
async ModifyLocalGateway(
req: ModifyLocalGatewayRequest,
cb?: (error: string, rep: ModifyLocalGatewayResponse) => void
): Promise<ModifyLocalGatewayResponse> {
return this.request("ModifyLocalGateway", req, cb)
}
/**
* 本接口(DescribeVpnConnections)查询VPN通道列表。
*/
async DescribeVpnConnections(
req: DescribeVpnConnectionsRequest,
cb?: (error: string, rep: DescribeVpnConnectionsResponse) => void
): Promise<DescribeVpnConnectionsResponse> {
return this.request("DescribeVpnConnections", req, cb)
}
/**
* 该接口用于续费包月带宽计费模式的弹性公网IP
*/
async RenewAddresses(
req: RenewAddressesRequest,
cb?: (error: string, rep: RenewAddressesResponse) => void
): Promise<RenewAddressesResponse> {
return this.request("RenewAddresses", req, cb)
}
/**
* 本接口(DescribeFlowLog)用于查询流日志实例信息
*/
async DescribeFlowLog(
req: DescribeFlowLogRequest,
cb?: (error: string, rep: DescribeFlowLogResponse) => void
): Promise<DescribeFlowLogResponse> {
return this.request("DescribeFlowLog", req, cb)
}
/**
* 本接口(ModifyGatewayFlowQos)用于调整网关流控带宽。
*/
async ModifyGatewayFlowQos(
req: ModifyGatewayFlowQosRequest,
cb?: (error: string, rep: ModifyGatewayFlowQosResponse) => void
): Promise<ModifyGatewayFlowQosResponse> {
return this.request("ModifyGatewayFlowQos", req, cb)
}
/**
* 本接口(DeleteNatGateway)用于删除NAT网关。
删除 NAT 网关后,系统会自动删除路由表中包含此 NAT 网关的路由项,同时也会解绑弹性公网IP(EIP)。
*/
async DeleteNatGateway(
req: DeleteNatGatewayRequest,
cb?: (error: string, rep: DeleteNatGatewayResponse) => void
): Promise<DeleteNatGatewayResponse> {
return this.request("DeleteNatGateway", req, cb)
}
/**
* 本接口(DescribeRouteConflicts)用于查询自定义路由策略与云联网路由策略冲突列表
*/
async DescribeRouteConflicts(
req: DescribeRouteConflictsRequest,
cb?: (error: string, rep: DescribeRouteConflictsResponse) => void
): Promise<DescribeRouteConflictsResponse> {
return this.request("DescribeRouteConflicts", req, cb)
}
/**
* 本接口(DisableRoutes)用于禁用已启用的子网路由
*/
async DisableRoutes(
req: DisableRoutesRequest,
cb?: (error: string, rep: DisableRoutesResponse) => void
): Promise<DisableRoutesResponse> {
return this.request("DisableRoutes", req, cb)
}
/**
* 本接口(CreateDefaultSecurityGroup)用于创建(如果项目下未存在默认安全组,则创建;已存在则获取。)默认安全组(SecurityGroup)。
* 每个账户下每个地域的每个项目的<a href="https://cloud.tencent.com/document/product/213/12453">安全组数量限制</a>。
* 默认安全组会放通所有IPv4规则,在创建后通常您需要再调用CreateSecurityGroupPolicies将安全组的规则设置为需要的规则。
* 创建安全组同时可以绑定标签, 应答里的标签列表代表添加成功的标签。
*/
async CreateDefaultSecurityGroup(
req: CreateDefaultSecurityGroupRequest,
cb?: (error: string, rep: CreateDefaultSecurityGroupResponse) => void
): Promise<CreateDefaultSecurityGroupResponse> {
return this.request("CreateDefaultSecurityGroup", req, cb)
}
/**
* 1. 该接口用于在转换实例下添加IPV6转换规则。
2. 支持在同一个转换实例下批量添加转换规则,一个账户在一个地域最多50个。
3. 一个完整的转换规则包括vip6:vport6:protocol:vip:vport,其中vip6:vport6:protocol必须是唯一。
*/
async AddIp6Rules(
req: AddIp6RulesRequest,
cb?: (error: string, rep: AddIp6RulesResponse) => void
): Promise<AddIp6RulesResponse> {
return this.request("AddIp6Rules", req, cb)
}
/**
* 本接口(AssociateDhcpIpWithAddressIp)用于DhcpIp绑定弹性公网IP(EIP)。<br />
>?本接口为异步接口,可调用 [DescribeVpcTaskResult](https://cloud.tencent.com/document/api/215/59037) 接口查询任务执行结果,待任务执行成功后再进行其他操作。
>
*/
async AssociateDhcpIpWithAddressIp(
req: AssociateDhcpIpWithAddressIpRequest,
cb?: (error: string, rep: AssociateDhcpIpWithAddressIpResponse) => void
): Promise<AssociateDhcpIpWithAddressIpResponse> {
return this.request("AssociateDhcpIpWithAddressIp", req, cb)
}
/**
* 本接口(DeleteServiceTemplate)用于删除协议端口模板
*/
async DeleteServiceTemplate(
req: DeleteServiceTemplateRequest,
cb?: (error: string, rep: DeleteServiceTemplateResponse) => void
): Promise<DeleteServiceTemplateResponse> {
return this.request("DeleteServiceTemplate", req, cb)
}
/**
* 本接口(UnassignPrivateIpAddresses)用于弹性网卡退还内网 IP。
* 退还弹性网卡上的辅助内网IP,接口自动解关联弹性公网 IP。不能退还弹性网卡的主内网IP。
本接口是异步完成,如需查询异步任务执行结果,请使用本接口返回的`RequestId`轮询`DescribeVpcTaskResult`接口。
*/
async UnassignPrivateIpAddresses(
req: UnassignPrivateIpAddressesRequest,
cb?: (error: string, rep: UnassignPrivateIpAddressesResponse) => void
): Promise<UnassignPrivateIpAddressesResponse> {
return this.request("UnassignPrivateIpAddresses", req, cb)
}
/**
* 本接口(DeleteAddressTemplateGroup)用于删除IP地址模板集合
*/
async DeleteAddressTemplateGroup(
req: DeleteAddressTemplateGroupRequest,
cb?: (error: string, rep: DeleteAddressTemplateGroupResponse) => void
): Promise<DeleteAddressTemplateGroupResponse> {
return this.request("DeleteAddressTemplateGroup", req, cb)
}
/**
* 本接口(DescribeCcnRoutes)用于查询已加入云联网(CCN)的路由
*/
async DescribeCcnRoutes(
req: DescribeCcnRoutesRequest,
cb?: (error: string, rep: DescribeCcnRoutesResponse) => void
): Promise<DescribeCcnRoutesResponse> {
return this.request("DescribeCcnRoutes", req, cb)
}
/**
* 接口用于查询账户在当前地域的带宽包上限数量以及使用数量
*/
async DescribeBandwidthPackageQuota(
req?: DescribeBandwidthPackageQuotaRequest,
cb?: (error: string, rep: DescribeBandwidthPackageQuotaResponse) => void
): Promise<DescribeBandwidthPackageQuotaResponse> {
return this.request("DescribeBandwidthPackageQuota", req, cb)
}
/**
* 1. 该接口用于创建IPV6转换IPV4实例,支持批量
2. 同一个账户在一个地域最多允许创建10个转换实例
*/
async CreateIp6Translators(
req: CreateIp6TranslatorsRequest,
cb?: (error: string, rep: CreateIp6TranslatorsResponse) => void
): Promise<CreateIp6TranslatorsResponse> {
return this.request("CreateIp6Translators", req, cb)
}
/**
* 本接口(CreateAssistantCidr)用于批量创建辅助CIDR。(接口灰度中,如需使用请提工单。)
*/
async CreateAssistantCidr(
req: CreateAssistantCidrRequest,
cb?: (error: string, rep: CreateAssistantCidrResponse) => void
): Promise<CreateAssistantCidrResponse> {
return this.request("CreateAssistantCidr", req, cb)
}
/**
* 本接口(CreateDefaultVpc)用于创建默认私有网络(VPC)。
默认VPC适用于快速入门和启动公共实例,您可以像使用任何其他VPC一样使用默认VPC。如果您想创建标准VPC,即指定VPC名称、VPC网段、子网网段、子网可用区,请使用常规创建VPC接口(CreateVpc)
正常情况,本接口并不一定生产默认VPC,而是根据用户账号的网络属性(DescribeAccountAttributes)来决定的
* 支持基础网络、VPC,返回VpcId为0
* 只支持VPC,返回默认VPC信息
您也可以通过 Force 参数,强制返回默认VPC
*/
async CreateDefaultVpc(
req: CreateDefaultVpcRequest,
cb?: (error: string, rep: CreateDefaultVpcResponse) => void
): Promise<CreateDefaultVpcResponse> {
return this.request("CreateDefaultVpc", req, cb)
}
/**
* 本接口(AttachNetworkInterface)用于弹性网卡绑定云服务器。
* 一个云服务器可以绑定多个弹性网卡,但只能绑定一个主网卡。更多限制信息详见<a href="https://cloud.tencent.com/document/product/576/18527">弹性网卡使用限制</a>。
* 一个弹性网卡只能同时绑定一个云服务器。
* 只有运行中或者已关机状态的云服务器才能绑定弹性网卡,查看云服务器状态详见<a href="https://cloud.tencent.com/document/api/213/9452#InstanceStatus">腾讯云服务器信息</a>。
* 弹性网卡绑定的云服务器必须是私有网络的,而且云服务器所在可用区必须和弹性网卡子网的可用区相同。
本接口是异步完成,如需查询异步任务执行结果,请使用本接口返回的`RequestId`轮询`DescribeVpcTaskResult`接口。
*/
async AttachNetworkInterface(
req: AttachNetworkInterfaceRequest,
cb?: (error: string, rep: AttachNetworkInterfaceResponse) => void
): Promise<AttachNetworkInterfaceResponse> {
return this.request("AttachNetworkInterface", req, cb)
}
/**
* 本接口(ReplaceDirectConnectGatewayCcnRoutes)根据路由ID(RouteId)修改指定的路由(Route),支持批量修改。
*/
async ReplaceDirectConnectGatewayCcnRoutes(
req: ReplaceDirectConnectGatewayCcnRoutesRequest,
cb?: (error: string, rep: ReplaceDirectConnectGatewayCcnRoutesResponse) => void
): Promise<ReplaceDirectConnectGatewayCcnRoutesResponse> {
return this.request("ReplaceDirectConnectGatewayCcnRoutes", req, cb)
}
/**
* 本接口(GetCcnRegionBandwidthLimits)用于查询云联网相关地域带宽信息,其中预付费模式的云联网仅支持地域间限速,后付费模式的云联网支持地域间限速和地域出口限速。
*/
async GetCcnRegionBandwidthLimits(
req: GetCcnRegionBandwidthLimitsRequest,
cb?: (error: string, rep: GetCcnRegionBandwidthLimitsResponse) => void
): Promise<GetCcnRegionBandwidthLimitsResponse> {
return this.request("GetCcnRegionBandwidthLimits", req, cb)
}
/**
* 本接口(CreateNatGateway)用于创建NAT网关。
在对新建的NAT网关做其他操作前,需先确认此网关已被创建完成(DescribeNatGateway接口返回的实例State字段为AVAILABLE)。
*/
async CreateNatGateway(
req: CreateNatGatewayRequest,
cb?: (error: string, rep: CreateNatGatewayResponse) => void
): Promise<CreateNatGatewayResponse> {
return this.request("CreateNatGateway", req, cb)
}
/**
* 本接口(DeleteNetDetect)用于删除网络探测实例。
*/
async DeleteNetDetect(
req: DeleteNetDetectRequest,
cb?: (error: string, rep: DeleteNetDetectResponse) => void
): Promise<DeleteNetDetectResponse> {
return this.request("DeleteNetDetect", req, cb)
}
/**
* 本接口(ModifySecurityGroupAttribute)用于修改安全组(SecurityGroupPolicy)属性。
*/
async ModifySecurityGroupAttribute(
req: ModifySecurityGroupAttributeRequest,
cb?: (error: string, rep: ModifySecurityGroupAttributeResponse) => void
): Promise<ModifySecurityGroupAttributeResponse> {
return this.request("ModifySecurityGroupAttribute", req, cb)
}
/**
* 本接口(DeleteAddressTemplate)用于删除IP地址模板
*/
async DeleteAddressTemplate(
req: DeleteAddressTemplateRequest,
cb?: (error: string, rep: DeleteAddressTemplateResponse) => void
): Promise<DeleteAddressTemplateResponse> {
return this.request("DeleteAddressTemplate", req, cb)
}
/**
* 路由表列表页操作增加“发布到云联网”,用于发布路由到云联网。
*/
async NotifyRoutes(
req: NotifyRoutesRequest,
cb?: (error: string, rep: NotifyRoutesResponse) => void
): Promise<NotifyRoutesResponse> {
return this.request("NotifyRoutes", req, cb)
}
/**
* 删除终端节点服务。
*/
async DeleteVpcEndPointService(
req: DeleteVpcEndPointServiceRequest,
cb?: (error: string, rep: DeleteVpcEndPointServiceResponse) => void
): Promise<DeleteVpcEndPointServiceResponse> {
return this.request("DeleteVpcEndPointService", req, cb)
}
/**
* 本接口(ModifyAssistantCidr)用于批量修改辅助CIDR,支持新增和删除。(接口灰度中,如需使用请提工单。)
*/
async ModifyAssistantCidr(
req: ModifyAssistantCidrRequest,
cb?: (error: string, rep: ModifyAssistantCidrResponse) => void
): Promise<ModifyAssistantCidrResponse> {
return this.request("ModifyAssistantCidr", req, cb)
}
/**
* 删除终端节点。
*/
async DeleteVpcEndPoint(
req: DeleteVpcEndPointRequest,
cb?: (error: string, rep: DeleteVpcEndPointResponse) => void
): Promise<DeleteVpcEndPointResponse> {
return this.request("DeleteVpcEndPoint", req, cb)
}
/**
* 本接口(DeleteVpnGateway)用于删除VPN网关。目前只支持删除运行中的按量计费的IPSEC网关实例。
*/
async DeleteVpnGateway(
req: DeleteVpnGatewayRequest,
cb?: (error: string, rep: DeleteVpnGatewayResponse) => void
): Promise<DeleteVpnGatewayResponse> {
return this.request("DeleteVpnGateway", req, cb)
}
/**
* 本接口(CreateServiceTemplate)用于创建协议端口模板
*/
async CreateServiceTemplate(
req: CreateServiceTemplateRequest,
cb?: (error: string, rep: CreateServiceTemplateResponse) => void
): Promise<CreateServiceTemplateResponse> {
return this.request("CreateServiceTemplate", req, cb)
}
/**
* 本接口(DeleteRoutes)用于对某个路由表批量删除路由策略(Route)。
*/
async DeleteRoutes(
req: DeleteRoutesRequest,
cb?: (error: string, rep: DeleteRoutesResponse) => void
): Promise<DeleteRoutesResponse> {
return this.request("DeleteRoutes", req, cb)
}
/**
* 本接口(ModifyDirectConnectGatewayAttribute)用于修改专线网关属性
*/
async ModifyDirectConnectGatewayAttribute(
req: ModifyDirectConnectGatewayAttributeRequest,
cb?: (error: string, rep: ModifyDirectConnectGatewayAttributeResponse) => void
): Promise<ModifyDirectConnectGatewayAttributeResponse> {
return this.request("ModifyDirectConnectGatewayAttribute", req, cb)
}
/**
* 本接口(ModifyNetworkInterfaceAttribute)用于修改弹性网卡属性。
*/
async ModifyNetworkInterfaceAttribute(
req: ModifyNetworkInterfaceAttributeRequest,
cb?: (error: string, rep: ModifyNetworkInterfaceAttributeResponse) => void
): Promise<ModifyNetworkInterfaceAttributeResponse> {
return this.request("ModifyNetworkInterfaceAttribute", req, cb)
}
/**
* 本接口(ModifySubnetAttribute)用于修改子网属性。
*/
async ModifySubnetAttribute(
req: ModifySubnetAttributeRequest,
cb?: (error: string, rep: ModifySubnetAttributeResponse) => void
): Promise<ModifySubnetAttributeResponse> {
return this.request("ModifySubnetAttribute", req, cb)
}
/**
* 本接口(DescribeNetworkInterfaces)用于查询弹性网卡列表。
*/
async DescribeNetworkInterfaces(
req: DescribeNetworkInterfacesRequest,
cb?: (error: string, rep: DescribeNetworkInterfacesResponse) => void
): Promise<DescribeNetworkInterfacesResponse> {
return this.request("DescribeNetworkInterfaces", req, cb)
}
/**
* 本接口(InquiryPriceRenewVpnGateway)用于续费VPN网关询价。目前仅支持IPSEC类型网关的询价。
*/
async InquiryPriceRenewVpnGateway(
req: InquiryPriceRenewVpnGatewayRequest,
cb?: (error: string, rep: InquiryPriceRenewVpnGatewayResponse) => void
): Promise<InquiryPriceRenewVpnGatewayResponse> {
return this.request("InquiryPriceRenewVpnGateway", req, cb)
}
/**
* 本接口(DisableCcnRoutes)用于禁用已经启用的云联网(CCN)路由
*/
async DisableCcnRoutes(
req: DisableCcnRoutesRequest,
cb?: (error: string, rep: DisableCcnRoutesResponse) => void
): Promise<DisableCcnRoutesResponse> {
return this.request("DisableCcnRoutes", req, cb)
}
/**
* 查询终端节点服务的服务白名单列表。
*/
async DescribeVpcEndPointServiceWhiteList(
req: DescribeVpcEndPointServiceWhiteListRequest,
cb?: (error: string, rep: DescribeVpcEndPointServiceWhiteListResponse) => void
): Promise<DescribeVpcEndPointServiceWhiteListResponse> {
return this.request("DescribeVpcEndPointServiceWhiteList", req, cb)
}
/**
* 本接口(ResetVpnConnection)用于重置VPN通道。
*/
async ResetVpnConnection(
req: ResetVpnConnectionRequest,
cb?: (error: string, rep: ResetVpnConnectionResponse) => void
): Promise<ResetVpnConnectionResponse> {
return this.request("ResetVpnConnection", req, cb)
}
/**
* 本接口(CreateCustomerGateway)用于创建对端网关。
*/
async CreateCustomerGateway(
req: CreateCustomerGatewayRequest,
cb?: (error: string, rep: CreateCustomerGatewayResponse) => void
): Promise<CreateCustomerGatewayResponse> {
return this.request("CreateCustomerGateway", req, cb)
}
/**
* 本接口(DescribeCrossBorderCompliance)用于查询用户创建的合规化资质审批单。
服务商可以查询服务名下的任意 `APPID` 创建的审批单;非服务商,只能查询自己审批单。
*/
async DescribeCrossBorderCompliance(
req: DescribeCrossBorderComplianceRequest,
cb?: (error: string, rep: DescribeCrossBorderComplianceResponse) => void
): Promise<DescribeCrossBorderComplianceResponse> {
return this.request("DescribeCrossBorderCompliance", req, cb)
}
/**
* 本接口(CreateAddressTemplateGroup)用于创建IP地址模版集合
*/
async CreateAddressTemplateGroup(
req: CreateAddressTemplateGroupRequest,
cb?: (error: string, rep: CreateAddressTemplateGroupResponse) => void
): Promise<CreateAddressTemplateGroupResponse> {
return this.request("CreateAddressTemplateGroup", req, cb)
}
/**
* 本接口(CreateSecurityGroup)用于创建新的安全组(SecurityGroup)。
* 每个账户下每个地域的每个项目的<a href="https://cloud.tencent.com/document/product/213/12453">安全组数量限制</a>。
* 新建的安全组的入站和出站规则默认都是全部拒绝,在创建后通常您需要再调用CreateSecurityGroupPolicies将安全组的规则设置为需要的规则。
* 创建安全组同时可以绑定标签, 应答里的标签列表代表添加成功的标签。
*/
async CreateSecurityGroup(
req: CreateSecurityGroupRequest,
cb?: (error: string, rep: CreateSecurityGroupResponse) => void
): Promise<CreateSecurityGroupResponse> {
return this.request("CreateSecurityGroup", req, cb)
}
/**
* 本接口(AuditCrossBorderCompliance)用于服务商操作合规化资质审批。
* 服务商只能操作提交到本服务商的审批单,后台会校验身份。即只授权给服务商的`APPID` 调用本接口。
* `APPROVED` 状态的审批单,可以再次操作为 `DENY`;`DENY` 状态的审批单,也可以再次操作为 `APPROVED`。
*/
async AuditCrossBorderCompliance(
req: AuditCrossBorderComplianceRequest,
cb?: (error: string, rep: AuditCrossBorderComplianceResponse) => void
): Promise<AuditCrossBorderComplianceResponse> {
return this.request("AuditCrossBorderCompliance", req, cb)
}
/**
* 本接口(AssociateNetworkAclSubnets)用于网络ACL关联vpc下的子网。
*/
async AssociateNetworkAclSubnets(
req: AssociateNetworkAclSubnetsRequest,
cb?: (error: string, rep: AssociateNetworkAclSubnetsResponse) => void
): Promise<AssociateNetworkAclSubnetsResponse> {
return this.request("AssociateNetworkAclSubnets", req, cb)
}
/**
* 查询账户在指定地域IPV6转换实例和规则的配额
*/
async DescribeIp6TranslatorQuota(
req: DescribeIp6TranslatorQuotaRequest,
cb?: (error: string, rep: DescribeIp6TranslatorQuotaResponse) => void
): Promise<DescribeIp6TranslatorQuotaResponse> {
return this.request("DescribeIp6TranslatorQuota", req, cb)
}
/**
* 本接口(DescribeVpnGateways)用于查询VPN网关列表。
*/
async DescribeVpnGateways(
req: DescribeVpnGatewaysRequest,
cb?: (error: string, rep: DescribeVpnGatewaysResponse) => void
): Promise<DescribeVpnGatewaysResponse> {
return this.request("DescribeVpnGateways", req, cb)
}
/**
* 本接口(DownloadCustomerGatewayConfiguration)用于下载VPN通道配置。
*/
async DownloadCustomerGatewayConfiguration(
req: DownloadCustomerGatewayConfigurationRequest,
cb?: (error: string, rep: DownloadCustomerGatewayConfigurationResponse) => void
): Promise<DownloadCustomerGatewayConfigurationResponse> {
return this.request("DownloadCustomerGatewayConfiguration", req, cb)
}
/**
* 本接口(DescribeVpcInstances)用于查询VPC下的云主机实例列表。
*/
async DescribeVpcInstances(
req: DescribeVpcInstancesRequest,
cb?: (error: string, rep: DescribeVpcInstancesResponse) => void
): Promise<DescribeVpcInstancesResponse> {
return this.request("DescribeVpcInstances", req, cb)
}
/**
* 删除路由表
*/
async DeleteRouteTable(
req: DeleteRouteTableRequest,
cb?: (error: string, rep: DeleteRouteTableResponse) => void
): Promise<DeleteRouteTableResponse> {
return this.request("DeleteRouteTable", req, cb)
}
/**
* 本接口(DescribeSecurityGroupLimits)用于查询用户安全组配额。
*/
async DescribeSecurityGroupLimits(
req?: DescribeSecurityGroupLimitsRequest,
cb?: (error: string, rep: DescribeSecurityGroupLimitsResponse) => void
): Promise<DescribeSecurityGroupLimitsResponse> {
return this.request("DescribeSecurityGroupLimits", req, cb)
}
/**
* 本接口 (DisassociateAddress) 用于解绑[弹性公网IP](https://cloud.tencent.com/document/product/213/1941)(简称 EIP)。
* 支持CVM实例,弹性网卡上的EIP解绑
* 不支持NAT上的EIP解绑。NAT上的EIP解绑请参考[DisassociateNatGatewayAddress](https://cloud.tencent.com/document/api/215/36716)
* 只有状态为 BIND 和 BIND_ENI 的 EIP 才能进行解绑定操作。
* EIP 如果被封堵,则不能进行解绑定操作。
*/
async DisassociateAddress(
req: DisassociateAddressRequest,
cb?: (error: string, rep: DisassociateAddressResponse) => void
): Promise<DisassociateAddressResponse> {
return this.request("DisassociateAddress", req, cb)
}
/**
* 路由表列表页操作增加“从云联网撤销”,用于撤销已发布到云联网的路由。
*/
async WithdrawNotifyRoutes(
req: WithdrawNotifyRoutesRequest,
cb?: (error: string, rep: WithdrawNotifyRoutesResponse) => void
): Promise<WithdrawNotifyRoutesResponse> {
return this.request("WithdrawNotifyRoutes", req, cb)
}
/**
* 查询专线绑定NAT的路由
*/
async DescribeNatGatewayDirectConnectGatewayRoute(
req: DescribeNatGatewayDirectConnectGatewayRouteRequest,
cb?: (error: string, rep: DescribeNatGatewayDirectConnectGatewayRouteResponse) => void
): Promise<DescribeNatGatewayDirectConnectGatewayRouteResponse> {
return this.request("DescribeNatGatewayDirectConnectGatewayRoute", req, cb)
}
/**
* 本接口(ModifyIpv6AddressesAttribute)用于修改弹性网卡内网IPv6地址属性。
*/
async ModifyIpv6AddressesAttribute(
req: ModifyIpv6AddressesAttributeRequest,
cb?: (error: string, rep: ModifyIpv6AddressesAttributeResponse) => void
): Promise<ModifyIpv6AddressesAttributeResponse> {
return this.request("ModifyIpv6AddressesAttribute", req, cb)
}
/**
* 本接口(DescribeDirectConnectGateways)用于查询专线网关。
*/
async DescribeDirectConnectGateways(
req: DescribeDirectConnectGatewaysRequest,
cb?: (error: string, rep: DescribeDirectConnectGatewaysResponse) => void
): Promise<DescribeDirectConnectGatewaysResponse> {
return this.request("DescribeDirectConnectGateways", req, cb)
}
/**
* 该接口用于修改IP6转换实例属性,当前仅支持修改实例名称。
*/
async ModifyIp6Translator(
req: ModifyIp6TranslatorRequest,
cb?: (error: string, rep: ModifyIp6TranslatorResponse) => void
): Promise<ModifyIp6TranslatorResponse> {
return this.request("ModifyIp6Translator", req, cb)
}
/**
* 本接口(DescribeAccountAttributes)用于查询用户账号私有属性。
*/
async DescribeAccountAttributes(
req?: DescribeAccountAttributesRequest,
cb?: (error: string, rep: DescribeAccountAttributesResponse) => void
): Promise<DescribeAccountAttributesResponse> {
return this.request("DescribeAccountAttributes", req, cb)
}
/**
* 本接口(AssignIpv6Addresses)用于弹性网卡申请`IPv6`地址。<br />
本接口是异步完成,如需查询异步任务执行结果,请使用本接口返回的`RequestId`轮询`DescribeVpcTaskResult`接口。
* 一个弹性网卡支持绑定的IP地址是有限制的,更多资源限制信息详见<a href="/document/product/576/18527">弹性网卡使用限制</a>。
* 可以指定`IPv6`地址申请,地址类型不能为主`IP`,`IPv6`地址暂时只支持作为辅助`IP`。
* 地址必须要在弹性网卡所在子网内,而且不能被占用。
* 在弹性网卡上申请一个到多个辅助`IPv6`地址,接口会在弹性网卡所在子网段内返回指定数量的辅助`IPv6`地址。
*/
async AssignIpv6Addresses(
req: AssignIpv6AddressesRequest,
cb?: (error: string, rep: AssignIpv6AddressesResponse) => void
): Promise<AssignIpv6AddressesResponse> {
return this.request("AssignIpv6Addresses", req, cb)
}
/**
* 本接口(DescribePriceCreateDirectConnectGateway)用于创建专线网关询价。
*/
async InquirePriceCreateDirectConnectGateway(
req?: InquirePriceCreateDirectConnectGatewayRequest,
cb?: (error: string, rep: InquirePriceCreateDirectConnectGatewayResponse) => void
): Promise<InquirePriceCreateDirectConnectGatewayResponse> {
return this.request("InquirePriceCreateDirectConnectGateway", req, cb)
}
/**
* 本接口(DescribeIpGeolocationInfos)用于查询IP地址信息,包括地理位置信息和网络信息。
本接口目前处于内测中,如需使用,请提交 [工单申请](https://console.cloud.tencent.com/workorder/category?level1_id=6&level2_id=660&source=0&data_title=%E5%BC%B9%E6%80%A7%E5%85%AC%E7%BD%91%20EIP&level3_id=662&queue=96&scene_code=16400&step=2)。
*/
async DescribeIpGeolocationInfos(
req: DescribeIpGeolocationInfosRequest,
cb?: (error: string, rep: DescribeIpGeolocationInfosResponse) => void
): Promise<DescribeIpGeolocationInfosResponse> {
return this.request("DescribeIpGeolocationInfos", req, cb)
}
/**
* 本接口(DescribeServiceTemplates)用于查询协议端口模板
*/
async DescribeServiceTemplates(
req: DescribeServiceTemplatesRequest,
cb?: (error: string, rep: DescribeServiceTemplatesResponse) => void
): Promise<DescribeServiceTemplatesResponse> {
return this.request("DescribeServiceTemplates", req, cb)
}
/**
* 本接口(UnassignIpv6CidrBlock)用于释放IPv6网段。<br />
网段如果还有IP占用且未回收,则网段无法释放。
*/
async UnassignIpv6CidrBlock(
req: UnassignIpv6CidrBlockRequest,
cb?: (error: string, rep: UnassignIpv6CidrBlockResponse) => void
): Promise<UnassignIpv6CidrBlockResponse> {
return this.request("UnassignIpv6CidrBlock", req, cb)
}
/**
* 本接口 (DescribeBandwidthPackageBillUsage) 用于查询后付费共享带宽包当前的计费用量.
*/
async DescribeBandwidthPackageBillUsage(
req: DescribeBandwidthPackageBillUsageRequest,
cb?: (error: string, rep: DescribeBandwidthPackageBillUsageResponse) => void
): Promise<DescribeBandwidthPackageBillUsageResponse> {
return this.request("DescribeBandwidthPackageBillUsage", req, cb)
}
/**
* 本接口(ModifyNatGatewayDestinationIpPortTranslationNatRule)用于修改NAT网关端口转发规则。
*/
async ModifyNatGatewayDestinationIpPortTranslationNatRule(
req: ModifyNatGatewayDestinationIpPortTranslationNatRuleRequest,
cb?: (error: string, rep: ModifyNatGatewayDestinationIpPortTranslationNatRuleResponse) => void
): Promise<ModifyNatGatewayDestinationIpPortTranslationNatRuleResponse> {
return this.request("ModifyNatGatewayDestinationIpPortTranslationNatRule", req, cb)
}
/**
* 获取私有网络配额,部分私有网络的配额有地域属性。
LimitTypes取值范围:
* appid-max-vpcs (每个开发商每个地域可创建的VPC数)
* vpc-max-subnets(每个VPC可创建的子网数)
* vpc-max-route-tables(每个VPC可创建的路由表数)
* route-table-max-policies(每个路由表可添加的策略数)
* vpc-max-vpn-gateways(每个VPC可创建的VPN网关数)
* appid-max-custom-gateways(每个开发商可创建的对端网关数)
* appid-max-vpn-connections(每个开发商可创建的VPN通道数)
* custom-gateway-max-vpn-connections(每个对端网关可创建的VPN通道数)
* vpn-gateway-max-custom-gateways(每个VPNGW可以创建的通道数)
* vpc-max-network-acls(每个VPC可创建的网络ACL数)
* network-acl-max-inbound-policies(每个网络ACL可添加的入站规则数)
* network-acl-max-outbound-policies(每个网络ACL可添加的出站规则数)
* vpc-max-vpcpeers(每个VPC可创建的对等连接数)
* vpc-max-available-vpcpeers(每个VPC可创建的有效对等连接数)
* vpc-max-basic-network-interconnections(每个VPC可创建的基础网络云主机与VPC互通数)
* direct-connection-max-snats(每个专线网关可创建的SNAT数)
* direct-connection-max-dnats(每个专线网关可创建的DNAT数)
* direct-connection-max-snapts(每个专线网关可创建的SNAPT数)
* direct-connection-max-dnapts(每个专线网关可创建的DNAPT数)
* vpc-max-nat-gateways(每个VPC可创建的NAT网关数)
* nat-gateway-max-eips(每个NAT可以购买的外网IP数量)
* vpc-max-enis(每个VPC可创建弹性网卡数)
* vpc-max-havips(每个VPC可创建HAVIP数)
* eni-max-private-ips(每个ENI可以绑定的内网IP数(ENI未绑定子机))
* nat-gateway-max-dnapts(每个NAT网关可创建的DNAPT数)
* vpc-max-ipv6s(每个VPC可分配的IPv6地址数)
* eni-max-ipv6s(每个ENI可分配的IPv6地址数)
* vpc-max-assistant_cidrs(每个VPC可分配的辅助CIDR数)
*/
async DescribeVpcLimits(
req: DescribeVpcLimitsRequest,
cb?: (error: string, rep: DescribeVpcLimitsResponse) => void
): Promise<DescribeVpcLimitsResponse> {
return this.request("DescribeVpcLimits", req, cb)
}
/**
* 本接口(HaVipAssociateAddressIp)用于高可用虚拟IP(HAVIP)绑定弹性公网IP(EIP)。<br />
本接口是异步完成,如需查询异步任务执行结果,请使用本接口返回的`RequestId`轮询`DescribeVpcTaskResult`接口。
*/
async HaVipAssociateAddressIp(
req: HaVipAssociateAddressIpRequest,
cb?: (error: string, rep: HaVipAssociateAddressIpResponse) => void
): Promise<HaVipAssociateAddressIpResponse> {
return this.request("HaVipAssociateAddressIp", req, cb)
}
/**
* 本接口(CreateNatGatewaySourceIpTranslationNatRule)用于创建NAT网关SNAT规则
*/
async CreateNatGatewaySourceIpTranslationNatRule(
req: CreateNatGatewaySourceIpTranslationNatRuleRequest,
cb?: (error: string, rep: CreateNatGatewaySourceIpTranslationNatRuleResponse) => void
): Promise<CreateNatGatewaySourceIpTranslationNatRuleResponse> {
return this.request("CreateNatGatewaySourceIpTranslationNatRule", req, cb)
}
/**
* 增加模版对象中的IP地址、协议端口、IP地址组、协议端口组。当前仅支持北京、泰国、北美地域请求。
*/
async AddTemplateMember(
req: AddTemplateMemberRequest,
cb?: (error: string, rep: AddTemplateMemberResponse) => void
): Promise<AddTemplateMemberResponse> {
return this.request("AddTemplateMember", req, cb)
}
/**
* 1. 该接口用于删除IPV6转换规则
2. 支持批量删除同一个转换实例下的多个转换规则
*/
async RemoveIp6Rules(
req: RemoveIp6RulesRequest,
cb?: (error: string, rep: RemoveIp6RulesResponse) => void
): Promise<RemoveIp6RulesResponse> {
return this.request("RemoveIp6Rules", req, cb)
}
/**
* 本接口(CheckDefaultSubnet)用于预判是否可建默认子网。
*/
async CheckDefaultSubnet(
req: CheckDefaultSubnetRequest,
cb?: (error: string, rep: CheckDefaultSubnetResponse) => void
): Promise<CheckDefaultSubnetResponse> {
return this.request("CheckDefaultSubnet", req, cb)
}
/**
* 本接口(DescribeHaVips)用于查询高可用虚拟IP(HAVIP)列表。
*/
async DescribeHaVips(
req: DescribeHaVipsRequest,
cb?: (error: string, rep: DescribeHaVipsResponse) => void
): Promise<DescribeHaVipsResponse> {
return this.request("DescribeHaVips", req, cb)
}
/**
* 该接口用于创建用于CDC的本地网关。
*/
async CreateLocalGateway(
req: CreateLocalGatewayRequest,
cb?: (error: string, rep: CreateLocalGatewayResponse) => void
): Promise<CreateLocalGatewayResponse> {
return this.request("CreateLocalGateway", req, cb)
}
/**
* 本接口(AssociateNetworkInterfaceSecurityGroups)用于弹性网卡绑定安全组(SecurityGroup)。
*/
async AssociateNetworkInterfaceSecurityGroups(
req: AssociateNetworkInterfaceSecurityGroupsRequest,
cb?: (error: string, rep: AssociateNetworkInterfaceSecurityGroupsResponse) => void
): Promise<AssociateNetworkInterfaceSecurityGroupsResponse> {
return this.request("AssociateNetworkInterfaceSecurityGroups", req, cb)
}
/**
* 本接口(DeleteHaVip)用于删除高可用虚拟IP(HAVIP)。<br />
本接口是异步完成,如需查询异步任务执行结果,请使用本接口返回的`RequestId`轮询`DescribeVpcTaskResult`接口。
*/
async DeleteHaVip(
req: DeleteHaVipRequest,
cb?: (error: string, rep: DeleteHaVipResponse) => void
): Promise<DeleteHaVipResponse> {
return this.request("DeleteHaVip", req, cb)
}
/**
* 本接口用于查询网络产品的配额信息
*/
async DescribeProductQuota(
req: DescribeProductQuotaRequest,
cb?: (error: string, rep: DescribeProductQuotaResponse) => void
): Promise<DescribeProductQuotaResponse> {
return this.request("DescribeProductQuota", req, cb)
}
/**
* 本接口(InquiryPriceCreateVpnGateway)用于创建VPN网关询价。
*/
async InquiryPriceCreateVpnGateway(
req: InquiryPriceCreateVpnGatewayRequest,
cb?: (error: string, rep: InquiryPriceCreateVpnGatewayResponse) => void
): Promise<InquiryPriceCreateVpnGatewayResponse> {
return this.request("InquiryPriceCreateVpnGateway", req, cb)
}
/**
* 接口用于修改带宽包属性,包括带宽包名字等
*/
async ModifyBandwidthPackageAttribute(
req: ModifyBandwidthPackageAttributeRequest,
cb?: (error: string, rep: ModifyBandwidthPackageAttributeResponse) => void
): Promise<ModifyBandwidthPackageAttributeResponse> {
return this.request("ModifyBandwidthPackageAttribute", req, cb)
}
/**
* 本接口(CreateAddressTemplate)用于创建IP地址模版
*/
async CreateAddressTemplate(
req: CreateAddressTemplateRequest,
cb?: (error: string, rep: CreateAddressTemplateResponse) => void
): Promise<CreateAddressTemplateResponse> {
return this.request("CreateAddressTemplate", req, cb)
}
/**
* 本接口(ModifyVpnGatewayAttribute)用于修改VPN网关属性。
*/
async ModifyVpnGatewayAttribute(
req: ModifyVpnGatewayAttributeRequest,
cb?: (error: string, rep: ModifyVpnGatewayAttributeResponse) => void
): Promise<ModifyVpnGatewayAttributeResponse> {
return this.request("ModifyVpnGatewayAttribute", req, cb)
}
/**
* 本接口(ResetVpnGatewayInternetMaxBandwidth)调整VPN网关带宽上限。目前支持升级配置,如果是包年包月VPN网关需要在有效期内。
*/
async ResetVpnGatewayInternetMaxBandwidth(
req: ResetVpnGatewayInternetMaxBandwidthRequest,
cb?: (error: string, rep: ResetVpnGatewayInternetMaxBandwidthResponse) => void
): Promise<ResetVpnGatewayInternetMaxBandwidthResponse> {
return this.request("ResetVpnGatewayInternetMaxBandwidth", req, cb)
}
/**
* 本接口(DeleteVpc)用于删除私有网络。
* 删除前请确保 VPC 内已经没有相关资源,例如云服务器、云数据库、NoSQL、VPN网关、专线网关、负载均衡、对等连接、与之互通的基础网络设备等。
* 删除私有网络是不可逆的操作,请谨慎处理。
*/
async DeleteVpc(
req: DeleteVpcRequest,
cb?: (error: string, rep: DeleteVpcResponse) => void
): Promise<DeleteVpcResponse> {
return this.request("DeleteVpc", req, cb)
}
/**
* 本接口(DescribeSubnets)用于查询子网列表。
*/
async DescribeSubnets(
req: DescribeSubnetsRequest,
cb?: (error: string, rep: DescribeSubnetsResponse) => void
): Promise<DescribeSubnetsResponse> {
return this.request("DescribeSubnets", req, cb)
}
/**
* 本接口 (DescribeAddressQuota) 用于查询您账户的[弹性公网IP](https://cloud.tencent.com/document/product/213/1941)(简称 EIP)在当前地域的配额信息。配额详情可参见 [EIP 产品简介](https://cloud.tencent.com/document/product/213/5733)。
*/
async DescribeAddressQuota(
req?: DescribeAddressQuotaRequest,
cb?: (error: string, rep: DescribeAddressQuotaResponse) => void
): Promise<DescribeAddressQuotaResponse> {
return this.request("DescribeAddressQuota", req, cb)
}
/**
* 本接口(CreateCcn)用于创建云联网(CCN)。<br />
* 创建云联网同时可以绑定标签, 应答里的标签列表代表添加成功的标签。
每个账号能创建的云联网实例个数是有限的,详请参考产品文档。如果需要扩充请联系在线客服。
*/
async CreateCcn(
req: CreateCcnRequest,
cb?: (error: string, rep: CreateCcnResponse) => void
): Promise<CreateCcnResponse> {
return this.request("CreateCcn", req, cb)
}
/**
* 本接口(ModifyCustomerGatewayAttribute)用于修改对端网关信息。
*/
async ModifyCustomerGatewayAttribute(
req: ModifyCustomerGatewayAttributeRequest,
cb?: (error: string, rep: ModifyCustomerGatewayAttributeResponse) => void
): Promise<ModifyCustomerGatewayAttributeResponse> {
return this.request("ModifyCustomerGatewayAttribute", req, cb)
}
/**
* 本接口(DescribeNetworkAcls)用于查询网络ACL列表。
*/
async DescribeNetworkAcls(
req: DescribeNetworkAclsRequest,
cb?: (error: string, rep: DescribeNetworkAclsResponse) => void
): Promise<DescribeNetworkAclsResponse> {
return this.request("DescribeNetworkAcls", req, cb)
}
/**
* 本接口(ModifyVpnConnectionAttribute)用于修改VPN通道。
*/
async ModifyVpnConnectionAttribute(
req: ModifyVpnConnectionAttributeRequest,
cb?: (error: string, rep: ModifyVpnConnectionAttributeResponse) => void
): Promise<ModifyVpnConnectionAttributeResponse> {
return this.request("ModifyVpnConnectionAttribute", req, cb)
}
/**
* 本接口(DescribeSecurityGroups)用于查询安全组。
*/
async DescribeSecurityGroups(
req: DescribeSecurityGroupsRequest,
cb?: (error: string, rep: DescribeSecurityGroupsResponse) => void
): Promise<DescribeSecurityGroupsResponse> {
return this.request("DescribeSecurityGroups", req, cb)
}
/**
* 本接口(CreateVpnGateway)用于创建VPN网关。
*/
async CreateVpnGateway(
req: CreateVpnGatewayRequest,
cb?: (error: string, rep: CreateVpnGatewayResponse) => void
): Promise<CreateVpnGatewayResponse> {
return this.request("CreateVpnGateway", req, cb)
}
/**
* 本接口(DescribeSecurityGroupPolicies)用于查询安全组规则。
*/
async DescribeSecurityGroupPolicies(
req: DescribeSecurityGroupPoliciesRequest,
cb?: (error: string, rep: DescribeSecurityGroupPoliciesResponse) => void
): Promise<DescribeSecurityGroupPoliciesResponse> {
return this.request("DescribeSecurityGroupPolicies", req, cb)
}
/**
* 本接口(DescribeAssistantCidr)用于查询辅助CIDR列表。(接口灰度中,如需使用请提工单。)
*/
async DescribeAssistantCidr(
req: DescribeAssistantCidrRequest,
cb?: (error: string, rep: DescribeAssistantCidrResponse) => void
): Promise<DescribeAssistantCidrResponse> {
return this.request("DescribeAssistantCidr", req, cb)
}
/**
* 本接口(CreateDirectConnectGateway)用于创建专线网关。
*/
async CreateDirectConnectGateway(
req: CreateDirectConnectGatewayRequest,
cb?: (error: string, rep: CreateDirectConnectGatewayResponse) => void
): Promise<CreateDirectConnectGatewayResponse> {
return this.request("CreateDirectConnectGateway", req, cb)
}
/**
* 本接口(DescribeClassicLinkInstances)用于查询私有网络和基础网络设备互通列表。
*/
async DescribeClassicLinkInstances(
req: DescribeClassicLinkInstancesRequest,
cb?: (error: string, rep: DescribeClassicLinkInstancesResponse) => void
): Promise<DescribeClassicLinkInstancesResponse> {
return this.request("DescribeClassicLinkInstances", req, cb)
}
/**
* 本接口 (TransformAddress) 用于将实例的普通公网 IP 转换为[弹性公网IP](https://cloud.tencent.com/document/product/213/1941)(简称 EIP)。
* 平台对用户每地域每日解绑 EIP 重新分配普通公网 IP 次数有所限制(可参见 [EIP 产品简介](/document/product/213/1941))。上述配额可通过 [DescribeAddressQuota](https://cloud.tencent.com/document/api/213/1378) 接口获取。
*/
async TransformAddress(
req: TransformAddressRequest,
cb?: (error: string, rep: TransformAddressResponse) => void
): Promise<TransformAddressResponse> {
return this.request("TransformAddress", req, cb)
}
/**
* 本接口(EnableRoutes)用于启用已禁用的子网路由。<br />
本接口会校验启用后,是否与已有路由冲突,如果冲突,则无法启用,失败处理。路由冲突时,需要先禁用与之冲突的路由,才能启用该路由。
*/
async EnableRoutes(
req: EnableRoutesRequest,
cb?: (error: string, rep: EnableRoutesResponse) => void
): Promise<EnableRoutesResponse> {
return this.request("EnableRoutes", req, cb)
}
/**
* 本接口(DisassociateDhcpIpWithAddressIp)用于将DhcpIp已绑定的弹性公网IP(EIP)解除绑定。<br />
>?本接口为异步接口,可调用 [DescribeVpcTaskResult](https://cloud.tencent.com/document/api/215/59037) 接口查询任务执行结果,待任务执行成功后再进行其他操作。
>
*/
async DisassociateDhcpIpWithAddressIp(
req: DisassociateDhcpIpWithAddressIpRequest,
cb?: (error: string, rep: DisassociateDhcpIpWithAddressIpResponse) => void
): Promise<DisassociateDhcpIpWithAddressIpResponse> {
return this.request("DisassociateDhcpIpWithAddressIp", req, cb)
}
/**
* 本接口(CreateHaVip)用于创建高可用虚拟IP(HAVIP)
*/
async CreateHaVip(
req: CreateHaVipRequest,
cb?: (error: string, rep: CreateHaVipResponse) => void
): Promise<CreateHaVipResponse> {
return this.request("CreateHaVip", req, cb)
}
/**
* 本接口(ModifyServiceTemplateAttribute)用于修改协议端口模板
*/
async ModifyServiceTemplateAttribute(
req: ModifyServiceTemplateAttributeRequest,
cb?: (error: string, rep: ModifyServiceTemplateAttributeResponse) => void
): Promise<ModifyServiceTemplateAttributeResponse> {
return this.request("ModifyServiceTemplateAttribute", req, cb)
}
/**
* 本接口(DeleteSecurityGroup)用于删除安全组(SecurityGroup)。
* 只有当前账号下的安全组允许被删除。
* 安全组实例ID如果在其他安全组的规则中被引用,则无法直接删除。这种情况下,需要先进行规则修改,再删除安全组。
* 删除的安全组无法再找回,请谨慎调用。
*/
async DeleteSecurityGroup(
req: DeleteSecurityGroupRequest,
cb?: (error: string, rep: DeleteSecurityGroupResponse) => void
): Promise<DeleteSecurityGroupResponse> {
return this.request("DeleteSecurityGroup", req, cb)
}
/**
* 本接口(DisassociateNetworkAclSubnets)用于网络ACL解关联vpc下的子网。
*/
async DisassociateNetworkAclSubnets(
req: DisassociateNetworkAclSubnetsRequest,
cb?: (error: string, rep: DisassociateNetworkAclSubnetsResponse) => void
): Promise<DisassociateNetworkAclSubnetsResponse> {
return this.request("DisassociateNetworkAclSubnets", req, cb)
}
/**
* 本接口(DescribeNatGatewaySourceIpTranslationNatRules)用于查询NAT网关SNAT转发规则对象数组。
*/
async DescribeNatGatewaySourceIpTranslationNatRules(
req: DescribeNatGatewaySourceIpTranslationNatRulesRequest,
cb?: (error: string, rep: DescribeNatGatewaySourceIpTranslationNatRulesResponse) => void
): Promise<DescribeNatGatewaySourceIpTranslationNatRulesResponse> {
return this.request("DescribeNatGatewaySourceIpTranslationNatRules", req, cb)
}
/**
* 本接口(EnableCcnRoutes)用于启用已经加入云联网(CCN)的路由。<br />
本接口会校验启用后,是否与已有路由冲突,如果冲突,则无法启用,失败处理。路由冲突时,需要先禁用与之冲突的路由,才能启用该路由。
*/
async EnableCcnRoutes(
req: EnableCcnRoutesRequest,
cb?: (error: string, rep: EnableCcnRoutesResponse) => void
): Promise<EnableCcnRoutesResponse> {
return this.request("EnableCcnRoutes", req, cb)
}
/**
* 本接口(ModifyRouteTableAttribute)用于修改路由表(RouteTable)属性。
*/
async ModifyRouteTableAttribute(
req: ModifyRouteTableAttributeRequest,
cb?: (error: string, rep: ModifyRouteTableAttributeResponse) => void
): Promise<ModifyRouteTableAttributeResponse> {
return this.request("ModifyRouteTableAttribute", req, cb)
}
/**
* 本接口(ReplaceRoutes)根据路由策略ID(RouteId)修改指定的路由策略(Route),支持批量修改。
*/
async ReplaceRoutes(
req: ReplaceRoutesRequest,
cb?: (error: string, rep: ReplaceRoutesResponse) => void
): Promise<ReplaceRoutesResponse> {
return this.request("ReplaceRoutes", req, cb)
}
/**
* 本接口(ModifyNetDetect)用于修改网络探测参数。
*/
async ModifyNetDetect(
req: ModifyNetDetectRequest,
cb?: (error: string, rep: ModifyNetDetectResponse) => void
): Promise<ModifyNetDetectResponse> {
return this.request("ModifyNetDetect", req, cb)
}
/**
* 本接口(DisableGatewayFlowMonitor)用于关闭网关流量监控。
*/
async DisableGatewayFlowMonitor(
req: DisableGatewayFlowMonitorRequest,
cb?: (error: string, rep: DisableGatewayFlowMonitorResponse) => void
): Promise<DisableGatewayFlowMonitorResponse> {
return this.request("DisableGatewayFlowMonitor", req, cb)
}
/**
* 本接口(DeleteNatGatewayDestinationIpPortTranslationNatRule)用于删除NAT网关端口转发规则。
*/
async DeleteNatGatewayDestinationIpPortTranslationNatRule(
req: DeleteNatGatewayDestinationIpPortTranslationNatRuleRequest,
cb?: (error: string, rep: DeleteNatGatewayDestinationIpPortTranslationNatRuleResponse) => void
): Promise<DeleteNatGatewayDestinationIpPortTranslationNatRuleResponse> {
return this.request("DeleteNatGatewayDestinationIpPortTranslationNatRule", req, cb)
}
/**
* 本接口(CreateRoutes)用于创建路由策略。
* 向指定路由表批量新增路由策略。
*/
async CreateRoutes(
req: CreateRoutesRequest,
cb?: (error: string, rep: CreateRoutesResponse) => void
): Promise<CreateRoutesResponse> {
return this.request("CreateRoutes", req, cb)
}
/**
* 本接口(CreateNetDetect)用于创建网络探测。
*/
async CreateNetDetect(
req: CreateNetDetectRequest,
cb?: (error: string, rep: CreateNetDetectResponse) => void
): Promise<CreateNetDetectResponse> {
return this.request("CreateNetDetect", req, cb)
}
/**
* 本接口(ModifyHaVipAttribute)用于修改高可用虚拟IP(HAVIP)属性
*/
async ModifyHaVipAttribute(
req: ModifyHaVipAttributeRequest,
cb?: (error: string, rep: ModifyHaVipAttributeResponse) => void
): Promise<ModifyHaVipAttributeResponse> {
return this.request("ModifyHaVipAttribute", req, cb)
}
/**
* 本接口 (ReleaseAddresses) 用于释放一个或多个[弹性公网IP](https://cloud.tencent.com/document/product/213/1941)(简称 EIP)。
* 该操作不可逆,释放后 EIP 关联的 IP 地址将不再属于您的名下。
* 只有状态为 UNBIND 的 EIP 才能进行释放操作。
*/
async ReleaseAddresses(
req: ReleaseAddressesRequest,
cb?: (error: string, rep: ReleaseAddressesResponse) => void
): Promise<ReleaseAddressesResponse> {
return this.request("ReleaseAddresses", req, cb)
}
/**
* 本接口(ModifyVpcEndPointServiceAttribute)用于修改终端节点服务属性。
*/
async ModifyVpcEndPointServiceAttribute(
req: ModifyVpcEndPointServiceAttributeRequest,
cb?: (error: string, rep: ModifyVpcEndPointServiceAttributeResponse) => void
): Promise<ModifyVpcEndPointServiceAttributeResponse> {
return this.request("ModifyVpcEndPointServiceAttribute", req, cb)
}
/**
* 接口用于查询带宽包详细信息,包括带宽包唯一标识ID,类型,计费模式,名称,资源信息等
*/
async DescribeBandwidthPackages(
req: DescribeBandwidthPackagesRequest,
cb?: (error: string, rep: DescribeBandwidthPackagesResponse) => void
): Promise<DescribeBandwidthPackagesResponse> {
return this.request("DescribeBandwidthPackages", req, cb)
}
/**
* 本接口(CreateServiceTemplateGroup)用于创建协议端口模板集合
*/
async CreateServiceTemplateGroup(
req: CreateServiceTemplateGroupRequest,
cb?: (error: string, rep: CreateServiceTemplateGroupResponse) => void
): Promise<CreateServiceTemplateGroupResponse> {
return this.request("CreateServiceTemplateGroup", req, cb)
}
/**
* 该接口用于给弹性公网IPv6地址释放带宽。
*/
async ReleaseIp6AddressesBandwidth(
req: ReleaseIp6AddressesBandwidthRequest,
cb?: (error: string, rep: ReleaseIp6AddressesBandwidthResponse) => void
): Promise<ReleaseIp6AddressesBandwidthResponse> {
return this.request("ReleaseIp6AddressesBandwidth", req, cb)
}
/**
* 本接口(CreateDhcpIp)用于创建DhcpIp
*/
async CreateDhcpIp(
req: CreateDhcpIpRequest,
cb?: (error: string, rep: CreateDhcpIpResponse) => void
): Promise<CreateDhcpIpResponse> {
return this.request("CreateDhcpIp", req, cb)
}
/**
* 本接口(ModifyNatGatewaySourceIpTranslationNatRule)用于修改NAT网关SNAT转发规则。
*/
async ModifyNatGatewaySourceIpTranslationNatRule(
req: ModifyNatGatewaySourceIpTranslationNatRuleRequest,
cb?: (error: string, rep: ModifyNatGatewaySourceIpTranslationNatRuleResponse) => void
): Promise<ModifyNatGatewaySourceIpTranslationNatRuleResponse> {
return this.request("ModifyNatGatewaySourceIpTranslationNatRule", req, cb)
}
/**
* 本接口(ModifyCcnAttribute)用于修改云联网(CCN)的相关属性。
*/
async ModifyCcnAttribute(
req: ModifyCcnAttributeRequest,
cb?: (error: string, rep: ModifyCcnAttributeResponse) => void
): Promise<ModifyCcnAttributeResponse> {
return this.request("ModifyCcnAttribute", req, cb)
}
/**
* 本接口(DescribeSecurityGroupReferences)用于查询安全组被引用信息。
*/
async DescribeSecurityGroupReferences(
req: DescribeSecurityGroupReferencesRequest,
cb?: (error: string, rep: DescribeSecurityGroupReferencesResponse) => void
): Promise<DescribeSecurityGroupReferencesResponse> {
return this.request("DescribeSecurityGroupReferences", req, cb)
}
/**
* 本接口(DescribeSecurityGroupAssociationStatistics)用于查询安全组关联的实例统计。
*/
async DescribeSecurityGroupAssociationStatistics(
req: DescribeSecurityGroupAssociationStatisticsRequest,
cb?: (error: string, rep: DescribeSecurityGroupAssociationStatisticsResponse) => void
): Promise<DescribeSecurityGroupAssociationStatisticsResponse> {
return this.request("DescribeSecurityGroupAssociationStatistics", req, cb)
}
/**
* 本接口(UnassignIpv6SubnetCidrBlock)用于释放IPv6子网段。<br />
子网段如果还有IP占用且未回收,则子网段无法释放。
*/
async UnassignIpv6SubnetCidrBlock(
req: UnassignIpv6SubnetCidrBlockRequest,
cb?: (error: string, rep: UnassignIpv6SubnetCidrBlockResponse) => void
): Promise<UnassignIpv6SubnetCidrBlockResponse> {
return this.request("UnassignIpv6SubnetCidrBlock", req, cb)
}
/**
* 本接口(DescribeIpGeolocationDatabaseUrl)用于获取IP地理位置库下载链接。
*/
async DescribeIpGeolocationDatabaseUrl(
req: DescribeIpGeolocationDatabaseUrlRequest,
cb?: (error: string, rep: DescribeIpGeolocationDatabaseUrlResponse) => void
): Promise<DescribeIpGeolocationDatabaseUrlResponse> {
return this.request("DescribeIpGeolocationDatabaseUrl", req, cb)
}
/**
* 该接口用于修改IPV6地址访问internet的带宽
*/
async ModifyIp6AddressesBandwidth(
req: ModifyIp6AddressesBandwidthRequest,
cb?: (error: string, rep: ModifyIp6AddressesBandwidthResponse) => void
): Promise<ModifyIp6AddressesBandwidthResponse> {
return this.request("ModifyIp6AddressesBandwidth", req, cb)
}
/**
* 本接口(DescribeAddressTemplates)用于查询IP地址模板
*/
async DescribeAddressTemplates(
req: DescribeAddressTemplatesRequest,
cb?: (error: string, rep: DescribeAddressTemplatesResponse) => void
): Promise<DescribeAddressTemplatesResponse> {
return this.request("DescribeAddressTemplates", req, cb)
}
/**
* 本接口(CreateVpnConnection)用于创建VPN通道。
>?本接口为异步接口,可调用 [DescribeVpcTaskResult](https://cloud.tencent.com/document/api/215/59037) 接口查询任务执行结果,待任务执行成功后再进行其他操作。
>
*/
async CreateVpnConnection(
req: CreateVpnConnectionRequest,
cb?: (error: string, rep: CreateVpnConnectionResponse) => void
): Promise<CreateVpnConnectionResponse> {
return this.request("CreateVpnConnection", req, cb)
}
/**
* 本接口 (ModifyAddressAttribute) 用于修改[弹性公网IP](https://cloud.tencent.com/document/product/213/1941)(简称 EIP)的名称。
*/
async ModifyAddressAttribute(
req: ModifyAddressAttributeRequest,
cb?: (error: string, rep: ModifyAddressAttributeResponse) => void
): Promise<ModifyAddressAttributeResponse> {
return this.request("ModifyAddressAttribute", req, cb)
}
/**
* 本接口(DescribeAddressTemplateGroups)用于查询IP地址模板集合
*/
async DescribeAddressTemplateGroups(
req: DescribeAddressTemplateGroupsRequest,
cb?: (error: string, rep: DescribeAddressTemplateGroupsResponse) => void
): Promise<DescribeAddressTemplateGroupsResponse> {
return this.request("DescribeAddressTemplateGroups", req, cb)
}
/**
* 创建终端节点。
*/
async CreateVpcEndPoint(
req: CreateVpcEndPointRequest,
cb?: (error: string, rep: CreateVpcEndPointResponse) => void
): Promise<CreateVpcEndPointResponse> {
return this.request("CreateVpcEndPoint", req, cb)
}
/**
* 本接口(DetachClassicLinkVpc)用于删除私有网络和基础网络设备互通。
>?本接口为异步接口,可调用 [DescribeVpcTaskResult](https://cloud.tencent.com/document/api/215/59037) 接口查询任务执行结果,待任务执行成功后再进行其他操作。
>
*/
async DetachClassicLinkVpc(
req: DetachClassicLinkVpcRequest,
cb?: (error: string, rep: DetachClassicLinkVpcResponse) => void
): Promise<DetachClassicLinkVpcResponse> {
return this.request("DetachClassicLinkVpc", req, cb)
}
/**
* 本接口(CreateSecurityGroupWithPolicies)用于创建新的安全组(SecurityGroup),并且可以同时添加安全组规则(SecurityGroupPolicy)。
* 每个账户下每个地域的每个项目的<a href="https://cloud.tencent.com/document/product/213/12453">安全组数量限制</a>。
* 新建的安全组的入站和出站规则默认都是全部拒绝,在创建后通常您需要再调用CreateSecurityGroupPolicies将安全组的规则设置为需要的规则。
安全组规则说明:
* Version安全组规则版本号,用户每次更新安全规则版本会自动加1,防止您更新的路由规则已过期,不填不考虑冲突。
* Protocol字段支持输入TCP, UDP, ICMP, ICMPV6, GRE, ALL。
* CidrBlock字段允许输入符合cidr格式标准的任意字符串。(展开)在基础网络中,如果CidrBlock包含您的账户内的云服务器之外的设备在腾讯云的内网IP,并不代表此规则允许您访问这些设备,租户之间网络隔离规则优先于安全组中的内网规则。
* Ipv6CidrBlock字段允许输入符合IPv6 cidr格式标准的任意字符串。(展开)在基础网络中,如果Ipv6CidrBlock包含您的账户内的云服务器之外的设备在腾讯云的内网IPv6,并不代表此规则允许您访问这些设备,租户之间网络隔离规则优先于安全组中的内网规则。
* SecurityGroupId字段允许输入与待修改的安全组位于相同项目中的安全组ID,包括这个安全组ID本身,代表安全组下所有云服务器的内网IP。使用这个字段时,这条规则用来匹配网络报文的过程中会随着被使用的这个ID所关联的云服务器变化而变化,不需要重新修改。
* Port字段允许输入一个单独端口号,或者用减号分隔的两个端口号代表端口范围,例如80或8000-8010。只有当Protocol字段是TCP或UDP时,Port字段才被接受,即Protocol字段不是TCP或UDP时,Protocol和Port排他关系,不允许同时输入,否则会接口报错。
* Action字段只允许输入ACCEPT或DROP。
* CidrBlock, Ipv6CidrBlock, SecurityGroupId, AddressTemplate四者是排他关系,不允许同时输入,Protocol + Port和ServiceTemplate二者是排他关系,不允许同时输入。
* 一次请求中只能创建单个方向的规则, 如果需要指定索引(PolicyIndex)参数, 多条规则的索引必须一致。
*/
async CreateSecurityGroupWithPolicies(
req: CreateSecurityGroupWithPoliciesRequest,
cb?: (error: string, rep: CreateSecurityGroupWithPoliciesResponse) => void
): Promise<CreateSecurityGroupWithPoliciesResponse> {
return this.request("CreateSecurityGroupWithPolicies", req, cb)
}
/**
* 本接口(CreateSecurityGroupPolicies)用于创建安全组规则(SecurityGroupPolicy)。
在 SecurityGroupPolicySet 参数中:
<ul>
<li>Version 安全组规则版本号,用户每次更新安全规则版本会自动加1,防止您更新的路由规则已过期,不填不考虑冲突。</li>
<li>在创建出站和入站规则(Egress 和 Ingress)时:<ul>
<li>Protocol 字段支持输入TCP, UDP, ICMP, ICMPV6, GRE, ALL。</li>
<li>CidrBlock 字段允许输入符合cidr格式标准的任意字符串。在基础网络中,如果 CidrBlock 包含您的账户内的云服务器之外的设备在腾讯云的内网 IP,并不代表此规则允许您访问这些设备,租户之间网络隔离规则优先于安全组中的内网规则。</li>
<li>Ipv6CidrBlock 字段允许输入符合IPv6 cidr格式标准的任意字符串。在基础网络中,如果Ipv6CidrBlock 包含您的账户内的云服务器之外的设备在腾讯云的内网 IPv6,并不代表此规则允许您访问这些设备,租户之间网络隔离规则优先于安全组中的内网规则。</li>
<li>SecurityGroupId 字段允许输入与待修改的安全组位于相同项目中的安全组 ID,包括这个安全组 ID 本身,代表安全组下所有云服务器的内网 IP。使用这个字段时,这条规则用来匹配网络报文的过程中会随着被使用的这个 ID 所关联的云服务器变化而变化,不需要重新修改。</li>
<li>Port 字段允许输入一个单独端口号,或者用减号分隔的两个端口号代表端口范围,例如80或8000-8010。只有当 Protocol 字段是 TCP 或 UDP 时,Port 字段才被接受,即 Protocol 字段不是 TCP 或 UDP 时,Protocol 和 Port 排他关系,不允许同时输入,否则会接口报错。</li>
<li>Action 字段只允许输入 ACCEPT 或 DROP。</li>
<li>CidrBlock, Ipv6CidrBlock, SecurityGroupId, AddressTemplate 四者是排他关系,不允许同时输入,Protocol + Port 和 ServiceTemplate 二者是排他关系,不允许同时输入。</li>
<li>一次请求中只能创建单个方向的规则, 如果需要指定索引(PolicyIndex)参数, 多条规则的索引必须一致。</li>
</ul></li></ul>
*/
async CreateSecurityGroupPolicies(
req: CreateSecurityGroupPoliciesRequest,
cb?: (error: string, rep: CreateSecurityGroupPoliciesResponse) => void
): Promise<CreateSecurityGroupPoliciesResponse> {
return this.request("CreateSecurityGroupPolicies", req, cb)
}
/**
* 本接口(ModifyNetworkAclAttribute)用于修改网络ACL属性。
*/
async ModifyNetworkAclAttribute(
req: ModifyNetworkAclAttributeRequest,
cb?: (error: string, rep: ModifyNetworkAclAttributeResponse) => void
): Promise<ModifyNetworkAclAttributeResponse> {
return this.request("ModifyNetworkAclAttribute", req, cb)
}
/**
* 本接口(ResetNatGatewayConnection)用来NAT网关并发连接上限。
*/
async ResetNatGatewayConnection(
req: ResetNatGatewayConnectionRequest,
cb?: (error: string, rep: ResetNatGatewayConnectionResponse) => void
): Promise<ResetNatGatewayConnectionResponse> {
return this.request("ResetNatGatewayConnection", req, cb)
}
/**
* 本接口(ModifyVpcAttribute)用于修改私有网络(VPC)的相关属性。
*/
async ModifyVpcAttribute(
req: ModifyVpcAttributeRequest,
cb?: (error: string, rep: ModifyVpcAttributeResponse) => void
): Promise<ModifyVpcAttributeResponse> {
return this.request("ModifyVpcAttribute", req, cb)
}
/**
* 查询终端节点列表。
*/
async DescribeVpcEndPoint(
req: DescribeVpcEndPointRequest,
cb?: (error: string, rep: DescribeVpcEndPointResponse) => void
): Promise<DescribeVpcEndPointResponse> {
return this.request("DescribeVpcEndPoint", req, cb)
}
/**
* 创建路由型VPN网关的目的路由
*/
async CreateVpnGatewayRoutes(
req: CreateVpnGatewayRoutesRequest,
cb?: (error: string, rep: CreateVpnGatewayRoutesResponse) => void
): Promise<CreateVpnGatewayRoutesResponse> {
return this.request("CreateVpnGatewayRoutes", req, cb)
}
/**
* 创建终端服务白名单。
*/
async CreateVpcEndPointServiceWhiteList(
req: CreateVpcEndPointServiceWhiteListRequest,
cb?: (error: string, rep: CreateVpcEndPointServiceWhiteListResponse) => void
): Promise<CreateVpcEndPointServiceWhiteListResponse> {
return this.request("CreateVpcEndPointServiceWhiteList", req, cb)
}
} | the_stack |
namespace eui {
/**
* @private
*/
const enum Keys {
useVirtualLayout,
useVirtualLayoutChanged,
rendererToClassMap,
freeRenderers,
createNewRendererFlag,
itemRendererChanged,
itemRenderer,
itemRendererFunction,
typicalItemChanged,
typicalLayoutRect,
cleanFreeRenderer,
renderersBeingUpdated,
typicalItem,
itemRendererSkinName,
itemRendererSkinNameChange
}
/**
* The DataGroup class is the base container class for data items.
* The DataGroup class converts data items to visual elements for display.
* While this container can hold visual elements, it is often used only
* to hold data items as children.
*
* @see eui.Group
* @see http://edn.egret.com/cn/article/index/id/527 Data container
* @see http://edn.egret.com/cn/article/index/id/528 Array collection
* @defaultProperty dataProvider
* @includeExample extension/eui/components/DataGroupExample.ts
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* DataGroup 类将数据项目转换为可视元素以进行显示。
* 尽管此容器可以包含可视元素,但它通常仅用于包含作为子项的数据项目。
*
* @see eui.Group
* @see http://edn.egret.com/cn/article/index/id/527 数据容器
* @see http://edn.egret.com/cn/article/index/id/528 数组集合
* @defaultProperty dataProvider
* @includeExample extension/eui/components/DataGroupExample.ts
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
export class DataGroup extends Group {
/**
* Constructor.
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 构造函数。
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
public constructor() {
super();
this.$DataGroup = {
0: true, //useVirtualLayout
1: false, //useVirtualLayoutChanged
2: {}, //rendererToClassMap
3: {}, //freeRenderers
4: false, //createNewRendererFlag
5: false, //itemRendererChanged
6: null, //itemRenderer
7: null, //itemRendererFunction
8: false, //typicalItemChanged
9: null, //typicalLayoutRect
10: false, //cleanFreeRenderer
11: false, //renderersBeingUpdated
12: null, //typicalItem
13: null, //itemRendererSkinName
14: false, //itemRendererSkinNameChange
};
}
$DataGroup: Object;
/**
* @copy eui.LayoutBase#useVirtualLayout
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public get useVirtualLayout(): boolean {
return this.$layout ? this.$layout.$useVirtualLayout :
this.$DataGroup[Keys.useVirtualLayout];
}
public set useVirtualLayout(value: boolean) {
value = !!value;
let values = this.$DataGroup;
if (value === values[Keys.useVirtualLayout])
return;
values[Keys.useVirtualLayout] = value;
if (this.$layout)
this.$layout.useVirtualLayout = value;
}
/**
* @private
*
* @param value
*/
$setLayout(value: LayoutBase): boolean {
if (value == this.$layout)
return false;
if (this.$layout) {
this.$layout.setTypicalSize(0, 0);
this.$layout.removeEventListener("useVirtualLayoutChanged", this.onUseVirtualLayoutChanged, this);
}
if (this.$layout && value && (this.$layout.$useVirtualLayout != value.$useVirtualLayout))
this.onUseVirtualLayoutChanged();
let result: boolean = super.$setLayout(value);
if (value) {
let rect = this.$DataGroup[Keys.typicalLayoutRect];
if (rect) {
value.setTypicalSize(rect.width, rect.height);
}
value.useVirtualLayout = this.$DataGroup[Keys.useVirtualLayout];
value.addEventListener("useVirtualLayoutChanged", this.onUseVirtualLayoutChanged, this);
}
return result;
}
/**
* @private
* 是否使用虚拟布局标记改变
*/
private onUseVirtualLayoutChanged(event?: egret.Event): void {
let values = this.$DataGroup;
values[Keys.useVirtualLayoutChanged] = true;
values[Keys.cleanFreeRenderer] = true;
this.removeDataProviderListener();
this.invalidateProperties();
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public setVirtualElementIndicesInView(startIndex: number, endIndex: number): void {
if (!this.$layout || !this.$layout.$useVirtualLayout) {
return;
}
let indexToRenderer = this.$indexToRenderer;
let keys = Object.keys(indexToRenderer);
let length = keys.length;
for (let i = 0; i < length; i++) {
let index = +keys[i];
if (index < startIndex || index > endIndex) {
this.freeRendererByIndex(index);
}
}
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public getElementAt(index: number): egret.DisplayObject {
return this.$indexToRenderer[index];
}
/**
* @inheritDoc
*
* @version Egret 2.5.2
* @version eui 1.0
* @platform Web,Native
*/
public getVirtualElementAt(index: number): UIComponent {
index = +index | 0;
if (index < 0 || index >= this.$dataProvider.length)
return null;
let renderer = this.$indexToRenderer[index];
if (!renderer) {
let item: any = this.$dataProvider.getItemAt(index);
renderer = this.createVirtualRenderer(item);
this.$indexToRenderer[index] = renderer;
this.updateRenderer(renderer, index, item);
let values = this.$DataGroup;
if (values[Keys.createNewRendererFlag]) {
renderer.validateNow();
values[Keys.createNewRendererFlag] = false;
this.rendererAdded(renderer, index, item);
}
}
return renderer;
}
/**
* @private
* 释放指定索引处的项呈示器
*/
private freeRendererByIndex(index: number): void {
let renderer = this.$indexToRenderer[index];
if (renderer) {
delete this.$indexToRenderer[index];
this.doFreeRenderer(renderer);
}
}
/**
* @private
*
* @param renderer
*/
private doFreeRenderer(renderer: IItemRenderer): void {
let values = this.$DataGroup;
let rendererClass = values[Keys.rendererToClassMap][renderer.$hashCode];
let hashCode = rendererClass.$hashCode;
if (!values[Keys.freeRenderers][hashCode]) {
values[Keys.freeRenderers][hashCode] = [];
}
values[Keys.freeRenderers][hashCode].push(renderer);
renderer.visible = false;
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public invalidateSize(): void {
if (!this.$DataGroup[Keys.createNewRendererFlag]) {//虚拟布局时创建子项不需要重新验证
super.invalidateSize();
}
}
/**
* @private
* 为指定索引创建虚拟的项呈示器
*/
private createVirtualRenderer(item: any): IItemRenderer {
let renderer: IItemRenderer;
let rendererClass = this.itemToRendererClass(item);
let hashCode = rendererClass.$hashCode;
let values = this.$DataGroup;
let freeRenderers = values[Keys.freeRenderers];
if (freeRenderers[hashCode] && freeRenderers[hashCode].length > 0) {
renderer = freeRenderers[hashCode].pop();
renderer.visible = true;
this.invalidateDisplayList();
return renderer;
}
values[Keys.createNewRendererFlag] = true;
return this.createOneRenderer(rendererClass);
}
/**
* @private
* 根据rendererClass创建一个Renderer,并添加到显示列表
*/
private createOneRenderer(rendererClass: any): IItemRenderer {
let renderer = <IItemRenderer>(new rendererClass());
let values = this.$DataGroup;
values[Keys.rendererToClassMap][renderer.$hashCode] = rendererClass;
if (!egret.is(renderer, "eui.IItemRenderer")) {
return null;
}
if (values[Keys.itemRendererSkinName]) {
this.setItemRenderSkinName(renderer, values[Keys.itemRendererSkinName]);
}
this.addChild(renderer);
return renderer;
}
/**
* @private
* 设置项呈示器的默认皮肤
*/
private setItemRenderSkinName(renderer: IItemRenderer, skinName: any): void {
if (renderer && renderer instanceof Component) {
let comp: Component = <Component><any>renderer;
if (!comp.$Component[sys.ComponentKeys.skinNameExplicitlySet]) {
comp.skinName = skinName;
comp.$Component[sys.ComponentKeys.skinNameExplicitlySet] = false;
}
}
}
/**
* @private
*/
$dataProviderChanged: boolean = false;
/**
* @private
*/
$dataProvider: ICollection = null;
/**
* The data provider for this DataGroup.
* It must be an ICollection, such as ArrayCollection
*
* @see eui.ICollection
* @see eui.ArrayCollection
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 列表数据源,请使用实现了ICollection接口的数据类型,例如 ArrayCollection
*
* @see eui.ICollection
* @see eui.ArrayCollection
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
public get dataProvider(): ICollection {
return this.$dataProvider;
}
public set dataProvider(value: ICollection) {
this.$setDataProvider(value);
}
/**
* @private
*
* @param value
*/
$setDataProvider(value: ICollection): boolean {
if (this.$dataProvider == value || (value && !value.getItemAt))
return false;
this.removeDataProviderListener();
this.$dataProvider = value;
this.$dataProviderChanged = true;
this.$DataGroup[Keys.cleanFreeRenderer] = true;
this.invalidateProperties();
this.invalidateSize();
this.invalidateDisplayList();
return true;
}
/**
* @private
* 移除数据源监听
*/
private removeDataProviderListener(): void {
if (this.$dataProvider)
this.$dataProvider.removeEventListener(CollectionEvent.COLLECTION_CHANGE, this.onCollectionChange, this);
}
/**
* Called when contents within the dataProvider changes. We will catch certain
* events and update our children based on that.
*
* @param event 事件<code>eui.CollectionEvent</code>的对象。
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 数据源改变事件处理。
*
* @param event 事件<code>eui.CollectionEvent</code>的对象。
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
protected onCollectionChange(event: CollectionEvent): void {
switch (event.kind) {
case CollectionEventKind.ADD:
this.itemAddedHandler(event.items, event.location);
break;
case CollectionEventKind.REMOVE:
this.itemRemovedHandler(event.items, event.location);
break;
case CollectionEventKind.UPDATE:
case CollectionEventKind.REPLACE:
this.itemUpdatedHandler(event.items[0], event.location);
break;
case CollectionEventKind.RESET:
case CollectionEventKind.REFRESH: {
if (this.$layout && this.$layout.$useVirtualLayout) {
const indexToRenderer = this.$indexToRenderer;
const keys = Object.keys(indexToRenderer);
const length = keys.length;
for (let i = length - 1; i >= 0; i--) {
const index = +keys[i];
this.freeRendererByIndex(index);
}
}
this.$dataProviderChanged = true;
this.invalidateProperties();
break;
}
default: {
egret.$warn(2204, event.kind);
break;
}
}
this.invalidateSize();
this.invalidateDisplayList();
}
/**
* @private
* 数据源添加项目事件处理
*/
private itemAddedHandler(items: any[], index: number): void {
let length = items.length;
for (let i = 0; i < length; i++) {
this.itemAdded(items[i], index + i);
}
this.resetRenderersIndices();
}
/**
* @private
* 数据源移除项目事件处理
*/
private itemRemovedHandler(items: any[], location: number): void {
let length = items.length;
for (let i = length - 1; i >= 0; i--) {
this.itemRemoved(items[i], location + i);
}
this.resetRenderersIndices();
}
/**
* Adds the item for the specified dataProvider item to this DataGroup.
*
* This method is called as needed by the DataGroup implementation,
* it should not be called directly.
*
* @param item The item that was added, the value of dataProvider[index].
* @param index The index where the dataProvider item was added.
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 添加一个指定的数据到数据源。
*
* 这个方法不应该由开发者直接调用,而用于本类自动内调用。
*
* @param item 添加的数据项。
* @param index 被添加到的索引。
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
protected itemAdded(item: any, index: number): void {
if (this.$layout)
this.$layout.elementAdded(index);
if (this.$layout && this.$layout.$useVirtualLayout) {
this.$indexToRenderer.splice(index, 0, null);
return;
}
let renderer = this.createVirtualRenderer(item);
this.$indexToRenderer.splice(index, 0, renderer);
if (renderer) {
this.updateRenderer(renderer, index, item);
let values = this.$DataGroup;
if (values[Keys.createNewRendererFlag]) {
values[Keys.createNewRendererFlag] = false;
this.rendererAdded(renderer, index, item);
}
}
}
/**
* Removes the itemRenderer for the specified dataProvider item from this DataGroup.
*
* This method is called as needed by the DataGroup implementation,
* it should not be called directly.
*
* @param item The item that is being removed.
* @param index The index of the item that is being removed.
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 删除数据源中指定的项。
*
* 这个方法不应该由开发者直接调用,而用于本类自动内调用。
*
* @param item 移除的数据项。
* @param index 被移除的索引。
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
protected itemRemoved(item: any, index: number): void {
if (this.$layout)
this.$layout.elementRemoved(index);
let oldRenderer = this.$indexToRenderer[index];
if (this.$indexToRenderer.length > index)
this.$indexToRenderer.splice(index, 1);
if (oldRenderer) {
if (this.$layout && this.$layout.$useVirtualLayout) {
this.doFreeRenderer(oldRenderer);
}
else {
this.rendererRemoved(oldRenderer, index, item);
this.removeChild(oldRenderer);
}
}
}
/**
* @private
* 更新当前所有项的索引
*/
private resetRenderersIndices(): void {
let indexToRenderer = this.$indexToRenderer;
if (indexToRenderer.length == 0)
return;
if (this.$layout && this.$layout.$useVirtualLayout) {
let keys = Object.keys(indexToRenderer);
let length = keys.length;
for (let i = 0; i < length; i++) {
let index = +keys[i];
this.resetRendererItemIndex(index);
}
}
else {
let indexToRendererLength = indexToRenderer.length;
for (let index = 0; index < indexToRendererLength; index++) {
this.resetRendererItemIndex(index);
}
}
}
/**
* @private
* 数据源更新或替换项目事件处理
*/
private itemUpdatedHandler(item: any, location: number): void {
if (this.$DataGroup[Keys.renderersBeingUpdated]) {
return;//防止无限循环
}
let renderer = this.$indexToRenderer[location];
if (renderer)
this.updateRenderer(renderer, location, item);
}
/**
* @private
* 调整指定项呈示器的索引值
*/
private resetRendererItemIndex(index: number): void {
let renderer = this.$indexToRenderer[index];
if (renderer)
renderer.itemIndex = index;
}
/**
* The item renderer to use for data items.
* The class must implement the IItemRenderer interface.
* If defined, the <code>itemRendererFunction</code> property
* takes precedence over this property.
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 用于数据项目的项呈示器。您应该直接为此属性赋值自定义类的类定义,而不是一个实例。注意:该类必须实现 IItemRenderer 接口。<br/>
* rendererClass获取顺序:itemRendererFunction > itemRenderer > 默认ItemRenerer。
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
public get itemRenderer(): any {
return this.$DataGroup[Keys.itemRenderer];
}
public set itemRenderer(value: any) {
let values = this.$DataGroup;
if (values[Keys.itemRenderer] == value)
return;
values[Keys.itemRenderer] = value;
values[Keys.itemRendererChanged] = true;
values[Keys.typicalItemChanged] = true;
values[Keys.cleanFreeRenderer] = true;
this.removeDataProviderListener();
this.invalidateProperties();
}
/**
* The skinName property of the itemRenderer.This property will be passed to itemRenderer.skinName as default value,if you
* did not set it explicitly.<br>
* Note: This property is invalid if the itemRenderer is not a subclass of the Component class.
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 条目渲染器的可选皮肤标识符。在实例化itemRenderer时,若其内部没有设置过skinName,则将此属性的值赋值给它的skinName。
* 注意:若 itemRenderer 不是 Component 的子类,则此属性无效。
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
public get itemRendererSkinName(): any {
return this.$DataGroup[Keys.itemRendererSkinName];
}
public set itemRendererSkinName(value: any) {
let values = this.$DataGroup;
if (values[Keys.itemRendererSkinName] == value)
return;
values[Keys.itemRendererSkinName] = value;
if (this.$UIComponent[sys.UIKeys.initialized]) {
values[Keys.itemRendererSkinNameChange] = true;
this.invalidateProperties();
}
}
/**
* Function that returns an item renderer for a
* specific item.
*
* If defined, this property
* takes precedence over the <code>itemRenderer</code> property.
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 为某个特定数据项返回一个项呈示器类定义的函数。
* rendererClass获取顺序:itemRendererFunction > itemRenderer > 默认ItemRenerer。
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
public get itemRendererFunction(): (item: any) => any {
return this.$DataGroup[Keys.itemRendererFunction];
}
public set itemRendererFunction(value: (item: any) => any) {
let values = this.$DataGroup;
if (values[Keys.itemRendererFunction] == value)
return;
values[Keys.itemRendererFunction] = value;
values[Keys.itemRendererChanged] = true;
values[Keys.typicalItemChanged] = true;
this.removeDataProviderListener();
this.invalidateProperties();
}
/**
* @private
* 为特定的数据项返回项呈示器的工厂实例
*/
private itemToRendererClass(item: any): any {
let rendererClass: any;
let values = this.$DataGroup;
if (values[Keys.itemRendererFunction]) {
rendererClass = values[Keys.itemRendererFunction](item);
}
if (!rendererClass) {
rendererClass = values[Keys.itemRenderer];
}
if (!rendererClass) {
rendererClass = ItemRenderer;
}
if (!rendererClass.$hashCode) {
rendererClass.$hashCode = egret.$hashCount++;
}
return rendererClass;
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
protected createChildren(): void {
if (!this.$layout) {
let layout: VerticalLayout = new VerticalLayout();
layout.gap = 0;
layout.horizontalAlign = JustifyAlign.CONTENT_JUSTIFY;
this.$setLayout(layout);
}
super.createChildren();
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
protected commitProperties(): void {
let values = this.$DataGroup;
if (values[Keys.itemRendererChanged] || this.$dataProviderChanged || values[Keys.useVirtualLayoutChanged]) {
this.removeAllRenderers();
if (this.$layout)
this.$layout.clearVirtualLayoutCache();
this.setTypicalLayoutRect(null);
values[Keys.useVirtualLayoutChanged] = false;
values[Keys.itemRendererChanged] = false;
if (this.$dataProvider)
this.$dataProvider.addEventListener(CollectionEvent.COLLECTION_CHANGE, this.onCollectionChange, this);
if (this.$layout && this.$layout.$useVirtualLayout) {
this.invalidateSize();
this.invalidateDisplayList();
}
else {
this.createRenderers();
}
if (this.$dataProviderChanged) {
this.$dataProviderChanged = false;
this.scrollV = this.scrollH = 0;
}
}
super.commitProperties();
if (values[Keys.typicalItemChanged]) {
values[Keys.typicalItemChanged] = false;
if (this.$dataProvider && this.$dataProvider.length > 0) {
values[Keys.typicalItem] = this.$dataProvider.getItemAt(0);
this.measureRendererSize();
}
}
if (values[Keys.itemRendererSkinNameChange]) {
values[Keys.itemRendererSkinNameChange] = false;
let skinName = values[Keys.itemRendererSkinName];
let indexToRenderer = this.$indexToRenderer;
let keys = Object.keys(indexToRenderer);
let length = keys.length;
for (let i = 0; i < length; i++) {
let index = keys[i];
this.setItemRenderSkinName(indexToRenderer[index], skinName);
}
let freeRenderers = values[Keys.freeRenderers];
keys = Object.keys(freeRenderers);
length = keys.length;
for (let i = 0; i < length; i++) {
let hashCode = keys[i];
let list: IItemRenderer[] = freeRenderers[hashCode];
let length = list.length;
for (let i = 0; i < length; i++) {
this.setItemRenderSkinName(list[i], skinName);
}
}
}
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
protected measure(): void {
if (this.$layout && this.$layout.$useVirtualLayout) {
this.ensureTypicalLayoutElement();
}
super.measure();
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
protected updateDisplayList(unscaledWidth: number, unscaledHeight: number): void {
let useVirtualLayout = (this.$layout && this.$layout.$useVirtualLayout);
if (useVirtualLayout) {
this.ensureTypicalLayoutElement();
}
super.updateDisplayList(unscaledWidth, unscaledHeight);
let values = this.$DataGroup;
if (useVirtualLayout) {
//检查索引 0 处的项测量大小是否发生改变,若改变就重新计算 typicalLayoutRect
let rect = values[Keys.typicalLayoutRect];
if (rect) {
let renderer = this.$indexToRenderer[0];
if (renderer) {
let bounds = egret.$TempRectangle;
renderer.getPreferredBounds(bounds);
if (bounds.width != rect.width || bounds.height != rect.height) {
values[Keys.typicalLayoutRect] = null;
}
}
}
}
}
/**
* @private
* 确保测量过默认条目大小。
*/
private ensureTypicalLayoutElement(): void {
if (this.$DataGroup[Keys.typicalLayoutRect])
return;
if (this.$dataProvider && this.$dataProvider.length > 0) {
this.$DataGroup[Keys.typicalItem] = this.$dataProvider.getItemAt(0);
this.measureRendererSize();
}
}
/**
* @private
* 测量项呈示器默认尺寸
*/
private measureRendererSize(): void {
let values = this.$DataGroup;
if (values[Keys.typicalItem] == undefined) {
this.setTypicalLayoutRect(null);
return;
}
let typicalRenderer = this.createVirtualRenderer(values[Keys.typicalItem]);
if (!typicalRenderer) {
this.setTypicalLayoutRect(null);
return;
}
this.updateRenderer(typicalRenderer, 0, values[Keys.typicalItem]);
typicalRenderer.validateNow();
let bounds = egret.$TempRectangle;
typicalRenderer.getPreferredBounds(bounds);
let rect = new egret.Rectangle(0, 0, bounds.width, bounds.height);
if (this.$layout && this.$layout.$useVirtualLayout) {
if (values[Keys.createNewRendererFlag]) {
this.rendererAdded(typicalRenderer, 0, values[Keys.typicalItem]);
}
this.doFreeRenderer(typicalRenderer);
}
else {
this.removeChild(typicalRenderer);
}
this.setTypicalLayoutRect(rect);
values[Keys.createNewRendererFlag] = false;
}
/**
* @private
* 设置项目默认大小
*/
private setTypicalLayoutRect(rect: egret.Rectangle): void {
this.$DataGroup[Keys.typicalLayoutRect] = rect;
if (this.$layout) {
if (rect) {
this.$layout.setTypicalSize(rect.width, rect.height);
}
else {
this.$layout.setTypicalSize(0, 0);
}
}
}
/**
* @private
* 索引到项呈示器的转换数组
*/
$indexToRenderer: IItemRenderer[] = [];
/**
* @private
* 移除所有项呈示器
*/
private removeAllRenderers(): void {
let indexToRenderer = this.$indexToRenderer;
let keys = Object.keys(indexToRenderer);
let length = keys.length;
for (let i = 0; i < length; i++) {
let index = keys[i];
let renderer = indexToRenderer[index];
if (renderer) {
this.rendererRemoved(renderer, renderer.itemIndex, renderer.data);
this.removeChild(renderer);
}
}
this.$indexToRenderer = [];
let values = this.$DataGroup;
if (values[Keys.cleanFreeRenderer]) {
let freeRenderers = values[Keys.freeRenderers];
let keys = Object.keys(freeRenderers);
let length = keys.length;
for (let i = 0; i < length; i++) {
let hashCode = keys[i];
let list: IItemRenderer[] = freeRenderers[hashCode];
let length = list.length;
for (let i = 0; i < length; i++) {
let renderer = list[i];
this.rendererRemoved(renderer, renderer.itemIndex, renderer.data);
this.removeChild(renderer);
}
}
values[Keys.freeRenderers] = {};
values[Keys.rendererToClassMap] = {};
values[Keys.cleanFreeRenderer] = false;
}
}
/**
* @private
* 为数据项创建项呈示器
*/
private createRenderers(): void {
if (!this.$dataProvider)
return;
let index = 0;
let length = this.$dataProvider.length;
for (let i = 0; i < length; i++) {
let item = this.$dataProvider.getItemAt(i);
let rendererClass = this.itemToRendererClass(item);
let renderer: IItemRenderer = this.createOneRenderer(rendererClass);
if (!renderer)
continue;
this.$indexToRenderer[index] = renderer;
this.updateRenderer(renderer, index, item);
this.rendererAdded(renderer, index, item);
index++;
}
}
/**
* Updates the renderer for reuse.
* This method first prepares the item
* renderer for reuse by cleaning out any stale properties
* as well as updating it with new properties.<p/>
*
* The last thing this method should do is set the <code>data</code> property
* of the item renderer.
*
* @param renderer The item renderer.
* @param itemIndex The index of the data in the data provider.
* @param data The data object this item renderer is representing.
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 此方法首先会准备项呈示器以重用,方法是清除任何旧属性,同时使用新属性进行更新。<p/>
*
* 最后,此方法应对项呈示器设置 data 属性。
*
* @param renderer 项呈示器。
* @param itemIndex 数据提供程序中的数据索引。
* @param data 此项呈示器正在表示的数据对象。
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
public updateRenderer(renderer: IItemRenderer, itemIndex: number, data: any): IItemRenderer {
let values = this.$DataGroup;
values[Keys.renderersBeingUpdated] = true;
renderer.itemIndex = itemIndex;
if (renderer.parent == this) {
this.setChildIndex(renderer, itemIndex);
}
renderer.data = data;
values[Keys.renderersBeingUpdated] = false;
return renderer;
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public get numElements(): number {
if (!this.$dataProvider)
return 0;
return this.$dataProvider.length;
}
/**
* Adds the itemRenderer for the specified dataProvider item to this DataGroup.
*
* This method is called as needed by the DataGroup implementation,
* it should not be called directly.
*
* @param renderer The renderer that was added.
* @param index The index where the dataProvider item was added.
* @param item The item that was added, the value of dataProvider[index].
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 项呈示器被添加.
*
* 这个方法不能直接调用,它是由该类自身自动调用的。
*
* @param renderer 添加的项呈示器
* @param index 项呈示器的索引
* @param item 项呈示器对应的数据
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
protected rendererAdded(renderer: IItemRenderer, index: number, item: any): void {
}
/**
* Removes the itemRenderer for the specified dataProvider item from this DataGroup.
*
* This method is called as needed by the DataGroup implementation,
* it should not be called directly.
*
* @param renderer The renderer that is being removed.
* @param index The index of the item that is being removed.
* @param item The item that is being removed.
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 项呈示器被移除。
* 这个方法不能直接调用,它是由该类自身自动调用的。
*
* @param renderer 移除的项呈示器
* @param index 项呈示器的索引
* @param item 项呈示器对应的数据
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
protected rendererRemoved(renderer: IItemRenderer, index: number, item: any): void {
}
}
registerProperty(DataGroup, "itemRenderer", "Class");
registerProperty(DataGroup, "itemRendererSkinName", "Class");
registerProperty(DataGroup, "dataProvider", "eui.ICollection", true);
} | the_stack |
import {FS, Utils} from '../../lib';
import {SSBSet, ssbSets} from '../../data/mods/ssb/random-teams';
interface SetCriteria {
moves: {mustHave: Move[], mustNotHave: Move[]};
ability: {mustHave?: Ability, mustNotHave: Ability[]};
item: {mustHave?: Item, mustNotHave: Item[]};
nature: {mustHave?: Nature, mustNotHave: Nature[]};
}
function getHTMLCriteriaDescription(criteria: SetCriteria) {
const format = (list: {name: string}[]) => list.map(m => Utils.html`<strong>${m.name}</strong>`);
const parts = [];
const {moves, ability, item, nature} = criteria;
if (moves.mustHave.length) {
parts.push(`had the move${Chat.plural(moves.mustHave.length)} ${Chat.toListString(format(moves.mustHave))}`);
}
if (moves.mustNotHave.length) {
parts.push(`did not have the move${Chat.plural(moves.mustNotHave.length)} ${Chat.toListString(format(moves.mustNotHave), 'or')}`);
}
if (ability.mustHave) {
parts.push(Utils.html`had the ability <strong>${ability.mustHave.name}</strong>`);
}
if (ability.mustNotHave.length) {
parts.push(`did not have the ${Chat.plural(ability.mustNotHave.length, 'abilities', 'ability')} ${Chat.toListString(format(ability.mustNotHave), 'or')}`);
}
if (item.mustHave) {
parts.push(Utils.html`had the item <strong>${item.mustHave.name}</strong>`);
}
if (item.mustNotHave.length) {
parts.push(`did not have the item${Chat.plural(item.mustNotHave.length)} ${Chat.toListString(format(item.mustNotHave), 'or')}`);
}
if (nature.mustHave) {
parts.push(Utils.html`had the nature <strong>${nature.mustHave.name}</strong>`);
}
if (nature.mustNotHave.length) {
parts.push(`did not have the nature${Chat.plural(nature.mustNotHave.length)} ${Chat.toListString(format(nature.mustNotHave), 'or')}`);
}
return Chat.toListString(parts, 'and');
}
function setProbability(
species: Species,
format: Format,
criteria: SetCriteria,
rounds = 700
): {rounds: number, matches: number} {
const results = {rounds, matches: 0};
const generator = Teams.getGenerator(format);
for (let i = 0; i < rounds; i++) {
const set = generator.randomSet(species);
if (criteria.item.mustHave && set.item !== criteria.item.mustHave.name) continue;
if (criteria.item.mustNotHave.some(item => item.name === set.item)) continue;
if (criteria.ability.mustHave && set.ability !== criteria.ability.mustHave.name) continue;
if (criteria.ability.mustNotHave.some(ability => ability.name === set.ability)) continue;
if (criteria.nature.mustHave && set.nature !== criteria.nature.mustHave.name) continue;
if (criteria.nature.mustNotHave.some(nature => nature.name === set.nature)) continue;
const setHasMove = (move: Move) => {
const id = move.id === 'hiddenpower' ? `${move.id}${toID(move.type)}` : move.id;
return set.moves.includes(id);
};
if (!criteria.moves.mustHave.every(setHasMove)) continue;
if (criteria.moves.mustNotHave.some(setHasMove)) continue;
results.matches++;
}
return results;
}
const GEN_NAMES: {[k: string]: string} = {
gen1: '[Gen 1]', gen2: '[Gen 2]', gen3: '[Gen 3]', gen4: '[Gen 4]', gen5: '[Gen 5]', gen6: '[Gen 6]', gen7: '[Gen 7]',
};
const STAT_NAMES: {[k: string]: string} = {
hp: "HP", atk: "Atk", def: "Def", spa: "SpA", spd: "SpD", spe: "Spe",
};
const TIERS: {[k: string]: string} = {
uber: "Uber", ubers: "Uber",
ou: "OU", uu: "UU", ru: "RU", nu: "NU", pu: "PU",
mono: "Mono", monotype: "Mono", lc: "LC", littlecup: "LC",
};
function formatAbility(ability: Ability | string) {
ability = Dex.abilities.get(ability);
return `<a href="https://${Config.routes.dex}/abilities/${ability.id}" target="_blank" class="subtle" style="white-space:nowrap">${ability.name}</a>`;
}
function formatNature(n: string) {
const nature = Dex.natures.get(n);
return nature.name;
}
function formatMove(move: Move | string) {
move = Dex.moves.get(move);
return `<a href="https://${Config.routes.dex}/moves/${move.id}" target="_blank" class="subtle" style="white-space:nowrap">${move.name}</a>`;
}
function formatItem(item: Item | string) {
if (typeof item === 'string' && item === "No Item") {
return `No Item`;
} else {
item = Dex.items.get(item);
return `<a href="https://${Config.routes.dex}/items/${item.id}" target="_blank" class="subtle" style="white-space:nowrap">${item.name}</a>`;
}
}
function getRBYMoves(species: string | Species) {
species = Dex.mod(`gen1`).species.get(species);
let buf = ``;
if (species.randomBattleMoves) {
buf += `<details><summary>Randomized moves</summary>`;
buf += species.randomBattleMoves.map(formatMove).sort().join(", ");
buf += `</details>`;
}
if (species.comboMoves) {
buf += `<details><summary>Combo moves</summary>`;
buf += species.comboMoves.map(formatMove).sort().join(", ");
buf += `</details>`;
}
if (species.exclusiveMoves) {
buf += `<details><summary>Exclusive moves</summary>`;
buf += species.exclusiveMoves.map(formatMove).sort().join(", ");
buf += `</details>`;
}
if (species.essentialMove) {
buf += `<details><summary>Essential move</summary>`;
buf += formatMove(species.essentialMove);
buf += `</details>`;
}
if (
!species.randomBattleMoves && !species.comboMoves &&
!species.exclusiveMoves && !species.essentialMove
) {
return false;
}
return buf;
}
function getLetsGoMoves(species: string | Species) {
species = Dex.species.get(species);
const isLetsGoLegal = (
(species.num <= 151 || ['Meltan', 'Melmetal'].includes(species.name)) &&
(!species.forme || ['Alola', 'Mega', 'Mega-X', 'Mega-Y', 'Starter'].includes(species.forme))
);
if (!isLetsGoLegal) return false;
if (!species.randomBattleMoves?.length) return false;
return species.randomBattleMoves.map(formatMove).sort().join(`, `);
}
function battleFactorySets(species: string | Species, tier: string | null, gen = 'gen7', isBSS = false) {
species = Dex.species.get(species);
if (typeof species.battleOnly === 'string') {
species = Dex.species.get(species.battleOnly);
}
gen = toID(gen);
const genNum = parseInt(gen[3]);
if (isNaN(genNum) || genNum < 6 || (isBSS && genNum < 7)) return null;
const statsFile = JSON.parse(
FS(`data${gen === 'gen8' ? '/' : `/mods/${gen}`}/${isBSS ? `bss-` : ``}factory-sets.json`).readIfExistsSync() ||
"{}"
);
if (!Object.keys(statsFile).length) return null;
let buf = ``;
if (!isBSS) {
if (!tier) return {e: `Please provide a valid tier.`};
if (!(toID(tier) in TIERS)) return {e: `That tier isn't supported.`};
if (['Mono', 'LC'].includes(TIERS[toID(tier)]) && genNum < 7) {
return {e: `${TIERS[toID(tier)]} is not included in [Gen ${genNum}] Battle Factory.`};
}
const t = statsFile[TIERS[toID(tier)]];
if (!(species.id in t)) {
const formatName = Dex.formats.get(`${gen}battlefactory`).name;
return {e: `${species.name} doesn't have any sets in ${TIERS[toID(tier)]} for ${formatName}.`};
}
const setObj = t[species.id];
buf += `<span style="color:#999999;">Sets for ${species.name} in${genNum === 8 ? `` : ` ${GEN_NAMES[gen]}`} ${TIERS[toID(tier)]}:</span><br />`;
for (const [i, set] of setObj.sets.entries()) {
buf += `<details><summary>Set ${i + 1}</summary>`;
buf += `<ul style="list-style-type:none;">`;
buf += `<li>${set.species}${set.gender ? ` (${set.gender})` : ``} @ ${Array.isArray(set.item) ? set.item.map(formatItem).join(" / ") : formatItem(set.item)}</li>`;
buf += `<li>Ability: ${Array.isArray(set.ability) ? set.ability.map(formatAbility).join(" / ") : formatAbility(set.ability)}</li>`;
if (TIERS[toID(tier)] === "LC" && !set.level) buf += `<li>Level: 5</li>`;
if (set.level && set.level < 100) buf += `<li>Level: ${set.level}</li>`;
if (set.shiny) buf += `<li>Shiny: Yes</li>`;
if (set.happiness) buf += `<li>Happiness: ${set.happiness}</li>`;
if (set.evs) {
buf += `<li>EVs: `;
const evs: string[] = [];
let ev: string;
for (ev in set.evs) {
if (set.evs[ev] === 0) continue;
evs.push(`${set.evs[ev]} ${STAT_NAMES[ev]}`);
}
buf += `${evs.join(" / ")}</li>`;
}
buf += `<li>${Array.isArray(set.nature) ? set.nature.map(formatNature).join(" / ") : formatNature(set.nature)} Nature</li>`;
if (set.ivs) {
buf += `<li>IVs: `;
const ivs: string[] = [];
let iv: string;
for (iv in set.ivs) {
if (set.ivs[iv] === 31) continue;
ivs.push(`${set.ivs[iv]} ${STAT_NAMES[iv]}`);
}
buf += `${ivs.join(" / ")}</li>`;
}
for (const moveid of set.moves) {
buf += `<li>- ${Array.isArray(moveid) ? moveid.map(formatMove).join(" / ") : formatMove(moveid)}</li>`;
}
buf += `</ul></details>`;
}
} else {
const format = Dex.formats.get(`${gen}bssfactory`);
if (!(species.id in statsFile)) return {e: `${species.name} doesn't have any sets in ${format.name}.`};
const setObj = statsFile[species.id];
buf += `<span style="color:#999999;">Sets for ${species.name} in ${format.name}:</span><br />`;
for (const [i, set] of setObj.sets.entries()) {
buf += `<details><summary>Set ${i + 1}</summary>`;
buf += `<ul style="list-style-type:none;padding-left:0;">`;
buf += `<li>${set.species}${set.gender ? ` (${set.gender})` : ``} @ ${Array.isArray(set.item) ? set.item.map(formatItem).join(" / ") : formatItem(set.item)}</li>`;
buf += `<li>Ability: ${Array.isArray(set.ability) ? set.ability.map(formatAbility).join(" / ") : formatAbility(set.ability)}</li>`;
if (!set.level) buf += `<li>Level: 50</li>`;
if (set.level && set.level < 50) buf += `<li>Level: ${set.level}</li>`;
if (set.shiny) buf += `<li>Shiny: Yes</li>`;
if (set.happiness) buf += `<li>Happiness: ${set.happiness}</li>`;
if (set.evs) {
buf += `<li>EVs: `;
const evs: string[] = [];
let ev: string;
for (ev in set.evs) {
if (set.evs[ev] === 0) continue;
evs.push(`${set.evs[ev]} ${STAT_NAMES[ev]}`);
}
buf += `${evs.join(" / ")}</li>`;
}
buf += `<li>${Array.isArray(set.nature) ? set.nature.map(formatNature).join(" / ") : formatNature(set.nature)} Nature</li>`;
if (set.ivs) {
buf += `<li>IVs: `;
const ivs: string[] = [];
let iv: string;
for (iv in set.ivs) {
if (set.ivs[iv] === 31) continue;
ivs.push(`${set.ivs[iv]} ${STAT_NAMES[iv]}`);
}
buf += `${ivs.join(" / ")}</li>`;
}
for (const moveid of set.moves) {
buf += `<li>- ${Array.isArray(moveid) ? moveid.map(formatMove).join(" / ") : formatMove(moveid)}</li>`;
}
buf += `</ul></details>`;
}
}
return buf;
}
function CAP1v1Sets(species: string | Species) {
species = Dex.species.get(species);
const statsFile = JSON.parse(
FS(`data/cap-1v1-sets.json`).readIfExistsSync() ||
"{}"
);
if (!Object.keys(statsFile).length) return null;
if (species.isNonstandard !== "CAP") {
return {
e: `[Gen 8] CAP 1v1 only allows Pok\u00e9mon created by the Create-A-Pok\u00e9mon Project.`,
parse: `/cap`,
};
}
if (species.isNonstandard === "CAP" && !(species.name in statsFile)) {
return {e: `${species.name} doesn't have any sets in [Gen 8] CAP 1v1.`};
}
let buf = `<span style="color:#999999;">Sets for ${species.name} in [Gen 8] CAP 1v1:</span><br />`;
for (const [i, set] of statsFile[species.name].entries()) {
buf += `<details><summary>Set ${i + 1}</summary>`;
buf += `<ul style="list-style-type:none;">`;
buf += `<li>${set.species || species.name}${set.gender ? ` (${set.gender})` : ``} @ ${Array.isArray(set.item) ? set.item.map(formatItem).join(" / ") : formatItem(set.item)}</li>`;
buf += `<li>Ability: ${Array.isArray(set.ability) ? set.ability.map(formatAbility).join(" / ") : formatAbility(set.ability)}</li>`;
if (set.level && set.level < 100) buf += `<li>Level: ${set.level}</li>`;
if (set.shiny) buf += `<li>Shiny: Yes</li>`;
if (set.happiness) buf += `<li>Happiness: ${set.happiness}</li>`;
if (set.evs) {
buf += `<li>EVs: `;
const evs: string[] = [];
let ev: string;
for (ev in set.evs) {
if (set.evs[ev] === 0) continue;
evs.push(`${set.evs[ev]} ${STAT_NAMES[ev]}`);
}
buf += `${evs.join(" / ")}</li>`;
}
buf += `<li>${Array.isArray(set.nature) ? set.nature.map(formatNature).join(" / ") : formatNature(set.nature)} Nature</li>`;
if (set.ivs) {
buf += `<li>IVs: `;
const ivs: string[] = [];
let iv: string;
for (iv in set.ivs) {
if (set.ivs[iv] === 31) continue;
ivs.push(`${set.ivs[iv]} ${STAT_NAMES[iv]}`);
}
buf += `${ivs.join(" / ")}</li>`;
}
for (const moveid of set.moves) {
buf += `<li>- ${Array.isArray(moveid) ? moveid.map(formatMove).join(" / ") : formatMove(moveid)}</li>`;
}
buf += `</ul></details>`;
}
return buf;
}
function generateSSBSet(set: SSBSet, dex: ModdedDex, baseDex: ModdedDex) {
if (set.skip) {
const baseSet = toID(Object.values(ssbSets[set.skip]).join());
const skipSet = toID(Object.values(set).join()).slice(0, -toID(set.skip).length);
if (baseSet === skipSet) return ``;
}
let buf = ``;
buf += `<details><summary>Set</summary>`;
buf += `<ul style="list-style-type:none;"><li>${set.species}${set.gender !== '' ? ` (${set.gender})` : ``} @ ${Array.isArray(set.item) ? set.item.map(x => dex.items.get(x).name).join(' / ') : dex.items.get(set.item).name}</li>`;
buf += `<li>Ability: ${Array.isArray(set.ability) ? set.ability.map(x => dex.abilities.get(x).name).join(' / ') : dex.abilities.get(set.ability).name}</li>`;
if (set.shiny) buf += `<li>Shiny: ${typeof set.shiny === 'number' ? `Sometimes` : `Yes`}</li>`;
if (set.evs) {
const evs: string[] = [];
let ev: StatID;
for (ev in set.evs) {
if (set.evs[ev] === 0) continue;
evs.push(`${set.evs[ev]} ${STAT_NAMES[ev]}`);
}
buf += `<li>EVs: ${evs.join(" / ")}</li>`;
}
if (set.nature) {
buf += `<li>${Array.isArray(set.nature) ? set.nature.join(" / ") : formatNature(set.nature)} Nature</li>`;
}
if (set.ivs) {
const ivs: string[] = [];
let iv: StatID;
for (iv in set.ivs) {
if (set.ivs[iv] === 31) continue;
ivs.push(`${set.ivs[iv]} ${STAT_NAMES[iv]}`);
}
buf += `<li>IVs: ${ivs.join(" / ")}</li>`;
}
for (const moveid of set.moves) {
buf += `<li>- ${Array.isArray(moveid) ? moveid.map(x => dex.moves.get(x).name).join(" / ") : dex.moves.get(moveid).name}</li>`;
}
const italicize = !baseDex.moves.get(set.signatureMove).exists;
buf += `<li>- ${italicize ? `<i>` : ``}${dex.moves.get(set.signatureMove).name}${italicize ? `</i>` : ``}</li>`;
buf += `</ul>`;
buf += `</details>`;
return buf;
}
function generateSSBMoveInfo(sigMove: Move, dex: ModdedDex) {
let buf = ``;
if (sigMove.shortDesc || sigMove.desc) {
buf += `<hr />`;
buf += Chat.getDataMoveHTML(sigMove);
const details: {[k: string]: string} = {
Priority: String(sigMove.priority),
Gen: String(sigMove.gen) || 'CAP',
};
if (sigMove.isNonstandard === "Past" && dex.gen >= 8) details["✗ Past Gens Only"] = "";
if (sigMove.secondary || sigMove.secondaries) details["✓ Secondary effect"] = "";
if (sigMove.flags['contact']) details["✓ Contact"] = "";
if (sigMove.flags['sound']) details["✓ Sound"] = "";
if (sigMove.flags['bullet']) details["✓ Bullet"] = "";
if (sigMove.flags['pulse']) details["✓ Pulse"] = "";
if (!sigMove.flags['protect'] && !/(ally|self)/i.test(sigMove.target)) details["✓ Bypasses Protect"] = "";
if (sigMove.flags['bypasssub']) details["✓ Bypasses Substitutes"] = "";
if (sigMove.flags['defrost']) details["✓ Thaws user"] = "";
if (sigMove.flags['bite']) details["✓ Bite"] = "";
if (sigMove.flags['punch']) details["✓ Punch"] = "";
if (sigMove.flags['powder']) details["✓ Powder"] = "";
if (sigMove.flags['reflectable']) details["✓ Bounceable"] = "";
if (sigMove.flags['charge']) details["✓ Two-turn move"] = "";
if (sigMove.flags['recharge']) details["✓ Has recharge turn"] = "";
if (sigMove.flags['gravity']) details["✗ Suppressed by Gravity"] = "";
if (sigMove.flags['dance']) details["✓ Dance move"] = "";
if (sigMove.zMove?.basePower) {
details["Z-Power"] = String(sigMove.zMove.basePower);
} else if (sigMove.zMove?.effect) {
const zEffects: {[k: string]: string} = {
clearnegativeboost: "Restores negative stat stages to 0",
crit2: "Crit ratio +2",
heal: "Restores HP 100%",
curse: "Restores HP 100% if user is Ghost type, otherwise Attack +1",
redirect: "Redirects opposing attacks to user",
healreplacement: "Restores replacement's HP 100%",
};
details["Z-Effect"] = zEffects[sigMove.zMove.effect];
} else if (sigMove.zMove?.boost) {
details["Z-Effect"] = "";
const boost = sigMove.zMove.boost;
for (const h in boost) {
details["Z-Effect"] += ` ${Dex.stats.mediumNames[h as 'atk']} +${boost[h as 'atk']}`;
}
} else if (sigMove.isZ && typeof sigMove.isZ === 'string') {
details["✓ Z-Move"] = "";
const zCrystal = dex.items.get(sigMove.isZ);
details["Z-Crystal"] = zCrystal.name;
if (zCrystal.itemUser) {
details["User"] = zCrystal.itemUser.join(", ");
details["Required Move"] = dex.items.get(sigMove.isZ).zMoveFrom!;
}
} else {
details["Z-Effect"] = "None";
}
const targetTypes: {[k: string]: string} = {
normal: "One Adjacent Pok\u00e9mon",
self: "User",
adjacentAlly: "One Ally",
adjacentAllyOrSelf: "User or Ally",
adjacentFoe: "One Adjacent Opposing Pok\u00e9mon",
allAdjacentFoes: "All Adjacent Opponents",
foeSide: "Opposing Side",
allySide: "User's Side",
allyTeam: "User's Side",
allAdjacent: "All Adjacent Pok\u00e9mon",
any: "Any Pok\u00e9mon",
all: "All Pok\u00e9mon",
scripted: "Chosen Automatically",
randomNormal: "Random Adjacent Opposing Pok\u00e9mon",
allies: "User and Allies",
};
details["Target"] = targetTypes[sigMove.target] || "Unknown";
if (sigMove.isNonstandard === 'Unobtainable') {
details[`Unobtainable in Gen ${dex.gen}`] = "";
}
buf += `<font size="1">${Object.entries(details).map(([detail, value]) => (
value === '' ? detail : `<font color="#686868">${detail}:</font> ${value}`
)).join(" |  ")}</font>`;
if (sigMove.desc && sigMove.desc !== sigMove.shortDesc) {
buf += `<details><summary><strong>In-Depth Description</strong></summary>${sigMove.desc}</details>`;
}
}
return buf;
}
function generateSSBItemInfo(set: SSBSet, dex: ModdedDex, baseDex: ModdedDex) {
let buf = ``;
if (!Array.isArray(set.item)) {
const baseItem = baseDex.items.get(set.item);
const sigItem = dex.items.get(set.item);
if (!baseItem.exists || (baseItem.desc || baseItem.shortDesc) !== (sigItem.desc || sigItem.shortDesc)) {
buf += `<hr />`;
buf += Chat.getDataItemHTML(sigItem);
const details: {[k: string]: string} = {
Gen: String(sigItem.gen),
};
if (dex.gen >= 4) {
if (sigItem.fling) {
details["Fling Base Power"] = String(sigItem.fling.basePower);
if (sigItem.fling.status) details["Fling Effect"] = sigItem.fling.status;
if (sigItem.fling.volatileStatus) details["Fling Effect"] = sigItem.fling.volatileStatus;
if (sigItem.isBerry) details["Fling Effect"] = "Activates the Berry's effect on the target.";
if (sigItem.id === 'whiteherb') details["Fling Effect"] = "Restores the target's negative stat stages to 0.";
if (sigItem.id === 'mentalherb') {
const flingEffect = "Removes the effects of Attract, Disable, Encore, Heal Block, Taunt, and Torment from the target.";
details["Fling Effect"] = flingEffect;
}
} else {
details["Fling"] = "This item cannot be used with Fling.";
}
}
if (sigItem.naturalGift && dex.gen >= 3) {
details["Natural Gift Type"] = sigItem.naturalGift.type;
details["Natural Gift Base Power"] = String(sigItem.naturalGift.basePower);
}
if (sigItem.isNonstandard && sigItem.isNonstandard !== "Custom") {
details[`Unobtainable in Gen ${dex.gen}`] = "";
}
buf += `<font size="1">${Object.entries(details).map(([detail, value]) => (
value === '' ? detail : `<font color="#686868">${detail}:</font> ${value}`
)).join(" |  ")}</font>`;
}
}
return buf;
}
function generateSSBAbilityInfo(set: SSBSet, dex: ModdedDex, baseDex: ModdedDex) {
let buf = ``;
if (!Array.isArray(set.ability) && !baseDex.abilities.get(set.ability).exists) {
const sigAbil = Dex.deepClone(dex.abilities.get(set.ability));
if (!sigAbil.desc && !sigAbil.shortDesc) {
sigAbil.desc = `This ability doesn't have a description. Try contacting the SSB dev team.`;
}
buf += `<hr />`;
buf += Chat.getDataAbilityHTML(sigAbil);
const details: {[k: string]: string} = {
Gen: String(sigAbil.gen) || 'CAP',
};
buf += `<font size="1">${Object.entries(details).map(([detail, value]) => (
value === '' ? detail : `<font color="#686868">${detail}:</font> ${value}`
)).join(" |  ")}</font>`;
if (sigAbil.desc && sigAbil.shortDesc && sigAbil.desc !== sigAbil.shortDesc) {
buf += `<details><summary><strong>In-Depth Description</strong></summary>${sigAbil.desc}</details>`;
}
}
return buf;
}
function generateSSBPokemonInfo(species: string, dex: ModdedDex, baseDex: ModdedDex) {
let buf = ``;
const origSpecies = baseDex.species.get(species);
const newSpecies = dex.species.get(species);
if (
newSpecies.types.join('/') !== origSpecies.types.join('/') ||
Object.values(newSpecies.abilities).join('/') !== Object.values(origSpecies.abilities).join('/') ||
Object.values(newSpecies.baseStats).join('/') !== Object.values(origSpecies.baseStats).join('/')
) {
buf += `<hr />`;
buf += Chat.getDataPokemonHTML(newSpecies, dex.gen, 'SSB');
let weighthit = 20;
if (newSpecies.weighthg >= 2000) {
weighthit = 120;
} else if (newSpecies.weighthg >= 1000) {
weighthit = 100;
} else if (newSpecies.weighthg >= 500) {
weighthit = 80;
} else if (newSpecies.weighthg >= 250) {
weighthit = 60;
} else if (newSpecies.weighthg >= 100) {
weighthit = 40;
}
const details: {[k: string]: string} = {
"Dex#": String(newSpecies.num),
Gen: String(newSpecies.gen) || 'CAP',
Height: `${newSpecies.heightm} m`,
};
details["Weight"] = `${newSpecies.weighthg / 10} kg <em>(${weighthit} BP)</em>`;
if (newSpecies.color && dex.gen >= 5) details["Dex Colour"] = newSpecies.color;
if (newSpecies.eggGroups && dex.gen >= 2) details["Egg Group(s)"] = newSpecies.eggGroups.join(", ");
const evos: string[] = [];
for (const evoName of newSpecies.evos) {
const evo = dex.species.get(evoName);
if (evo.gen <= dex.gen) {
const condition = evo.evoCondition ? ` ${evo.evoCondition}` : ``;
switch (evo.evoType) {
case 'levelExtra':
evos.push(`${evo.name} (level-up${condition})`);
break;
case 'levelFriendship':
evos.push(`${evo.name} (level-up with high Friendship${condition})`);
break;
case 'levelHold':
evos.push(`${evo.name} (level-up holding ${evo.evoItem}${condition})`);
break;
case 'useItem':
evos.push(`${evo.name} (${evo.evoItem})`);
break;
case 'levelMove':
evos.push(`${evo.name} (level-up with ${evo.evoMove}${condition})`);
break;
case 'other':
evos.push(`${evo.name} (${evo.evoCondition})`);
break;
case 'trade':
evos.push(`${evo.name} (trade${evo.evoItem ? ` holding ${evo.evoItem}` : condition})`);
break;
default:
evos.push(`${evo.name} (${evo.evoLevel}${condition})`);
}
}
}
if (!evos.length) {
details[`<font color="#686868">Does Not Evolve</font>`] = "";
} else {
details["Evolution"] = evos.join(", ");
}
buf += `<font size="1">${Object.entries(details).map(([detail, value]) => (
value === '' ? detail : `<font color="#686868">${detail}:</font> ${value}`
)).join(" |  ")}</font>`;
}
return buf;
}
function generateSSBInnateInfo(name: string, dex: ModdedDex, baseDex: ModdedDex) {
let buf = ``;
// Special casing for users whose usernames are already existing, i.e. Perish Song
let effect = dex.conditions.get(name + 'user');
let longDesc = ``;
const baseAbility = Dex.deepClone(baseDex.abilities.get('noability'));
// @ts-ignore hack to record the name of the innate abilities without using name
if (effect.exists && effect.innateName && (effect.desc || effect.shortDesc)) {
// @ts-ignore hack
baseAbility.name = effect.innateName;
if (effect.desc) baseAbility.desc = effect.desc;
if (effect.shortDesc) baseAbility.shortDesc = effect.shortDesc;
buf += `<hr />Innate Ability:<br />${Chat.getDataAbilityHTML(baseAbility)}`;
if (effect.desc && effect.shortDesc && effect.desc !== effect.shortDesc) {
longDesc = effect.desc;
}
} else {
effect = dex.conditions.get(name);
// @ts-ignore hack
if (effect.exists && effect.innateName && (effect.desc || effect.shortDesc)) {
// @ts-ignore hack
baseAbility.name = effect.innateName;
if (effect.desc) baseAbility.desc = effect.desc;
if (effect.shortDesc) baseAbility.shortDesc = effect.shortDesc;
buf += `<hr />Innate Ability:<br />${Chat.getDataAbilityHTML(baseAbility)}`;
if (effect.desc && effect.shortDesc && effect.desc !== effect.shortDesc) {
longDesc = effect.desc;
}
}
}
if (buf) {
const details: {[k: string]: string} = {Gen: '8'};
buf += `<font size="1">${Object.entries(details).map(([detail, value]) => (
value === '' ? detail : `<font color="#686868">${detail}:</font> ${value}`
)).join(" |  ")}</font>`;
}
if (longDesc) {
buf += `<details><summary><strong>In-Depth Description</strong></summary>${longDesc}</details>`;
}
return buf;
}
function SSBSets(target: string) {
const baseDex = Dex;
const dex = Dex.forFormat('gen8superstaffbros4');
if (!Object.keys(ssbSets).map(toID).includes(toID(target))) {
return {e: `Error: ${target.trim()} doesn't have a [Gen 8] Super Staff Bros 4 set.`};
}
let displayName = '';
const names = [];
for (const member in ssbSets) {
if (toID(member).startsWith(toID(target))) names.push(member);
if (toID(member) === toID(target)) displayName = member;
}
let buf = '';
for (const name of names) {
if (buf) buf += `<hr>`;
const set = ssbSets[name];
const mutatedSpecies = dex.species.get(set.species);
if (!set.skip) {
buf += Utils.html`<h1><psicon pokemon="${mutatedSpecies.id}">${displayName === 'yuki' ? name : displayName}</h1>`;
} else {
buf += `<details><summary><psicon pokemon="${set.species}"><strong>${name.split('-').slice(1).join('-') + ' forme'}</strong></summary>`;
}
buf += generateSSBSet(set, dex, baseDex);
const item = dex.items.get(set.item as string);
if (!set.skip || set.signatureMove !== ssbSets[set.skip].signatureMove) {
const sigMove = baseDex.moves.get(set.signatureMove).exists && !Array.isArray(set.item) &&
typeof item.zMove === 'string' ?
dex.moves.get(item.zMove) : dex.moves.get(set.signatureMove);
buf += generateSSBMoveInfo(sigMove, dex);
if (sigMove.id === 'blackbird') buf += generateSSBMoveInfo(dex.moves.get('gaelstrom'), dex);
}
buf += generateSSBItemInfo(set, dex, baseDex);
buf += generateSSBAbilityInfo(set, dex, baseDex);
buf += generateSSBInnateInfo(name, dex, baseDex);
buf += generateSSBPokemonInfo(set.species, dex, baseDex);
if (!Array.isArray(set.item) && item.megaStone) {
buf += generateSSBPokemonInfo(item.megaStone, dex, baseDex);
// Psynergy, Struchni, and Raj.shoot have itemless Mega Evolutions
} else if (['Aggron', 'Rayquaza'].includes(set.species)) {
buf += generateSSBPokemonInfo(`${set.species}-Mega`, dex, baseDex);
} else if (set.species === 'Charizard') {
buf += generateSSBPokemonInfo('Charizard-Mega-X', dex, baseDex);
}
if (set.skip) buf += `</details>`;
}
return buf;
}
export const commands: Chat.ChatCommands = {
randbats: 'randombattles',
randombattles(target, room, user) {
if (!this.runBroadcast()) return;
if (room?.battle?.format.includes('nodmax')) return this.parse(`/randombattlenodmax ${target}`);
if (room?.battle?.format.includes('doubles')) return this.parse(`/randomdoublesbattle ${target}`);
const args = target.split(',');
if (!args[0]) return this.parse(`/help randombattles`);
const {dex} = this.splitFormat(target, true);
const isLetsGo = (dex.currentMod === 'gen7letsgo');
const species = dex.species.get(args[0]);
if (!species.exists) {
return this.errorReply(`Error: Pok\u00e9mon '${args[0].trim()}' does not exist.`);
}
const extraFormatModifier = isLetsGo ? 'letsgo' : (dex.currentMod === 'gen8bdsp' ? 'bdsp' : '');
let formatName = dex.formats.get(`gen${dex.gen}${extraFormatModifier}randombattle`).name;
const movesets = [];
if (dex.gen === 1) {
const rbyMoves = getRBYMoves(species);
if (!rbyMoves) {
return this.errorReply(`Error: ${species.name} has no Random Battle data in ${GEN_NAMES[toID(args[1])]}`);
}
movesets.push(`<span style="color:#999999;">Moves for ${species.name} in ${formatName}:</span><br />${rbyMoves}`);
} else if (isLetsGo) {
formatName = `[Gen 7 Let's Go] Random Battle`;
const lgpeMoves = getLetsGoMoves(species);
if (!lgpeMoves) {
return this.errorReply(`Error: ${species.name} has no Random Battle data in [Gen 7 Let's Go]`);
}
movesets.push(`<span style="color:#999999;">Moves for ${species.name} in ${formatName}:</span><br />${lgpeMoves}`);
} else {
const setsToCheck = [species];
if (dex.gen > 7) setsToCheck.push(dex.species.get(`${args[0]}gmax`));
if (species.otherFormes) setsToCheck.push(...species.otherFormes.map(pkmn => dex.species.get(pkmn)));
for (const pokemon of setsToCheck) {
if (!pokemon.randomBattleMoves || pokemon.isNonstandard === 'Future') continue;
const randomMoves = pokemon.randomBattleMoves.slice();
const m = randomMoves.sort().map(formatMove);
movesets.push(
`<details${!movesets.length ? ' open' : ''}>` +
`<summary><span style="color:#999999;">Moves for ${pokemon.name} in ${formatName}:<span style="color:#999999;"></summary>` +
`${m.join(`, `)}</details>`
);
}
}
if (!movesets.length) {
return this.errorReply(`Error: ${species.name} has no Random Battle data in ${formatName}`);
}
this.sendReplyBox(movesets.join('<hr />'));
},
randombattleshelp: [
`/randombattles OR /randbats [pokemon], [gen] - Displays a Pok\u00e9mon's Random Battle Moves. Defaults to Gen 8. If used in a battle, defaults to the gen of that battle.`,
],
randdubs: 'randomdoublesbattle',
randomdoublesbattle(target, room, user) {
if (!this.runBroadcast()) return;
const args = target.split(',');
if (!args[0]) return this.parse(`/help randomdoublesbattle`);
const {dex} = this.splitFormat(target, true);
if (dex.gen < 4) return this.parse(`/help randomdoublesbattle`);
const species = dex.species.get(args[0]);
const formatName = dex.gen > 6 ? dex.formats.get(`gen${dex.gen}randomdoublesbattle`).name : dex.gen === 6 ?
'[Gen 6] Random Doubles Battle' : dex.gen === 5 ?
'[Gen 5] Random Doubles Battle' : '[Gen 4] Random Doubles Battle';
if (!species.exists) {
return this.errorReply(`Error: Pok\u00e9mon '${args[0].trim()}' does not exist.`);
}
const setsToCheck = [species];
if (dex.gen > 7) setsToCheck.push(dex.species.get(`${args[0]}gmax`));
if (species.otherFormes) setsToCheck.push(...species.otherFormes.map(pkmn => dex.species.get(pkmn)));
const movesets = [];
for (const pokemon of setsToCheck) {
if (!pokemon.randomDoubleBattleMoves) continue;
const moves: string[] = [...pokemon.randomDoubleBattleMoves];
const m = moves.sort().map(formatMove);
movesets.push(`<span style="color:#999999;">Doubles moves for ${pokemon.name} in ${formatName}:</span><br />${m.join(`, `)}`);
}
this.sendReplyBox(movesets.join('<hr />'));
},
randomdoublesbattlehelp: [
`/randomdoublesbattle OR /randdubs [pokemon], [gen] - Displays a Pok\u00e9mon's Random Doubles Battle Moves. Supports Gens 4-8. Defaults to Gen 8. If used in a battle, defaults to that gen.`,
],
randsnodmax: 'randombattlenodmax',
randombattlenodmax(target, room, user) {
if (!this.runBroadcast()) return;
if (!target) return this.parse(`/help randombattlenodmax`);
const dex = Dex.forFormat('gen8randombattlenodmax');
let species = dex.species.get(target);
if (!species.exists) {
throw new Chat.ErrorMessage(`Error: Pok\u00e9mon '${target.trim()}' does not exist.`);
}
let randomMoves = species.randomBattleNoDynamaxMoves || species.randomBattleMoves;
if (!randomMoves) {
const gmaxSpecies = dex.species.get(`${target}gmax`);
if (!gmaxSpecies.exists || !gmaxSpecies.randomBattleMoves) {
return this.errorReply(`Error: No move data found for ${species.name} in [Gen 8] Random Battle (No Dmax).`);
}
species = gmaxSpecies;
randomMoves = gmaxSpecies.randomBattleNoDynamaxMoves || gmaxSpecies.randomBattleMoves;
}
const m = [...randomMoves].sort().map(formatMove);
this.sendReplyBox(`<span style="color:#999999;">Moves for ${species.name} in [Gen 8] Random Battle (No Dmax):</span><br />${m.join(`, `)}`);
},
randombattlenodmaxhelp: [
`/randombattlenodmax OR /randsnodmax [pokemon] - Displays a Pok\u00e9mon's Random Battle (No Dmax) moves.`,
],
bssfactory: 'battlefactory',
battlefactory(target, room, user, connection, cmd) {
if (!this.runBroadcast()) return;
const isBSS = cmd === 'bssfactory';
if (isBSS) {
const args = target.split(',');
if (!args[0]) return this.parse(`/help battlefactory`);
const species = Dex.species.get(args[0]);
if (!species.exists) {
return this.errorReply(`Error: Pok\u00e9mon '${args[0].trim()}' not found.`);
}
let mod = 'gen8';
// There is only [Gen 7] BSS Factory right now
if (args[1] && toID(args[1]) in Dex.dexes && Dex.dexes[toID(args[1])].gen === 7) mod = toID(args[1]);
const bssSets = battleFactorySets(species, null, mod, true);
if (!bssSets) return this.parse(`/help battlefactory`);
if (typeof bssSets !== 'string') {
return this.errorReply(`Error: ${bssSets.e}`);
}
return this.sendReplyBox(bssSets);
} else {
const args = target.split(',');
if (!args[0]) return this.parse(`/help battlefactory`);
const species = Dex.species.get(args[0]);
if (!species.exists) {
return this.errorReply(`Error: Pok\u00e9mon '${args[0].trim()}' not found.`);
}
let tier = '';
if (args[1] && toID(args[1]) in TIERS) {
tier = TIERS[toID(args[1])];
} else {
tier = 'ou';
}
const mod = args[2] || 'gen7';
let bfSets;
if (species.name === 'Necrozma-Ultra') {
bfSets = battleFactorySets(Dex.species.get('necrozma-dawnwings'), tier, mod);
if (typeof bfSets === 'string') {
bfSets += battleFactorySets(Dex.species.get('necrozma-duskmane'), tier, mod);
}
} else if (species.name === 'Zygarde-Complete') {
bfSets = battleFactorySets(Dex.species.get('zygarde'), tier, mod);
if (typeof bfSets === 'string') {
bfSets += battleFactorySets(Dex.species.get('zygarde-10'), tier, mod);
}
} else {
bfSets = battleFactorySets(species, tier, mod);
}
if (!bfSets) return this.parse(`/help battlefactory`);
if (typeof bfSets !== 'string') {
return this.errorReply(`Error: ${bfSets.e}`);
}
return this.sendReplyBox(bfSets);
}
},
battlefactoryhelp: [
`/battlefactory [pokemon], [tier], [gen] - Displays a Pok\u00e9mon's Battle Factory sets. Supports Gens 6-7. Defaults to Gen 7. If no tier is provided, defaults to OU.`,
`- Supported tiers: OU, Ubers, UU, RU, NU, PU, Monotype (Gen 7 only), LC (Gen 7 only)`,
`/bssfactory [pokemon], [gen] - Displays a Pok\u00e9mon's BSS Factory sets. Supports Gen 7. Defaults to Gen 7.`,
],
cap1v1(target, room, user) {
if (!this.runBroadcast()) return;
if (!target) return this.parse(`/help cap1v1`);
const species = Dex.species.get(target);
if (!species.exists) return this.errorReply(`Error: Pok\u00e9mon '${target.trim()}' not found.`);
const cap1v1Set = CAP1v1Sets(species);
if (!cap1v1Set) return this.parse(`/help cap1v1`);
if (typeof cap1v1Set !== 'string') {
this.errorReply(`Error: ${cap1v1Set.e}`);
if (cap1v1Set.parse) this.parse(cap1v1Set.parse);
return;
}
return this.sendReplyBox(cap1v1Set);
},
cap1v1help: [
`/cap1v1 [pokemon] - Displays a Pok\u00e9mon's CAP 1v1 sets.`,
],
ssb(target, room, user) {
if (!this.runBroadcast()) return;
if (!target) return this.parse(`/help ssb`);
const set = SSBSets(target);
if (typeof set !== 'string') {
throw new Chat.ErrorMessage(set.e);
}
return this.sendReplyBox(set);
},
ssbhelp: [
`/ssb [staff member] - Displays a staff member's Super Staff Bros. set and custom features.`,
],
setodds: 'randombattlesetprobabilities',
randbatsodds: 'randombattlesetprobabilities',
randbatsprobabilities: 'randombattlesetprobabilities',
randombattlesetprobabilities(target, room, user) {
// Restricted to global staff and randbats room staff
const randbatsRoom = Rooms.get('randombattles');
if (randbatsRoom) {
if (!user.can('lock')) this.checkCan('mute', null, randbatsRoom);
} else {
this.checkCan('lock');
}
if (!target) return this.parse(`/help randombattlesetprobabilities`);
this.runBroadcast();
const args = target.split(',');
if (args.length < 2) return this.parse(`/help randombattlesetprobabilities`);
// Optional format
let format = Dex.formats.get('gen8randombattle');
let formatOrSpecies = args.shift();
const possibleFormat = Dex.formats.get(formatOrSpecies);
if (possibleFormat.exists) {
if (!possibleFormat.team) {
throw new Chat.ErrorMessage(`${possibleFormat.name} does not have randomly-generated teams.`);
}
format = possibleFormat;
formatOrSpecies = args.shift();
}
const dex = Dex.forFormat(format);
// Species
const species = dex.species.get(formatOrSpecies);
if (!species.exists) {
throw new Chat.ErrorMessage(`Species ${species.name} does not exist in the specified format.`);
}
if (!species.randomBattleMoves && !species.randomDoubleBattleMoves && !species.randomBattleNoDynamaxMoves) {
const modMessage = dex.currentMod === 'base' ? format.name : dex.currentMod;
throw new Chat.ErrorMessage(`${species.name} does not have random battle moves in ${modMessage}.`);
}
// Criteria
const criteria: SetCriteria = {
moves: {mustHave: [], mustNotHave: []},
item: {mustNotHave: []},
ability: {mustNotHave: []},
nature: {mustNotHave: []},
};
if (args.length < 1) {
this.errorReply(`You must specify at least one condition.`);
return this.parse(`/help randombattlesetprobabilities`);
}
for (const arg of args) {
let [key, value] = arg.split('=');
key = toID(key);
if (!value || !key) {
this.errorReply(`Invalid condition format: ${arg}`);
return this.parse(`/help randombattlesetprobabilities`);
}
switch (key) {
case 'moves':
for (const rawMove of value.split('&')) {
const move = dex.moves.get(rawMove);
if (!move.exists) {
throw new Chat.ErrorMessage(`"${rawMove}" is not a move in the specified format.`);
}
const isNegation = rawMove.trim().startsWith('!');
if (isNegation) {
criteria.moves.mustNotHave.push(move);
} else {
criteria.moves.mustHave.push(move);
}
}
break;
case 'item':
const item = dex.items.get(value);
if (!item.exists) {
throw new Chat.ErrorMessage(`"${value}" is not an item in the specified format.`);
}
const itemNegation = value.trim().startsWith('!');
if (itemNegation) {
criteria.item.mustNotHave.push(item);
} else {
if (criteria.item.mustHave) {
throw new Chat.ErrorMessage(`Impossible situation: two items (${criteria.item.mustHave.name} and ${item.name}) are required.`);
}
criteria.item.mustHave = item;
}
break;
case 'ability':
const ability = dex.abilities.get(value);
if (!ability.exists) {
throw new Chat.ErrorMessage(`"${value}" is not an ability in the specified format.`);
}
const abilityNegation = value.trim().startsWith('!');
if (abilityNegation) {
criteria.ability.mustNotHave.push(ability);
} else {
if (criteria.ability.mustHave) {
throw new Chat.ErrorMessage(`Impossible situation: two abilities (${criteria.ability.mustHave.name} and ${ability.name}) are required.`);
}
criteria.ability.mustHave = ability;
}
break;
case 'nature':
const nature = dex.natures.get(value);
if (!nature.exists) {
throw new Chat.ErrorMessage(`"${value}" is not a nature in the specified format.`);
}
const natureNegation = value.trim().startsWith('!');
if (natureNegation) {
criteria.nature.mustNotHave.push(nature);
} else {
if (criteria.nature.mustHave) {
throw new Chat.ErrorMessage(`Impossible situation: two natures (${criteria.nature.mustHave.name} and ${nature.name}) are required.`);
}
criteria.nature.mustHave = nature;
}
break;
default:
throw new Chat.ErrorMessage(`Invalid criterion: ${key}`);
}
}
const results = setProbability(species, format, criteria);
const percentage = Math.round((results.matches / results.rounds) * 100);
return this.sendReplyBox(
Utils.html`Generated ${results.rounds} sets for <strong>${species.name}</strong> in ${format.name}:<br />` +
`Approximately <strong>${percentage}%</strong> (${results.matches} sets) ${getHTMLCriteriaDescription(criteria)}.`
);
},
randombattlesetprobabilitieshelp() {
return this.sendReplyBox(
`<code>/randombattlesetprobabilities [optional format], [species], [conditions]</code>: Gives the probability of a set matching the conditions appearing for the given species.<br />` +
`<code>[conditions]</code> is a comma-separated list of conditions of the form <code>[component]=[matching value]</code>, where <code>[component]</code> can be any of the following: ` +
`<ul>` +
`<li><code>moves</code>: matches all generated sets that contain every move specified. <code>[matching value]</code> should be a list of moves separated with <code>&</code>.` +
`<li><code>item</code>: matches all generated sets that have the specified item. <code>[matching value]</code> should be an item name.` +
`<li><code>ability</code>: matches all generated sets with the specified ability. <code>[matching value]</code> should be an ability name.` +
`<li><code>nature</code>: matches all generated sets with the specified nature. <code>[matching value]</code> should be a nature name.` +
`</ul>` +
`The given probability is for a set that matches EVERY provided condition. ` +
`Conditions can be negated by prefixing the <code>[matching value]</code> with <code>!</code>.<br />` +
`Requires: % @ # & (globally or in the Random Battles room)`
);
},
}; | the_stack |
'use strict';
import {
app,
BrowserWindow,
Menu,
MenuItem,
MenuItemConstructorOptions,
shell,
dialog,
globalShortcut,
} from 'electron';
import * as path from 'path';
import { splash } from './splash';
import electronIsDev from 'electron-is-dev';
import { format as formatUrl } from 'url';
import { initIPC } from './api';
import { hideOrQuit } from './platform';
import { installCertAndHelper } from './install';
import extract from 'extract-zip';
import {
WINDOW_DEFAULT_WIDTH,
WINDOW_DEFAULT_HEIGHT,
WINDOW_MIN_WIDTH,
WINDOW_MIN_HEIGHT,
SYSTEM_IS_MACOS,
NEW_ISSUE_PAGE,
GITHUB_PROJECT_PAGE,
IPROXY_HOME_PATH,
IPROXY_FILES_DIR,
APP_VERSION,
IS_BUILD_FOR_PR,
} from './const';
import ua from 'universal-analytics';
import { CoreAPI } from '../renderer/core-api';
import { uuidv4 } from '../renderer/utils';
import windowStateKeeper from 'electron-window-state';
import os from 'os';
import fs from 'fs-extra';
// @ts-ignore
import logoIcon from '../../vendor/files/iconTemplate@2x.png';
import { nanoid } from 'nanoid';
require('@electron/remote/main').initialize();
require('electron-store').initRenderer();
const isDevelopment = process.env.NODE_ENV !== 'production';
// disable GPU for #219
app.disableHardwareAcceleration();
// global reference to mainWindow (necessary to prevent window from being garbage collected)
let mainWindow: BrowserWindow | null;
const version = APP_VERSION;
let appReady = false;
app.commandLine.appendSwitch('--no-proxy-server');
app.commandLine.appendSwitch('disable-site-isolation-trials');
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
app.quit();
} else {
app.on('second-instance', () => {
// 当运行第二个实例时,将会聚焦到myWindow这个窗口
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
}
});
}
function copyFileSync(source: string, target: string) {
let targetFile = target;
//if target is a directory a new file with the same name will be created
if (fs.existsSync(target)) {
if (fs.lstatSync(target).isDirectory()) {
targetFile = path.join(target, path.basename(source));
}
}
fs.writeFileSync(targetFile, fs.readFileSync(source));
}
function copyFolderRecursiveSync(source: string, target: string) {
let files = [];
//check if folder needs to be created or integrated
const targetFolder = path.join(target, path.basename(source));
if (!fs.existsSync(targetFolder)) {
fs.mkdirSync(targetFolder);
}
//copy
if (fs.lstatSync(source).isDirectory()) {
files = fs.readdirSync(source);
files.forEach(function (file) {
const curSource = path.join(source, file);
if (fs.lstatSync(curSource).isDirectory()) {
copyFolderRecursiveSync(curSource, targetFolder);
} else {
copyFileSync(curSource, targetFolder);
}
});
}
}
// @ts-ignore
// will be used in renderer
global.__static = __static;
// @ts-ignore
global.__filesDir = IPROXY_FILES_DIR;
const IPROXY_FILES_IN_ASAR_PATH = electronIsDev
? path.join(__dirname, '../../vendor/files/')
: path.join(__dirname, './files/');
const IPROXY_FILES_ZIP_IN_ASAR_PATH = electronIsDev
? path.join(__dirname, '../../vendor/files.zip')
: path.join(__dirname, './files.zip');
let splashWindow: BrowserWindow | null;
async function initSplashScreen() {
// start a splash window
return new Promise((resolve) => {
const splashContent =
'data:text/html;charset=UTF-8,' +
encodeURIComponent(
splash({
brand: 'Build with ♥',
productName: `iProxy`,
text: `Loading - ${version} ...`,
website: 'https://github.com/xcodebuild/iproxy',
logo: logoIcon,
color: '#1890ff',
}),
);
splashWindow = new BrowserWindow({
width: 600,
height: 400,
frame: false,
backgroundColor: '#1890ff',
// modal: true,
// transparent: true,
autoHideMenuBar: true,
resizable: false,
movable: true,
});
splashWindow.loadURL(splashContent);
splashWindow.webContents.on('did-finish-load', () => {
// @ts-ignore
resolve();
});
splashWindow.show();
});
}
async function initCopyFiles() {
try {
if (!fs.existsSync(IPROXY_FILES_DIR)) {
fs.mkdirpSync(IPROXY_FILES_DIR);
}
const versionFile = path.join(IPROXY_FILES_DIR, 'version');
if (fs.existsSync(versionFile) && fs.readFileSync(versionFile, 'utf-8') === version && !electronIsDev) {
// pass
} else {
console.log('copy files');
fs.removeSync(IPROXY_FILES_DIR);
await extract(IPROXY_FILES_ZIP_IN_ASAR_PATH, {
dir: IPROXY_HOME_PATH,
});
// copyFolderRecursiveSync(IPROXY_FILES_IN_ASAR_PATH, IPROXY_HOME_PATH);
// fs.chmodSync(IPROXY_NODEJS_PATH, '775');
fs.moveSync(
path.join(IPROXY_FILES_DIR, '/node/modules'),
path.join(IPROXY_FILES_DIR, '/node/node_modules'),
);
fs.writeFileSync(versionFile, version, 'utf-8');
}
} catch (e) {
console.error(e);
}
}
let forceQuit = false;
function createMainWindow() {
const mainWindowState = windowStateKeeper({
defaultWidth: WINDOW_DEFAULT_WIDTH,
defaultHeight: WINDOW_DEFAULT_HEIGHT,
});
const window = new BrowserWindow({
height: mainWindowState.height,
width: mainWindowState.width,
minWidth: WINDOW_MIN_WIDTH,
minHeight: WINDOW_MIN_HEIGHT,
webPreferences: {
nodeIntegration: true,
webSecurity: false,
// electron >= 10
contextIsolation: false,
},
// disable frameless in Windows
frame: SYSTEM_IS_MACOS ? false : true,
x: mainWindowState.x,
y: mainWindowState.y,
show: false,
});
window.hide();
mainWindowState.manage(window);
require('@electron/remote/main').enable(window.webContents);
if (isDevelopment) {
window.webContents.openDevTools();
}
const filter = {
urls: ['*://127.0.0.1:*/*'],
};
if (isDevelopment) {
window.loadURL(`http://localhost:2333`);
} else {
window.loadURL(
formatUrl({
pathname: path.join(__dirname, './index.html'),
protocol: 'file',
slashes: true,
}),
);
}
// @ts-ignore
global.WHISTLE_USERNAME = nanoid(8);
// @ts-ignore
global.WHISTLE_PASSWORD = nanoid(8);
window.webContents.session.webRequest.onBeforeSendHeaders(filter, (details, callback) => {
// @ts-ignore
const base64encodedData = new Buffer(global.WHISTLE_USERNAME + ':' + global.WHISTLE_PASSWORD).toString(
'base64',
);
callback({
requestHeaders: {
...details.requestHeaders,
Authorization: 'Basic ' + base64encodedData,
},
cancel: false,
});
});
window.on('close', (event) => {
if (!forceQuit) {
hideOrQuit();
event?.preventDefault();
}
});
window.webContents.on('new-window', function (event, url) {
event.preventDefault();
new BrowserWindow({
width: 1300,
height: 800,
}).loadURL(url);
});
window.webContents.on('did-finish-load', () => {
splashWindow?.destroy();
splashWindow = null;
window.show();
});
window.webContents.on('devtools-opened', () => {
window.focus();
setImmediate(() => {
window.focus();
});
});
const REFRESH_KEYS = ['CommandOrControl+R', 'CommandOrControl+Shift+R', 'F5'];
window.on('focus', () => {
REFRESH_KEYS.forEach((key) => {
globalShortcut.register(key, () => {
// pass
});
});
});
window.on('blur', () => {
REFRESH_KEYS.forEach((key) => {
globalShortcut.unregister(key);
});
});
return window;
}
function setApplicationMenu() {
const defaultMenu = Menu.getApplicationMenu();
const applicationMenu = new Menu();
(defaultMenu?.items ?? [])
.filter((menu) => {
// remove the original help menu
return menu.role !== 'help';
})
.forEach((menu) => {
// @ts-ignore
if (menu.role === 'viewmenu') {
const subMenu = new Menu();
(menu.submenu?.items ?? []).forEach((item) => {
// @ts-ignore
if (item.role !== 'reload' && item.role !== 'forcereload') {
subMenu.append(item);
}
});
applicationMenu.append(
new MenuItem({
type: menu.type,
label: menu.label,
submenu: subMenu,
}),
);
} else {
applicationMenu.append(menu);
}
});
// append custom help menu
const helpSubMenu = new Menu();
const helpSubMenuConfig: MenuItemConstructorOptions[] = [
{
label: 'Project Homepage',
click: function () {
shell.openExternal(GITHUB_PROJECT_PAGE);
},
},
{
label: 'Report Issue',
click: function () {
shell.openExternal(NEW_ISSUE_PAGE);
},
},
{
label: 'Install Certificate & Helper',
click: async () => {
await installCertAndHelper();
dialog.showMessageBox({
type: 'info',
message: 'Install Done, iProxy will restart',
});
app.relaunch();
app.quit();
},
},
];
helpSubMenuConfig.forEach((option) => {
helpSubMenu.append(new MenuItem(option));
});
applicationMenu.append(
new MenuItem({
label: 'Help',
type: 'submenu',
submenu: helpSubMenu,
}),
);
Menu.setApplicationMenu(applicationMenu);
}
app.on('before-quit', function () {
forceQuit = true;
});
app.on('will-quit', () => {
// 注销所有快捷键
globalShortcut.unregisterAll();
});
// quit application when all windows are closed
app.on('window-all-closed', () => {
// on macOS it is common for applications to stay open until the user explicitly quits
if (SYSTEM_IS_MACOS) {
app.quit();
}
});
app.on('activate', () => {
if (!appReady) {
// fix `Cannot create BrowserWindow before app is ready`
return;
}
// on macOS it is common to re-create a window even after all windows have been closed
if (!mainWindow) {
mainWindow = createMainWindow();
}
mainWindow.show();
});
// create main BrowserWindow when electron is ready
app.on('ready', async () => {
appReady = true;
await initSplashScreen();
await initCopyFiles();
mainWindow = createMainWindow();
setApplicationMenu();
initIPC(mainWindow);
}); | the_stack |
import { Component } from '@angular/core';
import * as json from './timelinedemo-dataproperties.json';
@Component({
selector: 'app-timeline',
templateUrl: './timelinedemo.component.html',
styleUrls: ['./timelinedemo.component.scss'],
})
export class TimelineDemoComponent {
public dataTableProperties;
public dataEvents;
public timeout;
public dataLazy;
public take = 20;
public dataAdvanced = [
{
title: 'Dr. Gregory House 1',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 2',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 3',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 4',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 5',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 6',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 7',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 8',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 9',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 10',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 11',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 12',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 13',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 14',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 15',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 16',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 17',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 18',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 19',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 20',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 21',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 22',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 23',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 24',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 25',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 26',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 27',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 28',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 29',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 30',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 31',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 32',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 32',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 33',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 34',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 35',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 36',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 37',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 38',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 39',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 40',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 41',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 42',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 43',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 44',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}, {
title: 'Dr. Gregory House 45',
date: 1537477718000,
text: 'Mauris vulputate dolor vel finibus sagittis.',
duration: 15,
category: [
{
title: 'Anamnese',
text: 'Mauris vulputate dolor vel finibus sagittis.'
},
{
title: 'Evolution',
text: 'Mauris vulputate dolor vel finibus sagittis.'
}
]
}
];
constructor() {
this.dataTableProperties = json.dataProperties;
this.dataLazy = {
'data' : this.getDataFromService(0, this.take),
'total' : this.dataAdvanced.length
};
}
getDataFromService(skip, take) {
return this.dataAdvanced.slice(skip, take);
}
onLazyLoad(event) {
clearTimeout( this.timeout );
this.timeout = setTimeout( () => {
this.dataLazy = {
'data': this.getDataFromService( event.skip, event.take ),
'total': this.dataAdvanced.length
};
}, 1000 );
}
} | the_stack |
import { GotOptions } from "got";
import { ClientRequest, IncomingMessage } from "http";
import { PassThrough, Transform } from "stream";
import Promise = require("bluebird");
/**
* Use [`got`](https://www.npmjs.com/package/got) to make an HTTP request with automatic retries for network errors.
*
* Designed for downloading large files. If transfer fails part-way through, will retry, resuming from point where
* previous attempt finished, using HTTP range headers.
*
* @param url URL.
* @param options Options object.
*
* @example
* import gotResume = require('got-resume');
* import fs from 'fs';
*
* const stream = gotResume('http://google.com/');
* stream.pipe(fs.createWriteStream('foo.html'));
*
* stream.on('error', err => console.log('Failed!'));
* stream.on('end', () => console.log('Finished!'));
*/
declare function gotResume(url: string, options?: gotResume.TransferOptions): gotResume.TransferStream;
declare function gotResume(options: gotResume.TransferOptionsWithUrl): gotResume.TransferStream;
declare namespace gotResume {
/**
* Fetch URL and stream to file.
* Return Promise. Promise resolves/reject once request is complete
* (successfully or unsuccessfully) and file is closed.
*
* Promise only resolves (or rejects in case of an error) once transfer is ended and output file is closed.
*
* Promise is a Bluebird v2 promise. Bluebird v2 is used due to its cancellation feature.
*
* @param path File path to write to.
* @param url URL.
* @param options Options object (as per stream method).
*
* @example
* import gotResume = require('got-resume');
*
* gotResume.toFile('google.html', 'http://google.com/')
* .then(() => console.log('Finished!'))
* .catch(err => console.log('Failed!'));
*/
function toFile(path: string, url: string, options?: ToFileOptions): Promise<void>;
function toFile(path: string, options: ToFileOptionsWithUrl): Promise<void>;
interface WithUrl {
/**
* Alternative way to provide URL.
*
* @example
* import gotResume = require('got-resume');
*
* const stream = gotResume({ url: 'http://google.com/' });
*/
url: string;
}
interface TransferOptionsWithUrl extends TransferOptions, WithUrl {}
interface TransferOptions {
/**
* Max number of attempts in a row yielding no data (i.e. failed connection, empty response) before aborting.
*
* Set to `0` for no limit.
*
* @default 10
*
* @example
* import gotResume = require('got-resume');
*
* const stream = gotResume('http://google.com/', { attempts: 0 });
*/
attempts?: number | undefined;
/**
* Max number of total attempts before aborting.
*
* Set to `0` for no limit.
*
* @default 0
*/
attemptsTotal?: number | undefined;
/**
* Function to determine wait in milliseconds before retry.
*
* If function returns `false`, the transfer is aborted. If using this mechanism,
* `options.attempts` should be set to `0` so it does not interfere.
*
* If not provided, default backoff function starts with 1000ms and doubles each time:
*
* ```
* (attempt) => return Math.pow(2, attempt - 1) * 1000
* ```
*
* @param attempt Attempt number for current chunk (reset to zero when a new chunk is successfully received).
* @param transfer The internal `Transfer` object.
*/
backoff?(attempt: number, transfer: Transfer): number;
/**
* Length of response expected in bytes. If `undefined`, `length` will be determined
* from HTTP `content-length` header.
*
* If server does not provide `content-length` header, and `options.length` is not set,
* transfer will be considered complete when first successful response completes.
*
* If `options.length` is set, only that number of bytes will be fetched (i.e. file
* will be truncated).
*/
length?: number | undefined;
/**
* Number of bytes at start of resource to skip.
*
* NB Number of bytes to be streamed is `length - offset`. i.e. `length` is actually not
* length of response, but end of range, e.g. `{offset: 5, length: 10}` will stream 5 bytes.
*
* @default 0
*/
offset?: number | undefined;
/**
* Set to `true` if you require the length of the transfer to be retrieved at start of the
* transfer.
*
* Explanation: By default `got` will use transfer encoding (e.g. gzip). This makes the
* `content-length` HTTP header unreliable. Setting `options.needLength` disables encoding
* so length should be retrieved accurately (if server provides it).
*
* @default false
*/
needLength?: boolean | undefined;
/**
* Timeout in milliseconds.
*
* To disable timeouts, set to `null`.
*
* Timeout is for each chunk, not the whole tranfer. After a timeout, the transfer will
* retry until max attempts are exhausted.
*
* `timeout` can also be an object specifying timeouts for different parts of the
* request/response cycle individually. The timeouts will be set for all properties that
* are provided, the ones that are omitted will remain `undefined`.
*
* All above timeout options are passed to [`got`](https://www.npmjs.com/package/got)
* (see [here](https://www.npmjs.com/package/got#timeout)), except for `idle`. `idle` is
* time to wait before aborting chunk if transfer stalls (no data received in specifie
* time).
*
* @default 5000
*
* @example
* import gotResume = require('got-resume');
*
* const stream = gotResume({
* url: 'http://google.com/',
* timeout: {
* lookup: 1000,
* connect: 1000,
* secureConnect: 1000,
* socket: 1000,
* response: 1000,
* send: 1000,
* request: undefined,
* idle: 10000
* }
* });
*/
timeout?: number | TimeoutSpec | null | undefined;
/**
* An async function that is run before each chunk request. Request will commence once
* returned promise resolves.
*
* Useful where some authentication requires being set up before the transfer HTTP request,
* or where resource has a different URL each time (e.g. some file transfer services).
*
* @param transfer Then internal `Transfer` object. To set URL for next chunk, `pre` should
* set `transfer.url`. To alter `got` options, `pre` should set `transfer.gotOptions`.
*
* @example
* import gotResume = require('got-resume');
*
* const stream = gotResume({
* url: 'http://google.com/',
* pre: (transfer) => {
* transfer.gotOptions.headers['user-agent'] = 'Stealth 2.0';
* return Promise.resolve();
* }
* });
*/
pre?(transfer: Transfer): globalThis.Promise<void>;
/**
* Transform stream through which download stream is passed before being returned.
*
* @example
* import gotResume = require('got-resume');
* import zlib from 'zlib';
*
* await gotResume.toFile(
* 'google.html.gz',
* 'http://google.com/',
* { transform: zlib.createGzip() }
* );
*/
transform?: Transform | undefined;
/**
* Function to receive logging information e.g. HTTP responses.
*
* @example
* import gotResume = require('got-resume');
*
* const stream = gotResume('http://google.com/', { log: console.log });
*/
log?(...args: unknown[]): void;
/**
* Options to pass to `got`. See [got documentation](https://www.npmjs.com/package/got) for
* details.
*
* @example
* import gotResume = require('got-resume');
*
* const stream = gotResume('http://google.com/', { got: { method: 'POST' } });
*/
got?: GotOptions<string | null> | undefined;
}
interface TimeoutSpec {
lookup?: number | undefined;
connect?: number | undefined;
secureConnect?: number | undefined;
socket?: number | undefined;
response?: number | undefined;
send?: number | undefined;
request?: number | undefined;
idle?: number | undefined;
}
interface ToFileOptionsWithUrl extends ToFileOptions, WithUrl {}
interface ToFileOptions extends TransferOptions {
/**
* Handler for `progress` event.
*/
onProgress?(progress: Progress): void;
/**
* Handler for `response` event.
*/
onResponse?(res: IncomingMessage): void;
/**
* Promise implementation to use.
*
* @default Bluebird v2
*/
Promise?: any;
}
type TransferStream = {
/**
* Calling `.cancel()` will abort the transfer and cause the stream to emit an `error`
* event with a `CancelError`.
*
* If the transfer is complete before `.cancel()` is called, no `error` event will be
* emitted.
*
* If `options.pre` function is supplied and `.cancel()` is called while `options.pre` is
* running, `.cancel()` method on the promise returned by `options.pre` will be called if
* it exists. Otherwise the transfer will abort once the promise resolves.
*/
cancel(): void;
/**
* Parent `Transfer` object.
*/
transfer: Transfer;
/**
* Emitted with a `TransferError` on stream when transfer fails and has exhausted retries.
*/
addListener(
event: "error",
listener: (error: TransferError | CancelError | globalThis.Error) => any,
): TransferStream;
/**
* Emitted when transfer completes.
*
* **NB** Is also emitted after error event if transfer fails.
*/
addListener(event: "end", listener: () => any): TransferStream;
/**
* Emitted when data received.
*/
addListener(event: "progress", listener: (progress: Progress) => any): TransferStream;
/**
* Emitted when first HTTP request made to server.
*
* **NB** Not emitted again for each retry HTTP request. You cannot abort the transfer
* with `request.abort()` as the request may be finished if a retry has happened.
*
* Useful for e.g. determining length of transfer.
*
* @example
* import gotResume = require('got-resume');
*
* const stream = gotResume('http://google.com/');
* stream.on('response', res => console.log('Length: ', stream.transfer.length));
*/
addListener(event: "response", listener: (res: IncomingMessage) => any): TransferStream;
on(event: "error", listener: (error: TransferError | CancelError | globalThis.Error) => any): TransferStream;
on(event: "end", listener: () => any): TransferStream;
on(event: "progress", listener: (progress: Progress) => any): TransferStream;
on(event: "response", listener: (res: IncomingMessage) => any): TransferStream;
once(event: "error", listener: (error: TransferError | CancelError | globalThis.Error) => any): TransferStream;
once(event: "end", listener: () => any): TransferStream;
once(event: "progress", listener: (progress: Progress) => any): TransferStream;
once(event: "response", listener: (res: IncomingMessage) => any): TransferStream;
prependListener(
event: "error",
listener: (error: TransferError | CancelError | globalThis.Error) => any,
): TransferStream;
prependListener(event: "end", listener: () => any): TransferStream;
prependListener(event: "progress", listener: (progress: Progress) => any): TransferStream;
prependListener(event: "response", listener: (res: IncomingMessage) => any): TransferStream;
prependOnceListener(
event: "error",
listener: (error: TransferError | CancelError | globalThis.Error) => any,
): TransferStream;
prependOnceListener(event: "end", listener: () => any): TransferStream;
prependOnceListener(event: "progress", listener: (progress: Progress) => any): TransferStream;
prependOnceListener(event: "response", listener: (res: IncomingMessage) => any): TransferStream;
removeListener(
event: "error",
listener: (error: TransferError | CancelError | globalThis.Error) => any,
): TransferStream;
removeListener(event: "end", listener: () => any): TransferStream;
removeListener(event: "progress", listener: (progress: Progress) => any): TransferStream;
removeListener(event: "response", listener: (res: IncomingMessage) => any): TransferStream;
off(event: "error", listener: (error: TransferError | CancelError | globalThis.Error) => any): TransferStream;
off(event: "end", listener: () => any): TransferStream;
off(event: "progress", listener: (progress: Progress) => any): TransferStream;
off(event: "response", listener: (res: IncomingMessage) => any): TransferStream;
} & PassThrough;
interface Progress {
total: number;
transferred: number;
}
class Error extends globalThis.Error {
name: "GotResumeError";
}
class OptionsError extends globalThis.Error {
name: "GotResumeOptionsError";
}
class TransferError extends globalThis.Error {
name: "GotResumeTransferError";
}
class CancelError extends globalThis.Error {
name: "GotResumeCancelError";
}
class PreError extends globalThis.Error {
name: "GotResumePreError";
}
class Transfer {
/** Options passed to constructor. */
options: ToFileOptions & Partial<WithUrl>;
url?: string | undefined;
/** Length of options passed to constructor. */
length?: number | undefined;
log: (...args: unknown[]) => void;
gotOptions: GotOptions<string | null>;
idleTimeout?: number | undefined;
attempt: number;
attemptTotal: number;
position?: number | undefined;
total?: number | undefined;
cancelled: boolean;
requestEventFired: boolean;
/** `got` stream request. */
req?: ClientRequest | undefined;
/** `got` stream response. */
res?: IncomingMessage | undefined;
/** Error occurred during transfer. */
err?: globalThis.Error | undefined;
lastMod?: string | undefined;
etag?: string | undefined;
/** Promise returned from `options.pre`. */
prePromise?: Promise<void> | undefined;
/** Timeout. */
waitTimer?: number | undefined;
/** Output stream. */
stream: TransferStream;
constructor(options: ToFileOptions);
start(): void;
get(): void;
failed(err: globalThis.Error, empty: boolean): void;
fatal(): void;
cancel(): void;
}
}
export = gotResume; | the_stack |
import * as React from 'react';
import * as _ from 'lodash';
import * as path from 'path';
import { render } from '@testing-library/react';
import { TestObject, IsConformantOptions } from './types';
import { defaultErrorMessages } from './defaultErrorMessages';
import { ComponentDoc } from 'react-docgen-typescript';
import { getPackagePath, getCallbackArguments, validateCallbackArguments } from './utils/index';
import { act } from 'react-dom/test-utils';
const CALLBACK_REGEX = /^on(?!Render[A-Z])[A-Z]/;
const DEFAULT_CLASSNAME_PREFIX = 'fui-';
/**
* Find the target element where the attribute is applied using either `getTargetElement`,
* or the first child of the container.
*/
function getTargetElement(
testInfo: IsConformantOptions,
...[result, attr]: Parameters<Required<IsConformantOptions>['getTargetElement']>
) {
return testInfo.getTargetElement
? testInfo.getTargetElement(result, attr)
: (result.container.firstElementChild as HTMLElement);
}
/* eslint-disable @typescript-eslint/naming-convention */
export const defaultTests: TestObject = {
/** Component file exports a valid React element type */
'exports-component': (componentInfo: ComponentDoc, testInfo: IsConformantOptions) => {
it(`exports component from file under correct name (exports-component)`, () => {
const { componentPath, Component, displayName } = testInfo;
const componentFile = require(componentPath);
try {
if (testInfo.useDefaultExport) {
expect(componentFile.default).toBe(Component);
} else {
expect(componentFile[displayName]).toBe(Component);
}
} catch (e) {
throw new Error(defaultErrorMessages['exports-component'](testInfo, e, Object.keys(componentFile)));
}
});
},
/** Component file exports a valid React element and can render it */
'component-renders': (componentInfo: ComponentDoc, testInfo: IsConformantOptions) => {
it(`renders (component-renders)`, () => {
try {
const { requiredProps, Component, renderOptions } = testInfo;
expect(() => render(<Component {...requiredProps} />, renderOptions)).not.toThrow();
} catch (e) {
throw new Error(defaultErrorMessages['component-renders'](testInfo, e));
}
});
},
/**
* If functional component: component has a displayName
* Else: component's constructor is a named function and matches displayName
*/
'component-has-displayname': (componentInfo: ComponentDoc, testInfo: IsConformantOptions) => {
const { Component } = testInfo;
it(`has a displayName or constructor name (component-has-displayname)`, () => {
try {
const constructorName = Component.prototype?.constructor.name;
const displayName = Component.displayName || constructorName;
// This check is needed in case the Component is wrapped with the v7 styled() helper, which returns a wrapper
// component with constructor name Wrapped, and adds a Styled prefix to the displayName. Components passed to
// styled() typically have Base in their name, so remove that too.
expect(displayName).toMatch(new RegExp(`^(Customized|Styled)?${testInfo.displayName}(Base)?$`));
} catch (e) {
throw new Error(defaultErrorMessages['component-has-displayname'](testInfo, e));
}
});
},
/** Component handles ref */
'component-handles-ref': (componentInfo: ComponentDoc, testInfo: IsConformantOptions) => {
it(`handles ref (component-handles-ref)`, () => {
// This test simply verifies that the passed ref is applied to an element *anywhere* in the DOM
const { Component, requiredProps, elementRefName = 'ref', renderOptions } = testInfo;
const rootRef = React.createRef<HTMLDivElement>();
const mergedProps: Partial<{}> = {
...requiredProps,
[elementRefName]: rootRef,
};
const { baseElement } = render(<Component {...mergedProps} />, renderOptions);
try {
expect(rootRef.current).toBeInstanceOf(HTMLElement);
expect(baseElement.contains(rootRef.current)).toBe(true);
} catch (e) {
throw new Error(defaultErrorMessages['component-handles-ref'](testInfo, e));
}
});
},
/** Component has ref applied to the root component DOM node */
'component-has-root-ref': (componentInfo: ComponentDoc, testInfo: IsConformantOptions) => {
it(`applies ref to root element (component-has-root-ref)`, () => {
const { renderOptions, Component, requiredProps, elementRefName = 'ref', primarySlot = 'root' } = testInfo;
const rootRef = React.createRef<HTMLDivElement>();
const mergedProps: Partial<{}> = {
...requiredProps,
...(primarySlot !== 'root'
? {
// If primarySlot is something other than 'root', add the ref to
// the root slot rather than to the component's props.
root: { ref: rootRef },
}
: {
[elementRefName]: rootRef,
}),
};
const result = render(<Component {...mergedProps} />, renderOptions);
const refEl = getTargetElement(testInfo, result, 'ref');
expect(refEl).toBeTruthy();
try {
// Do an instanceof check first because if `ref` returns a class instance, the toBe check
// will print out the very long stringified version in the error (which isn't helpful)
expect(rootRef.current).toBeInstanceOf(HTMLElement);
expect(rootRef.current).toBe(refEl);
} catch (e) {
throw new Error(defaultErrorMessages['component-has-root-ref'](testInfo, e));
}
});
},
/**
* Component does not apply `size` as a native prop when a custom version is defined.
*
* Background: `input` and `select` support a `size` prop which is not very useful
* (https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/size).
* Since we don't anticipate ever needing this functionality, and we often want to use the prop name
* `size` to refer to visual size (like small/medium/large), we want to ensure that components defining
* a custom `size` prop don't also apply it as a native prop by accident.
*
* (In the extremely unlikely event that someone has a compelling need for the native functionality
* in the future, it can be added under an `htmlSize` prop.)
*/
'omits-size-prop': (componentInfo: ComponentDoc, testInfo: IsConformantOptions) => {
const sizeType = componentInfo.props.size?.type?.name;
if (!sizeType || componentInfo.props.htmlSize) {
return;
}
// if the size prop is defined, type.name will probably be 'string | undefined'
// or something like '"small" | "medium" | "large" | undefined'
const sizeIsString = /\bstring\b/.test(sizeType);
const sizeLiteralMatch = sizeType.match(/"(.*?)"/);
if (!sizeIsString || sizeLiteralMatch) {
return; // not a format we know how to test
}
it(`does not apply native size prop if custom one is defined (omits-size-prop)`, () => {
const { renderOptions, Component, requiredProps } = testInfo;
const size = sizeLiteralMatch?.[1] || 'foo';
const mergedProps = {
...requiredProps,
size,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any; // we know the size prop is supported but there's not a good way to derive the actual type
const { baseElement } = render(<Component {...mergedProps} />, renderOptions);
const elementWithSize = baseElement.querySelector('[size]');
try {
expect(elementWithSize).toBeFalsy();
} catch (e) {
throw new Error(defaultErrorMessages['omits-size-prop'](testInfo, e, size, elementWithSize!));
}
});
},
/** Component file handles classname prop */
'component-handles-classname': (componentInfo: ComponentDoc, testInfo: IsConformantOptions) => {
const { Component, requiredProps, renderOptions } = testInfo;
const testClassName = 'testComponentClassName';
let handledClassName = false;
let defaultClassNames: string[];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const mergedProps: any = {
...requiredProps,
className: testClassName,
};
it('has default classNames', () => {
// this is not a real test, it's just to get the default class names without causing
// possible side effects within another test by rendering the component twice
const defaultResult = render(<Component {...requiredProps} />, renderOptions);
const defaultEl = getTargetElement(testInfo, defaultResult, 'className');
defaultClassNames = classListToStrings(defaultEl.classList);
});
it(`handles className prop (component-handles-classname)`, () => {
const result = render(<Component {...mergedProps} />, renderOptions);
const domNode = getTargetElement(testInfo, result, 'className');
expect(domNode).toBeTruthy();
const classNames = classListToStrings(domNode.classList);
try {
expect(classNames).toContain(testClassName);
handledClassName = true;
} catch (e) {
throw new Error(
defaultErrorMessages['component-handles-classname'](testInfo, e, testClassName, classNames, domNode),
);
}
});
it(`preserves component's default classNames (component-preserves-default-classname)`, () => {
if (!handledClassName || !defaultClassNames?.length) {
return; // don't run this test if the main className test failed or there are no defaults
}
const result = render(<Component {...mergedProps} />, renderOptions);
const el = getTargetElement(testInfo, result, 'className');
const classNames = classListToStrings(el.classList);
let defaultClassName: string = '';
try {
for (defaultClassName of defaultClassNames) {
expect(classNames).toContain(defaultClassName);
}
} catch (e) {
throw new Error(
defaultErrorMessages['component-preserves-default-classname'](
testInfo,
e,
testClassName,
defaultClassName,
classNames,
),
);
}
});
},
/** Component file has assigned and exported static class */
'component-has-static-classname': (componentInfo: ComponentDoc, testInfo: IsConformantOptions) => {
const {
Component,
requiredProps,
renderOptions,
testOptions: { 'component-has-static-classname': { prefix = DEFAULT_CLASSNAME_PREFIX } = {} } = {},
} = testInfo;
const componentClassName = `${prefix}${componentInfo.displayName}`;
it(`has static classname (component-has-static-classname)`, () => {
const result = render(<Component {...requiredProps} />, renderOptions);
const rootEl = getTargetElement(testInfo, result, 'className');
expect(rootEl).toBeTruthy();
const classNames = classListToStrings(rootEl.classList);
try {
expect(classNames).toContain(componentClassName);
} catch (e) {
throw new Error(
defaultErrorMessages['component-has-static-classname'](testInfo, e, componentClassName, classNames),
);
}
});
},
'component-has-static-classname-exported': (componentInfo: ComponentDoc, testInfo: IsConformantOptions) => {
if (testInfo.isInternal) {
return;
}
const {
componentPath,
testOptions: { 'component-has-static-classname': { prefix = DEFAULT_CLASSNAME_PREFIX } = {} } = {},
} = testInfo;
const componentClassName = `${prefix}${componentInfo.displayName}`;
it(`static classname is exported at top-level (component-has-static-classname-exported)`, () => {
const exportName =
componentInfo.displayName.slice(0, 1).toLowerCase() + componentInfo.displayName.slice(1) + 'ClassName';
try {
const indexFile = require(path.join(getPackagePath(componentPath), 'src', 'index'));
expect(indexFile[exportName]).toBe(componentClassName);
} catch (e) {
throw new Error(
defaultErrorMessages['component-has-static-classname-exported'](testInfo, e, componentClassName, exportName),
);
}
});
},
'component-has-static-classnames-object': (componentInfo: ComponentDoc, testInfo: IsConformantOptions) => {
const { componentPath, Component, requiredProps, renderOptions } = testInfo;
const componentName = componentInfo.displayName;
const componentClassName = `fui-${componentName}`;
const exportName = `${componentName[0].toLowerCase()}${componentName.slice(1)}ClassNames`;
const indexPath = path.join(getPackagePath(componentPath), 'src', 'index');
let handledClassNamesObjectExport = false;
it('has static classnames exported at top-level (component-has-static-classnames-object)', () => {
if (testInfo.isInternal) {
return;
}
try {
const indexFile = require(indexPath);
const classNamesFromFile = indexFile[exportName];
expect(classNamesFromFile).toBeTruthy();
handledClassNamesObjectExport = true;
} catch (e) {
throw new Error(
defaultErrorMessages['component-has-static-classnames-object-exported'](testInfo, e, exportName),
);
}
});
it('has static classnames in correct format (component-has-static-classnames-object)', () => {
if (!handledClassNamesObjectExport) {
return;
}
const indexFile = require(indexPath);
const classNamesFromFile = indexFile[exportName];
const expectedClassNames = Object.keys(classNamesFromFile).reduce(
(obj: { [key: string]: string }, key: string) => {
obj[key] = key === 'root' ? componentClassName : `${componentClassName}__${key}`;
return obj;
},
{},
);
try {
expect(classNamesFromFile).toEqual(expectedClassNames);
} catch (e) {
throw new Error(
defaultErrorMessages['component-has-static-classnames-in-correct-format'](testInfo, e, exportName),
);
}
});
it(`has static classnames in rendered component (component-has-static-classnames-object)`, () => {
if (!handledClassNamesObjectExport) {
return;
}
const { testOptions = {} } = testInfo;
const staticClassNameVariants = testOptions['has-static-classnames'] ?? [{ props: {} }];
for (const staticClassNames of staticClassNameVariants) {
const mergedProps = {
...requiredProps,
...staticClassNames.props,
};
const result = render(<Component {...mergedProps} />, renderOptions);
const rootEl = getTargetElement(testInfo, result, 'className');
const indexFile = require(indexPath);
const classNamesFromFile = indexFile[exportName];
const expectedClassNames: { [key: string]: string } = staticClassNames.expectedClassNames ?? classNamesFromFile;
const missingClassNames = Object.values(expectedClassNames).filter(
className => !rootEl.classList.contains(className) && !rootEl.querySelector(`.${className}`),
);
try {
expect(missingClassNames).toHaveLength(0);
} catch (e) {
throw new Error(
defaultErrorMessages['component-has-static-classnames'](
testInfo,
e,
componentName,
missingClassNames.join(', '),
rootEl,
),
);
}
}
});
},
/** Constructor/component name matches filename */
'name-matches-filename': (componentInfo: ComponentDoc, testInfo: IsConformantOptions) => {
it(`Component/constructor name matches filename (name-matches-filename)`, () => {
try {
const { componentPath, displayName } = testInfo;
const fileName = path.basename(componentPath, path.extname(componentPath));
expect(displayName).toMatch(fileName);
} catch (e) {
throw new Error(defaultErrorMessages['name-matches-filename'](testInfo, e));
}
});
},
/** Ensures component is exported at top level allowing `import { Component } from 'packageName'` */
'exported-top-level': (componentInfo: ComponentDoc, testInfo: IsConformantOptions) => {
if (testInfo.isInternal) {
return;
}
it(`is exported at top-level (exported-top-level)`, () => {
try {
const { displayName, componentPath, Component } = testInfo;
const indexFile = require(path.join(getPackagePath(componentPath), 'src', 'index'));
expect(indexFile[displayName]).toBe(Component);
} catch (e) {
throw new Error(defaultErrorMessages['exported-top-level'](testInfo, e));
}
});
},
/** Ensures component has top level file in package/src/componentName */
'has-top-level-file': (componentInfo: ComponentDoc, testInfo: IsConformantOptions) => {
if (testInfo.isInternal) {
return;
}
it(`has corresponding top-level file 'package/src/Component' (has-top-level-file)`, () => {
try {
const { displayName, componentPath, Component } = testInfo;
const topLevelFile = require(path.join(getPackagePath(componentPath), 'src', displayName));
expect(topLevelFile[displayName]).toBe(Component);
} catch (e) {
throw new Error(defaultErrorMessages['has-top-level-file'](testInfo, e));
}
});
},
/** Ensures aria attributes are kebab cased */
'kebab-aria-attributes': (componentInfo: ComponentDoc, testInfo: IsConformantOptions) => {
it(`uses kebab-case for aria attributes (kebab-aria-attributes)`, () => {
const invalidProps = Object.keys(componentInfo.props).filter(
prop => prop.startsWith('aria') && !/^aria-[a-z]+$/.test(prop),
);
try {
expect(invalidProps).toEqual([]);
} catch (e) {
throw new Error(defaultErrorMessages['kebab-aria-attributes'](testInfo, invalidProps));
}
});
},
// TODO: Test last word of callback name against list of valid verbs
/** Ensures that components have consistent custom callback names i.e. on[Part][Event] */
'consistent-callback-names': (componentInfo: ComponentDoc, testInfo: IsConformantOptions) => {
it(`has consistent custom callback names (consistent-callback-names)`, () => {
const { testOptions = {} } = testInfo;
const propNames = Object.keys(componentInfo.props);
const ignoreProps = testOptions['consistent-callback-names']?.ignoreProps || [];
const invalidProps = propNames.filter(propName => {
if (!ignoreProps.includes(propName) && CALLBACK_REGEX.test(propName)) {
const words = propName.slice(2).match(/[A-Z][a-z]+/g);
if (words) {
// Make sure last word doesn't end with ed
const lastWord = words[words.length - 1];
return lastWord.endsWith('ed');
}
}
return false;
});
try {
expect(invalidProps).toEqual([]);
} catch (e) {
throw new Error(defaultErrorMessages['consistent-callback-names'](testInfo, invalidProps));
}
});
},
/** Ensures that components have consistent callback arguments (ev, data) */
'consistent-callback-args': (componentInfo, testInfo, tsProgram) => {
it('has consistent custom callback arguments (consistent-callback-args)', () => {
const { testOptions = {} } = testInfo;
const propNames = Object.keys(componentInfo.props);
const ignoreProps = testOptions['consistent-callback-args']?.ignoreProps || [];
const invalidProps = propNames.reduce<Record<string, Error>>((errors, propName) => {
if (!ignoreProps.includes(propName) && CALLBACK_REGEX.test(propName)) {
const propInfo = componentInfo.props[propName];
if (!propInfo.declarations) {
throw new Error(
[
`Definition for "${propName}" does not have ".declarations" produced by "react-docgen-typescript".`,
'Please report a bug in Fluent UI repo if this happens. Include in a bug report details about file',
'where it happens and used interfaces.',
].join(' '),
);
}
if (propInfo.declarations.length !== 1) {
throw new Error(
[
`Definition for "${propName}" has multiple elements in ".declarations" produced by `,
`"react-docgen-typescript".`,
'Please report a bug in Fluent UI repo if this happens. Include in a bug report details about file',
'where it happens and used interfaces.',
].join(' '),
);
}
const rootFileName = propInfo.declarations[0].fileName;
const propsTypeName = propInfo.declarations[0].name;
try {
validateCallbackArguments(getCallbackArguments(tsProgram, rootFileName, propsTypeName, propName));
} catch (err) {
console.log('err', err);
return { ...errors, [propName]: err };
}
}
return errors;
}, {});
try {
expect(invalidProps).toEqual({});
} catch (e) {
throw new Error(defaultErrorMessages['consistent-callback-args'](testInfo, invalidProps));
}
});
},
/** If the primary slot is specified, it receives native props other than 'className' and 'style' */
'primary-slot-gets-native-props': (componentInfo: ComponentDoc, testInfo: IsConformantOptions) => {
it(`applies correct native props to the primary and root slots (primary-slot-gets-native-props)`, () => {
try {
const { Component, requiredProps, primarySlot = 'root', renderOptions } = testInfo;
// This test only applies if this component has a primary slot other than 'root'
// (this also prevents the test from running for northstar and v8)
if (primarySlot === 'root') {
return;
}
// Add this data attribute directly to the primary slot so that its DOM node can be
// found to verify that the props went to the correct element
const primarySlotDataTag = 'data-primary-slot';
// Add these values to the component's props to make sure they are forwarded to the appropriate slot
const ref = React.createRef<HTMLElement>();
const testDataAttribute = 'data-conformance-test'; // A data attribute is a proxy for any arbitrary native prop
const testClass = 'conformance-test-class-name';
const testStyleFontFamily = 'conformance-test-font-family';
const mergedProps: Partial<{}> = {
...requiredProps,
[primarySlot]: {
[primarySlotDataTag]: true,
},
ref,
className: testClass,
style: { fontFamily: testStyleFontFamily },
[testDataAttribute]: testDataAttribute,
};
const { container } = render(<Component {...mergedProps} />, renderOptions);
const rootNode = container.firstElementChild as HTMLElement;
expect(rootNode).toBeTruthy();
act(() => {
// Find the node that represents the primary slot, searching for its data attribute
const primaryNode = rootNode.querySelector(`[${primarySlotDataTag}]`);
// We should have found the primary slot's node
expect(primaryNode).toBeInstanceOf(HTMLElement);
if (!(primaryNode instanceof HTMLElement)) {
return;
}
// className and style should go the *root* slot
expect(classListToStrings(rootNode.classList)).toContain(testClass);
expect(rootNode.style.fontFamily).toEqual(testStyleFontFamily);
// ... and not the primary slot
expect(classListToStrings(primaryNode.classList)).not.toContain(testClass);
expect(primaryNode.style.fontFamily).not.toEqual(testStyleFontFamily);
// Ref and all other native props should go to the *primary* slot
expect(primaryNode).toBe(ref.current);
expect(primaryNode.getAttribute(testDataAttribute)).toEqual(testDataAttribute);
// ... and not the root slot
expect(rootNode).not.toBe(ref.current);
expect(rootNode.getAttribute(testDataAttribute)).not.toEqual(testDataAttribute);
});
} catch (e) {
throw new Error(defaultErrorMessages['primary-slot-gets-native-props'](testInfo, e));
}
});
},
};
function classListToStrings(classList: DOMTokenList): string[] {
// We should be able to just do [...classList] but that requires lib: dom.iterable in tsconfig.json.
// Due to path aliases, react-conformance gets type-checked with each converged package,
// so we'd need to add dom.iterable in all converged packages too.
// This function is a workaround.
const result: string[] = [];
for (let i = 0; i < classList.length; i++) {
result.push(classList[i]);
}
return result;
} | the_stack |
import React, { ChangeEvent, PureComponent } from 'react';
import { RedisGraph } from 'redis/graph';
import { css } from '@emotion/css';
import { QueryEditorProps, SelectableValue } from '@grafana/data';
import { Button, InlineFormLabel, LegacyForms, RadioButtonGroup, Select, TextArea } from '@grafana/ui';
import { StreamingDataType, StreamingDataTypes } from '../../constants';
import { DataSource } from '../../data-source';
import {
Aggregations,
AggregationValue,
CommandParameters,
Commands,
InfoSections,
InfoSectionValue,
QueryType,
QueryTypeValue,
Redis,
RedisQuery,
RedisTimeSeries,
} from '../../redis';
import { RedisDataSourceOptions } from '../../types';
/**
* Form Field
*/
const { FormField, Switch } = LegacyForms;
/**
* Editor Property
*/
type Props = QueryEditorProps<DataSource, RedisQuery, RedisDataSourceOptions>;
/**
* Query Editor
*/
export class QueryEditor extends PureComponent<Props> {
/**
* Change handler for number field
*
* @param {ChangeEvent<HTMLInputElement>} event Event
*/
createNumberFieldHandler = (name: keyof RedisQuery) => (event: ChangeEvent<HTMLInputElement>) => {
this.props.onChange({ ...this.props.query, [name]: Number(event.target.value) });
};
/**
* Change handler for text field
*
* @param {ChangeEvent<HTMLInputElement>} event Event
*/
createTextFieldHandler = (name: keyof RedisQuery) => (event: ChangeEvent<HTMLInputElement>) => {
this.props.onChange({ ...this.props.query, [name]: event.target.value });
};
/**
* Change handler for textarea field
*
* @param {ChangeEvent<HTMLInputElement>} event Event
*/
createTextareaFieldHandler = (name: keyof RedisQuery) => (event: ChangeEvent<HTMLTextAreaElement>) => {
this.props.onChange({ ...this.props.query, [name]: event.target.value });
};
/**
* Change handler for select field
*
* @param {ChangeEvent<HTMLInputElement>} event Event
*/
createSelectFieldHandler<ValueType>(name: keyof RedisQuery) {
return (val: SelectableValue<ValueType>) => {
this.props.onChange({ ...this.props.query, [name]: val.value });
};
}
/**
* Change handler for radio button field
*
* @param {value: ValueType}
*/
createRedioButtonFieldHandler<ValueType>(name: keyof RedisQuery) {
return (value?: ValueType) => {
this.props.onChange({ ...this.props.query, [name]: value });
};
}
/**
* Change handler for switch field
*
* @param {ChangeEvent<HTMLInputElement>} event Event
*/
createSwitchFieldHandler = (name: keyof RedisQuery) => (event: React.SyntheticEvent<HTMLInputElement>) => {
this.props.onChange({ ...this.props.query, [name]: event.currentTarget.checked });
};
/**
* Key name change
*/
onKeyNameChange = this.createTextFieldHandler('keyName');
/**
* Query change
*/
onQueryChange = this.createTextareaFieldHandler('query');
/**
* Filter change
*/
onFilterChange = this.createTextFieldHandler('filter');
/**
* Cypher change
*/
onCypherChange = this.createTextareaFieldHandler('cypher');
/**
* Field change
*/
onFieldChange = this.createTextFieldHandler('field');
/**
* Legend change
*/
onLegendChange = this.createTextFieldHandler('legend');
/**
* Value change
*/
onValueChange = this.createTextFieldHandler('value');
/**
* Command change
*/
onCommandChange = this.createSelectFieldHandler<string>('command');
/**
* Type change
*
* @param val Value
*/
onTypeChange = (val: SelectableValue<string>) => {
const { onChange, query } = this.props;
onChange({
...query,
type: val.value as QueryTypeValue,
query: '',
command: '',
});
};
/**
* Aggregation change
*/
onAggregationChange = this.createSelectFieldHandler<AggregationValue>('aggregation');
/**
* Info section change
*/
onInfoSectionChange = this.createSelectFieldHandler<InfoSectionValue>('section');
/**
* Bucket change
*/
onBucketChange = this.createNumberFieldHandler('bucket');
/**
* Size change
*/
onSizeChange = this.createNumberFieldHandler('size');
/**
* Count change
*/
onCountChange = this.createNumberFieldHandler('count');
/**
* Samples change
*/
onSamplesChange = this.createNumberFieldHandler('samples');
/**
* Cursor change
*/
onCursorChange = this.createTextFieldHandler('cursor');
/**
* Match change
*/
onMatchChange = this.createTextFieldHandler('match');
/**
* Start change
*/
onStartChange = this.createTextFieldHandler('start');
/**
* End change
*/
onEndChange = this.createTextFieldHandler('end');
/**
* Fill change
*/
onFillChange = this.createSwitchFieldHandler('fill');
/**
* Streaming change
*/
onStreamingChange = this.createSwitchFieldHandler('streaming');
/**
* Streaming interval change
*/
onStreamingIntervalChange = this.createNumberFieldHandler('streamingInterval');
/**
* Streaming capacity change
*/
onStreamingCapacityChange = this.createNumberFieldHandler('streamingCapacity');
/**
* Streaming data type change
*/
onStreamingDataTypeChange = this.createRedioButtonFieldHandler<StreamingDataType>('streamingDataType');
/**
* Render Editor
*/
render() {
const {
keyName,
aggregation,
bucket,
legend,
command,
field,
filter,
cypher,
value,
query,
type,
section,
size,
fill,
cursor,
count,
match,
samples,
start,
end,
streaming,
streamingInterval,
streamingCapacity,
streamingDataType,
} = this.props.query;
const { onRunQuery } = this.props;
/**
* Return
*/
return (
<div>
<div className="gf-form">
<InlineFormLabel width={8}>Type</InlineFormLabel>
<Select
className={css`
margin-right: 5px;
`}
width={40}
options={QueryType}
menuPlacement="bottom"
value={type}
onChange={this.onTypeChange}
/>
{type === QueryTypeValue.CLI && (
<>
<InlineFormLabel width={8}>Command</InlineFormLabel>
<TextArea value={query} className="gf-form-input" onChange={this.onQueryChange} />
</>
)}
{type && type !== QueryTypeValue.CLI && (
<>
<InlineFormLabel width={8}>Command</InlineFormLabel>
<Select options={Commands[type]} menuPlacement="bottom" value={command} onChange={this.onCommandChange} />
</>
)}
</div>
{type !== QueryTypeValue.CLI && command && (
<div className="gf-form">
{CommandParameters.keyName.includes(command as Redis) && (
<FormField
labelWidth={8}
inputWidth={30}
value={keyName}
onChange={this.onKeyNameChange}
label="Key"
tooltip="Key name"
/>
)}
{CommandParameters.filter.includes(command as RedisTimeSeries) && (
<FormField
labelWidth={8}
inputWidth={30}
value={filter}
onChange={this.onFilterChange}
label="Label Filter"
tooltip="Whenever filters need to be provided, a minimum of one l=v filter must be applied.
The list of possible filters:
https://oss.redislabs.com/redistimeseries/commands/#filtering"
/>
)}
{CommandParameters.field.includes(command as Redis) && (
<FormField labelWidth={8} inputWidth={30} value={field} onChange={this.onFieldChange} label="Field" />
)}
{CommandParameters.legend.includes(command as RedisTimeSeries) && (
<FormField
labelWidth={8}
inputWidth={20}
value={legend}
onChange={this.onLegendChange}
label="Legend"
tooltip="Legend override"
/>
)}
{CommandParameters.value.includes(command as RedisTimeSeries) && (
<FormField
labelWidth={8}
inputWidth={10}
value={value}
onChange={this.onValueChange}
label="Value"
tooltip="Value override"
/>
)}
{CommandParameters.legendLabel.includes(command as RedisTimeSeries) && (
<FormField
labelWidth={8}
inputWidth={10}
value={legend}
onChange={this.onLegendChange}
label="Legend Label"
/>
)}
{CommandParameters.valueLabel.includes(command as RedisTimeSeries) && (
<FormField
labelWidth={8}
inputWidth={10}
value={value}
onChange={this.onValueChange}
label="Value Label"
/>
)}
{CommandParameters.size.includes(command as Redis) && (
<FormField
labelWidth={8}
inputWidth={10}
value={size}
type="number"
onChange={this.onSizeChange}
label="Size"
/>
)}
{CommandParameters.cursor.includes(command as Redis) && (
<FormField labelWidth={8} inputWidth={10} value={cursor} onChange={this.onCursorChange} label="Cursor" />
)}
{CommandParameters.match.includes(command as Redis) && (
<FormField
labelWidth={8}
inputWidth={10}
value={match}
onChange={this.onMatchChange}
placeholder="*"
label="Match pattern"
/>
)}
{CommandParameters.start.includes(command as Redis) && (
<FormField
labelWidth={8}
inputWidth={10}
value={start}
onChange={this.onStartChange}
placeholder="-"
label="Start"
/>
)}
{CommandParameters.end.includes(command as Redis) && (
<FormField
labelWidth={8}
inputWidth={10}
value={end}
onChange={this.onEndChange}
placeholder="+"
label="End"
/>
)}
</div>
)}
{command && CommandParameters.cypher.includes(command as RedisGraph) && (
<div className="gf-form">
<InlineFormLabel
tooltip="The syntax is based on Cypher, and only a subset of the language currently supported: \
https://oss.redislabs.com/redisgraph/commands/#query-language"
width={8}
>
Cypher
</InlineFormLabel>
<TextArea value={cypher} className="gf-form-input" onChange={this.onCypherChange} />
</div>
)}
{type !== QueryTypeValue.CLI && command && (
<div className="gf-form">
{CommandParameters.count.includes(command as Redis) && (
<FormField
labelWidth={8}
inputWidth={10}
value={count}
type="number"
onChange={this.onCountChange}
label="Count"
tooltip="Can cause latency and is not recommended to use in Production."
/>
)}
{CommandParameters.samples.includes(command as Redis) && (
<FormField
labelWidth={8}
inputWidth={10}
value={samples}
type="number"
onChange={this.onSamplesChange}
label="Samples"
placeholder="5"
tooltip="Number of sampled nested values. 0 (all values) is not supported."
/>
)}
</div>
)}
{type === QueryTypeValue.REDIS && command && CommandParameters.section.includes(command as Redis) && (
<div className="gf-form">
<InlineFormLabel width={8}>Section</InlineFormLabel>
<Select options={InfoSections} onChange={this.onInfoSectionChange} value={section} menuPlacement="bottom" />
</div>
)}
{type === QueryTypeValue.TIMESERIES &&
command &&
CommandParameters.aggregation.includes(command as RedisTimeSeries) && (
<div className="gf-form">
<InlineFormLabel width={8}>Aggregation</InlineFormLabel>
<Select
className={css`
margin-right: 5px;
`}
options={Aggregations}
width={30}
onChange={this.onAggregationChange}
value={aggregation}
menuPlacement="bottom"
/>
{aggregation && (
<FormField
labelWidth={8}
value={bucket}
type="number"
onChange={this.onBucketChange}
label="Time Bucket"
tooltip="Time bucket for aggregation in milliseconds"
/>
)}
{aggregation && bucket && CommandParameters.fill.includes(command as RedisTimeSeries) && (
<Switch
label="Fill Missing"
labelClass="width-10"
tooltip="If checked, the datasource will fill missing intervals."
checked={fill || false}
onChange={this.onFillChange}
/>
)}
</div>
)}
<div className="gf-form">
<Switch
label="Streaming"
labelClass="width-8"
tooltip="If checked, the datasource will stream data."
checked={streaming || false}
onChange={this.onStreamingChange}
/>
{streaming && (
<>
<FormField
labelWidth={8}
value={streamingInterval}
type="number"
onChange={this.onStreamingIntervalChange}
label="Interval"
tooltip="Streaming interval in milliseconds. Default is 1000ms. For multiple Streaming targets minimum value will be taken."
placeholder="1000"
/>
<FormField
labelWidth={8}
value={streamingCapacity}
type="number"
onChange={this.onStreamingCapacityChange}
label="Capacity"
tooltip="Values will be constantly added and will never exceed the given capacity. Default is 1000."
placeholder="1000"
/>
</>
)}
</div>
{streaming && (
<div className="gf-form">
<InlineFormLabel width={8} tooltip="If checked Time series, the last line of data will be applied.">
Data type
</InlineFormLabel>
<RadioButtonGroup
options={StreamingDataTypes}
value={streamingDataType || StreamingDataType.TIMESERIES}
onChange={this.onStreamingDataTypeChange}
/>
{streamingDataType !== StreamingDataType.DATAFRAME && (
<FormField
className={css`
margin-left: 5px;
`}
labelWidth={8}
inputWidth={30}
value={field}
tooltip="Specify field(s) to return from backend. Required for Alerting to trigger on specific fields."
onChange={this.onFieldChange}
label="Filter Field"
/>
)}
</div>
)}
<Button onClick={onRunQuery}>Run</Button>
</div>
);
}
} | the_stack |
import { PublicKey } from '@solana/web3.js';
import { EventEmitter } from 'events';
import StrictEventEmitter from 'strict-event-emitter-types';
import { ClearingHouse } from './clearingHouse';
import {
isVariant,
MarginCategory,
Order,
SettlementStateAccount,
UserAccount,
UserOrdersAccount,
UserPosition,
UserPositionsAccount,
} from './types';
import {
calculateEntryPrice,
calculateSettledPositionPNL,
} from './math/position';
import {
MARK_PRICE_PRECISION,
AMM_TO_QUOTE_PRECISION_RATIO,
ZERO,
TEN_THOUSAND,
BN_MAX,
QUOTE_PRECISION,
AMM_RESERVE_PRECISION,
PRICE_TO_QUOTE_PRECISION,
MARGIN_PRECISION,
} from './constants/numericConstants';
import { UserAccountSubscriber, UserAccountEvents } from './accounts/types';
import {
calculateMarkPrice,
calculateBaseAssetValue,
calculatePositionFundingPNL,
calculatePositionPNL,
PositionDirection,
getUserOrdersAccountPublicKey,
calculateTradeSlippage,
BN,
} from '.';
import { getUserAccountPublicKey } from './addresses';
import {
getClearingHouseUser,
getWebSocketClearingHouseUserConfig,
} from './factory/clearingHouseUser';
export class ClearingHouseUser {
clearingHouse: ClearingHouse;
authority: PublicKey;
accountSubscriber: UserAccountSubscriber;
userAccountPublicKey?: PublicKey;
userOrdersAccountPublicKey?: PublicKey;
_isSubscribed = false;
eventEmitter: StrictEventEmitter<EventEmitter, UserAccountEvents>;
public get isSubscribed() {
return this._isSubscribed && this.accountSubscriber.isSubscribed;
}
public set isSubscribed(val: boolean) {
this._isSubscribed = val;
}
/**
* @deprecated You should use getClearingHouseUser factory method instead
* @param clearingHouse
* @param authority
* @returns
*/
public static from(
clearingHouse: ClearingHouse,
authority: PublicKey
): ClearingHouseUser {
if (clearingHouse.accountSubscriber.type !== 'websocket')
throw 'This method only works for clearing houses with a websocket account listener. Try using the getClearingHouseUser factory method to initialize a ClearingHouseUser instead';
const config = getWebSocketClearingHouseUserConfig(
clearingHouse,
authority
);
return getClearingHouseUser(config);
}
public constructor(
clearingHouse: ClearingHouse,
authority: PublicKey,
accountSubscriber: UserAccountSubscriber
) {
this.clearingHouse = clearingHouse;
this.authority = authority;
this.accountSubscriber = accountSubscriber;
this.eventEmitter = this.accountSubscriber.eventEmitter;
}
/**
* Subscribe to ClearingHouseUser state accounts
* @returns SusbcriptionSuccess result
*/
public async subscribe(): Promise<boolean> {
// Clearing house should already be subscribed, but await for the subscription just incase to avoid race condition
await this.clearingHouse.subscribe();
this.isSubscribed = await this.accountSubscriber.subscribe();
return this.isSubscribed;
}
/**
* Forces the accountSubscriber to fetch account updates from rpc
*/
public async fetchAccounts(): Promise<void> {
await this.accountSubscriber.fetch();
}
public async unsubscribe(): Promise<void> {
await this.accountSubscriber.unsubscribe();
this.isSubscribed = false;
}
public getUserAccount(): UserAccount {
return this.accountSubscriber.getUserAccount();
}
public getUserPositionsAccount(): UserPositionsAccount {
return this.accountSubscriber.getUserPositionsAccount();
}
public getUserOrdersAccount(): UserOrdersAccount | undefined {
return this.accountSubscriber.getUserOrdersAccount();
}
/**
* Gets the user's current position for a given market. If the user has no position returns undefined
* @param marketIndex
* @returns userPosition
*/
public getUserPosition(marketIndex: BN): UserPosition | undefined {
return this.getUserPositionsAccount().positions.find((position) =>
position.marketIndex.eq(marketIndex)
);
}
public getEmptyPosition(marketIndex: BN): UserPosition {
return {
baseAssetAmount: ZERO,
lastCumulativeFundingRate: ZERO,
marketIndex,
quoteAssetAmount: ZERO,
openOrders: ZERO,
};
}
/**
* @param orderId
* @returns Order
*/
public getOrder(orderId: BN): Order | undefined {
return this.getUserOrdersAccount().orders.find((order) =>
order.orderId.eq(orderId)
);
}
/**
* @param userOrderId
* @returns Order
*/
public getOrderByUserOrderId(userOrderId: number): Order | undefined {
return this.getUserOrdersAccount().orders.find(
(order) => order.userOrderId === userOrderId
);
}
public async getUserAccountPublicKey(): Promise<PublicKey> {
if (this.userAccountPublicKey) {
return this.userAccountPublicKey;
}
this.userAccountPublicKey = await getUserAccountPublicKey(
this.clearingHouse.program.programId,
this.authority
);
return this.userAccountPublicKey;
}
public async getUserOrdersAccountPublicKey(): Promise<PublicKey> {
if (this.userOrdersAccountPublicKey) {
return this.userOrdersAccountPublicKey;
}
this.userOrdersAccountPublicKey = await getUserOrdersAccountPublicKey(
this.clearingHouse.program.programId,
await this.getUserAccountPublicKey()
);
return this.userOrdersAccountPublicKey;
}
public async exists(): Promise<boolean> {
const userAccountPublicKey = await this.getUserAccountPublicKey();
const userAccountRPCResponse =
await this.clearingHouse.connection.getParsedAccountInfo(
userAccountPublicKey
);
return userAccountRPCResponse.value !== null;
}
/**
* calculates Buying Power = FC * MAX_LEVERAGE
* @returns : Precision QUOTE_PRECISION
*/
public getBuyingPower(marketIndex: BN | number): BN {
return this.getFreeCollateral()
.mul(this.getMaxLeverage(marketIndex, 'Initial'))
.div(TEN_THOUSAND);
}
/**
* calculates Free Collateral = Total collateral - initial margin requirement
* @returns : Precision QUOTE_PRECISION
*/
public getFreeCollateral(): BN {
const totalCollateral = this.getTotalCollateral();
const initialMarginRequirement = this.getInitialMarginRequirement();
const freeCollateral = totalCollateral.sub(initialMarginRequirement);
return freeCollateral.gte(ZERO) ? freeCollateral : ZERO;
}
public getInitialMarginRequirement(): BN {
return this.getUserPositionsAccount().positions.reduce(
(marginRequirement, marketPosition) => {
const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
return marginRequirement.add(
calculateBaseAssetValue(market, marketPosition)
.mul(new BN(market.marginRatioInitial))
.div(MARGIN_PRECISION)
);
},
ZERO
);
}
/**
* @returns The partial margin requirement in USDC. : QUOTE_PRECISION
*/
public getPartialMarginRequirement(): BN {
return this.getUserPositionsAccount().positions.reduce(
(marginRequirement, marketPosition) => {
const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
return marginRequirement.add(
calculateBaseAssetValue(market, marketPosition)
.mul(new BN(market.marginRatioPartial))
.div(MARGIN_PRECISION)
);
},
ZERO
);
}
/**
* calculates unrealized position price pnl
* @returns : Precision QUOTE_PRECISION
*/
public getUnrealizedPNL(withFunding?: boolean, marketIndex?: BN): BN {
return this.getUserPositionsAccount()
.positions.filter((pos) =>
marketIndex ? pos.marketIndex === marketIndex : true
)
.reduce((pnl, marketPosition) => {
const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
return pnl.add(
calculatePositionPNL(market, marketPosition, withFunding)
);
}, ZERO);
}
/**
* calculates unrealized funding payment pnl
* @returns : Precision QUOTE_PRECISION
*/
public getUnrealizedFundingPNL(marketIndex?: BN): BN {
return this.getUserPositionsAccount()
.positions.filter((pos) =>
marketIndex ? pos.marketIndex === marketIndex : true
)
.reduce((pnl, marketPosition) => {
const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
return pnl.add(calculatePositionFundingPNL(market, marketPosition));
}, ZERO);
}
/**
* calculates TotalCollateral: collateral + unrealized pnl
* @returns : Precision QUOTE_PRECISION
*/
public getTotalCollateral(): BN {
return (
this.getUserAccount().collateral.add(this.getUnrealizedPNL(true)) ??
new BN(0)
);
}
/**
* calculates sum of position value across all positions
* @returns : Precision QUOTE_PRECISION
*/
getTotalPositionValue(): BN {
return this.getUserPositionsAccount().positions.reduce(
(positionValue, marketPosition) => {
const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
return positionValue.add(
calculateBaseAssetValue(market, marketPosition)
);
},
ZERO
);
}
/**
* calculates position value from closing 100%
* @returns : Precision QUOTE_PRECISION
*/
public getPositionValue(marketIndex: BN): BN {
const userPosition =
this.getUserPosition(marketIndex) || this.getEmptyPosition(marketIndex);
const market = this.clearingHouse.getMarket(userPosition.marketIndex);
return calculateBaseAssetValue(market, userPosition);
}
public getPositionSide(
currentPosition: Pick<UserPosition, 'baseAssetAmount'>
): PositionDirection | undefined {
if (currentPosition.baseAssetAmount.gt(ZERO)) {
return PositionDirection.LONG;
} else if (currentPosition.baseAssetAmount.lt(ZERO)) {
return PositionDirection.SHORT;
} else {
return undefined;
}
}
/**
* calculates average exit price for closing 100% of position
* @returns : Precision MARK_PRICE_PRECISION
*/
public getPositionEstimatedExitPriceAndPnl(
position: UserPosition,
amountToClose?: BN
): [BN, BN] {
const market = this.clearingHouse.getMarket(position.marketIndex);
const entryPrice = calculateEntryPrice(position);
if (amountToClose) {
if (amountToClose.eq(ZERO)) {
return [calculateMarkPrice(market), ZERO];
}
position = {
baseAssetAmount: amountToClose,
lastCumulativeFundingRate: position.lastCumulativeFundingRate,
marketIndex: position.marketIndex,
quoteAssetAmount: position.quoteAssetAmount,
} as UserPosition;
}
const baseAssetValue = calculateBaseAssetValue(market, position);
if (position.baseAssetAmount.eq(ZERO)) {
return [ZERO, ZERO];
}
const exitPrice = baseAssetValue
.mul(AMM_TO_QUOTE_PRECISION_RATIO)
.mul(MARK_PRICE_PRECISION)
.div(position.baseAssetAmount.abs());
const pnlPerBase = exitPrice.sub(entryPrice);
const pnl = pnlPerBase
.mul(position.baseAssetAmount)
.div(MARK_PRICE_PRECISION)
.div(AMM_TO_QUOTE_PRECISION_RATIO);
return [exitPrice, pnl];
}
/**
* calculates current user leverage across all positions
* @returns : Precision TEN_THOUSAND
*/
public getLeverage(): BN {
const totalCollateral = this.getTotalCollateral();
const totalPositionValue = this.getTotalPositionValue();
if (totalPositionValue.eq(ZERO) && totalCollateral.eq(ZERO)) {
return ZERO;
}
return totalPositionValue.mul(TEN_THOUSAND).div(totalCollateral);
}
/**
* calculates max allowable leverage exceeding hitting requirement category
* @params category {Initial, Partial, Maintenance}
* @returns : Precision TEN_THOUSAND
*/
public getMaxLeverage(
marketIndex: BN | number,
category: MarginCategory = 'Initial'
): BN {
const market = this.clearingHouse.getMarket(marketIndex);
let marginRatioCategory: number;
switch (category) {
case 'Initial':
marginRatioCategory = market.marginRatioInitial;
break;
case 'Maintenance':
marginRatioCategory = market.marginRatioMaintenance;
break;
case 'Partial':
marginRatioCategory = market.marginRatioPartial;
break;
default:
marginRatioCategory = market.marginRatioInitial;
break;
}
const maxLeverage = TEN_THOUSAND.mul(TEN_THOUSAND).div(
new BN(marginRatioCategory)
);
return maxLeverage;
}
/**
* calculates margin ratio: total collateral / |total position value|
* @returns : Precision TEN_THOUSAND
*/
public getMarginRatio(): BN {
const totalPositionValue = this.getTotalPositionValue();
if (totalPositionValue.eq(ZERO)) {
return BN_MAX;
}
return this.getTotalCollateral().mul(TEN_THOUSAND).div(totalPositionValue);
}
public canBeLiquidated(): [boolean, BN] {
const totalCollateral = this.getTotalCollateral();
const partialMaintenanceRequirement = this.getPartialMarginRequirement();
const marginRatio = this.getMarginRatio();
const canLiquidate = totalCollateral.lt(partialMaintenanceRequirement);
return [canLiquidate, marginRatio];
}
/**
* Checks if any user position cumulative funding differs from respective market cumulative funding
* @returns
*/
public needsToSettleFundingPayment(): boolean {
const marketsAccount = this.clearingHouse.getMarketsAccount();
for (const userPosition of this.getUserPositionsAccount().positions) {
if (userPosition.baseAssetAmount.eq(ZERO)) {
continue;
}
const market =
marketsAccount.markets[userPosition.marketIndex.toNumber()];
if (
market.amm.cumulativeFundingRateLong.eq(
userPosition.lastCumulativeFundingRate
) ||
market.amm.cumulativeFundingRateShort.eq(
userPosition.lastCumulativeFundingRate
)
) {
continue;
}
return true;
}
return false;
}
/**
* Calculate the liquidation price of a position, with optional parameter to calculate the liquidation price after a trade
* @param marketPosition
* @param positionBaseSizeChange // change in position size to calculate liquidation price for : Precision 10^13
* @param partial
* @returns Precision : MARK_PRICE_PRECISION
*/
public liquidationPrice(
marketPosition: Pick<UserPosition, 'marketIndex'>,
positionBaseSizeChange: BN = ZERO,
partial = false
): BN {
// solves formula for example canBeLiquidated below
/* example: assume BTC price is $40k (examine 10% up/down)
if 10k deposit and levered 10x short BTC => BTC up $400 means:
1. higher base_asset_value (+$4k)
2. lower collateral (-$4k)
3. (10k - 4k)/(100k + 4k) => 6k/104k => .0576
for 10x long, BTC down $400:
3. (10k - 4k) / (100k - 4k) = 6k/96k => .0625 */
const totalCollateral = this.getTotalCollateral();
// calculate the total position value ignoring any value from the target market of the trade
const totalPositionValueExcludingTargetMarket =
this.getTotalPositionValueExcludingMarket(marketPosition.marketIndex);
const currentMarketPosition =
this.getUserPosition(marketPosition.marketIndex) ||
this.getEmptyPosition(marketPosition.marketIndex);
const currentMarketPositionBaseSize = currentMarketPosition.baseAssetAmount;
const proposedBaseAssetAmount = currentMarketPositionBaseSize.add(
positionBaseSizeChange
);
// calculate position for current market after trade
const proposedMarketPosition: UserPosition = {
marketIndex: marketPosition.marketIndex,
baseAssetAmount: proposedBaseAssetAmount,
lastCumulativeFundingRate:
currentMarketPosition.lastCumulativeFundingRate,
quoteAssetAmount: new BN(0),
openOrders: new BN(0),
};
if (proposedBaseAssetAmount.eq(ZERO)) return new BN(-1);
const market = this.clearingHouse.getMarket(
proposedMarketPosition.marketIndex
);
const proposedMarketPositionValue = calculateBaseAssetValue(
market,
proposedMarketPosition
);
// total position value after trade
const totalPositionValueAfterTrade =
totalPositionValueExcludingTargetMarket.add(proposedMarketPositionValue);
const marginRequirementExcludingTargetMarket =
this.getUserPositionsAccount().positions.reduce(
(totalMarginRequirement, position) => {
if (!position.marketIndex.eq(marketPosition.marketIndex)) {
const market = this.clearingHouse.getMarket(position.marketIndex);
const positionValue = calculateBaseAssetValue(market, position);
const marketMarginRequirement = positionValue
.mul(
partial
? new BN(market.marginRatioPartial)
: new BN(market.marginRatioMaintenance)
)
.div(MARGIN_PRECISION);
totalMarginRequirement = totalMarginRequirement.add(
marketMarginRequirement
);
}
return totalMarginRequirement;
},
ZERO
);
const freeCollateralExcludingTargetMarket = totalCollateral.sub(
marginRequirementExcludingTargetMarket
);
// if the position value after the trade is less than free collateral, there is no liq price
if (
totalPositionValueAfterTrade.lte(freeCollateralExcludingTargetMarket) &&
proposedMarketPosition.baseAssetAmount.abs().gt(ZERO)
) {
return new BN(-1);
}
const marginRequirementAfterTrade =
marginRequirementExcludingTargetMarket.add(
proposedMarketPositionValue
.mul(
partial
? new BN(market.marginRatioPartial)
: new BN(market.marginRatioMaintenance)
)
.div(MARGIN_PRECISION)
);
const freeCollateralAfterTrade = totalCollateral.sub(
marginRequirementAfterTrade
);
const marketMaxLeverage = partial
? this.getMaxLeverage(proposedMarketPosition.marketIndex, 'Partial')
: this.getMaxLeverage(proposedMarketPosition.marketIndex, 'Maintenance');
let priceDelta;
if (proposedBaseAssetAmount.lt(ZERO)) {
priceDelta = freeCollateralAfterTrade
.mul(marketMaxLeverage) // precision is TEN_THOUSAND
.div(marketMaxLeverage.add(TEN_THOUSAND))
.mul(PRICE_TO_QUOTE_PRECISION)
.mul(AMM_RESERVE_PRECISION)
.div(proposedBaseAssetAmount);
} else {
priceDelta = freeCollateralAfterTrade
.mul(marketMaxLeverage) // precision is TEN_THOUSAND
.div(marketMaxLeverage.sub(TEN_THOUSAND))
.mul(PRICE_TO_QUOTE_PRECISION)
.mul(AMM_RESERVE_PRECISION)
.div(proposedBaseAssetAmount);
}
let markPriceAfterTrade;
if (positionBaseSizeChange.eq(ZERO)) {
markPriceAfterTrade = calculateMarkPrice(
this.clearingHouse.getMarket(marketPosition.marketIndex)
);
} else {
const direction = positionBaseSizeChange.gt(ZERO)
? PositionDirection.LONG
: PositionDirection.SHORT;
markPriceAfterTrade = calculateTradeSlippage(
direction,
positionBaseSizeChange.abs(),
this.clearingHouse.getMarket(marketPosition.marketIndex),
'base'
)[3]; // newPrice after swap
}
if (priceDelta.gt(markPriceAfterTrade)) {
return new BN(-1);
}
return markPriceAfterTrade.sub(priceDelta);
}
/**
* Calculates the estimated liquidation price for a position after closing a quote amount of the position.
* @param positionMarketIndex
* @param closeQuoteAmount
* @returns : Precision MARK_PRICE_PRECISION
*/
public liquidationPriceAfterClose(
positionMarketIndex: BN,
closeQuoteAmount: BN
): BN {
const currentPosition =
this.getUserPosition(positionMarketIndex) ||
this.getEmptyPosition(positionMarketIndex);
const closeBaseAmount = currentPosition.baseAssetAmount
.mul(closeQuoteAmount)
.div(currentPosition.quoteAssetAmount)
.add(
currentPosition.baseAssetAmount
.mul(closeQuoteAmount)
.mod(currentPosition.quoteAssetAmount)
)
.neg();
return this.liquidationPrice(
{
marketIndex: positionMarketIndex,
},
closeBaseAmount
);
}
/**
* Get the maximum trade size for a given market, taking into account the user's current leverage, positions, collateral, etc.
*
* To Calculate Max Quote Available:
*
* Case 1: SameSide
* => Remaining quote to get to maxLeverage
*
* Case 2: NOT SameSide && currentLeverage <= maxLeverage
* => Current opposite position x2 + remaining to get to maxLeverage
*
* Case 3: NOT SameSide && currentLeverage > maxLeverage && otherPositions - currentPosition > maxLeverage
* => strictly reduce current position size
*
* Case 4: NOT SameSide && currentLeverage > maxLeverage && otherPositions - currentPosition < maxLeverage
* => current position + remaining to get to maxLeverage
*
* @param targetMarketIndex
* @param tradeSide
* @returns tradeSizeAllowed : Precision QUOTE_PRECISION
*/
public getMaxTradeSizeUSDC(
targetMarketIndex: BN,
tradeSide: PositionDirection
): BN {
const currentPosition =
this.getUserPosition(targetMarketIndex) ||
this.getEmptyPosition(targetMarketIndex);
const targetSide = isVariant(tradeSide, 'short') ? 'short' : 'long';
const currentPositionSide = currentPosition?.baseAssetAmount.isNeg()
? 'short'
: 'long';
const targetingSameSide = !currentPosition
? true
: targetSide === currentPositionSide;
// add any position we have on the opposite side of the current trade, because we can "flip" the size of this position without taking any extra leverage.
const oppositeSizeValueUSDC = targetingSameSide
? ZERO
: this.getPositionValue(targetMarketIndex);
let maxPositionSize = this.getBuyingPower(targetMarketIndex);
if (maxPositionSize.gte(ZERO)) {
if (oppositeSizeValueUSDC.eq(ZERO)) {
// case 1 : Regular trade where current total position less than max, and no opposite position to account for
// do nothing
} else {
// case 2 : trade where current total position less than max, but need to account for flipping the current position over to the other side
maxPositionSize = maxPositionSize.add(
oppositeSizeValueUSDC.mul(new BN(2))
);
}
} else {
// current leverage is greater than max leverage - can only reduce position size
if (!targetingSameSide) {
const market = this.clearingHouse.getMarket(targetMarketIndex);
const marketPositionValue = this.getPositionValue(targetMarketIndex);
const totalCollateral = this.getTotalCollateral();
const marginRequirement = this.getInitialMarginRequirement();
const marginFreedByClosing = marketPositionValue
.mul(new BN(market.marginRatioInitial))
.div(MARGIN_PRECISION);
const marginRequirementAfterClosing =
marginRequirement.sub(marginFreedByClosing);
if (marginRequirementAfterClosing.gt(totalCollateral)) {
maxPositionSize = marketPositionValue;
} else {
const freeCollateralAfterClose = totalCollateral.sub(
marginRequirementAfterClosing
);
const buyingPowerAfterClose = freeCollateralAfterClose
.mul(this.getMaxLeverage(targetMarketIndex))
.div(TEN_THOUSAND);
maxPositionSize = marketPositionValue.add(buyingPowerAfterClose);
}
} else {
// do nothing if targetting same side
}
}
// subtract oneMillionth of maxPositionSize
// => to avoid rounding errors when taking max leverage
const oneMilli = maxPositionSize.div(QUOTE_PRECISION);
return maxPositionSize.sub(oneMilli);
}
// TODO - should this take the price impact of the trade into account for strict accuracy?
/**
* Returns the leverage ratio for the account after adding (or subtracting) the given quote size to the given position
* @param targetMarketIndex
* @param positionMarketIndex
* @param tradeQuoteAmount
* @returns leverageRatio : Precision TEN_THOUSAND
*/
public accountLeverageRatioAfterTrade(
targetMarketIndex: BN,
tradeQuoteAmount: BN,
tradeSide: PositionDirection
): BN {
const currentPosition =
this.getUserPosition(targetMarketIndex) ||
this.getEmptyPosition(targetMarketIndex);
let currentPositionQuoteAmount = this.getPositionValue(targetMarketIndex);
const currentSide =
currentPosition && currentPosition.baseAssetAmount.isNeg()
? PositionDirection.SHORT
: PositionDirection.LONG;
if (currentSide === PositionDirection.SHORT)
currentPositionQuoteAmount = currentPositionQuoteAmount.neg();
if (tradeSide === PositionDirection.SHORT)
tradeQuoteAmount = tradeQuoteAmount.neg();
const currentMarketPositionAfterTrade = currentPositionQuoteAmount
.add(tradeQuoteAmount)
.abs();
const totalPositionAfterTradeExcludingTargetMarket =
this.getTotalPositionValueExcludingMarket(targetMarketIndex);
const totalCollateral = this.getTotalCollateral();
if (totalCollateral.gt(ZERO)) {
const newLeverage = currentMarketPositionAfterTrade
.add(totalPositionAfterTradeExcludingTargetMarket)
.abs()
.mul(TEN_THOUSAND)
.div(totalCollateral);
return newLeverage;
} else {
return new BN(0);
}
}
/**
* Calculates how much fee will be taken for a given sized trade
* @param quoteAmount
* @returns feeForQuote : Precision QUOTE_PRECISION
*/
public calculateFeeForQuoteAmount(quoteAmount: BN): BN {
const feeStructure = this.clearingHouse.getStateAccount().feeStructure;
return quoteAmount
.mul(feeStructure.feeNumerator)
.div(feeStructure.feeDenominator);
}
/**
* Get the total position value, excluding any position coming from the given target market
* @param marketToIgnore
* @returns positionValue : Precision QUOTE_PRECISION
*/
private getTotalPositionValueExcludingMarket(marketToIgnore: BN): BN {
const currentMarketPosition =
this.getUserPosition(marketToIgnore) ||
this.getEmptyPosition(marketToIgnore);
let currentMarketPositionValueUSDC = ZERO;
if (currentMarketPosition) {
currentMarketPositionValueUSDC = this.getPositionValue(marketToIgnore);
}
return this.getTotalPositionValue().sub(currentMarketPositionValueUSDC);
}
public getClaimableCollateral(settlementState: SettlementStateAccount): BN {
return this.getSettledPositionValue()
.mul(
settlementState.collateralAvailableToClaim.sub(
this.getUserAccount().lastCollateralAvailableToClaim
)
)
.div(settlementState.totalSettlementValue);
}
public getSettledPositionValue(): BN {
return BN.max(
this.getUserAccount()
.collateral.add(
this.getUnrealizedFundingPNL().div(PRICE_TO_QUOTE_PRECISION)
)
.add(this.getSettledPositionsPNL()),
ZERO
);
}
public getSettledPositionsPNL(): BN {
return this.getUserPositionsAccount().positions.reduce(
(pnl, marketPosition) => {
const market = this.clearingHouse.getMarket(marketPosition.marketIndex);
return pnl.add(calculateSettledPositionPNL(market, marketPosition));
},
ZERO
);
}
public async estimateClaimableCollateral(): Promise<BN> {
const currentCollateralVaultBalance = new BN(
(
await this.clearingHouse.connection.getTokenAccountBalance(
this.clearingHouse.getStateAccount().collateralVault
)
).value.amount
);
const currentInsuranceVaultBalance = new BN(
(
await this.clearingHouse.connection.getTokenAccountBalance(
this.clearingHouse.getStateAccount().insuranceVault
)
).value.amount
);
const totalClaimableCollateral = currentCollateralVaultBalance.add(
currentInsuranceVaultBalance
);
const totalEstimatedSettlementValue =
await this.clearingHouse.getTotalSettlementSize();
const userSettledPositionValue = await this.getSettledPositionValue();
return totalClaimableCollateral
.mul(userSettledPositionValue)
.div(totalEstimatedSettlementValue);
}
} | the_stack |
module HubTests {
"use strict";
var HubSection = <typeof WinJS.UI.PrivateHubSection>WinJS.UI.HubSection;
var Hub = <typeof WinJS.UI.PrivateHub>WinJS.UI.Hub;
// This is the setup function that will be called at the beginning of each test function.
var hostId = "HubTests";
var hostSelector = "#" + hostId;
var HubUtils = HubTests.Utilities;
function InitTest(testHost, config) {
var control = testHost.querySelector(".win-hub").winControl;
LiveUnit.LoggingCore.logComment("Waiting for control...");
return HubUtils.waitForReady(control)().then(() => {
LiveUnit.LoggingCore.logComment("Verifying...");
HubUtils.verifyOrientation(control, config.orientation);
//use the control's current template if none was defined by config
HubUtils.verifySections(control, config.sectionsArray, config.headerTemplate || control.headerTemplate);
});
}
function LoadingStateChangedTest(testHost, config) {
var control = testHost.querySelector(".win-hub").winControl;
var i = 0;
var sectionsLoadedIndex = i;
var completeIndex = i;
var loadingIndex = i;
LiveUnit.Assert.areEqual(Hub.LoadingState.loading, control.loadingState, "Loading state should start in loading");
i++;
return HubUtils.waitForReady(control)().
then(function () {
completeIndex = i;
LiveUnit.Assert.isTrue(completeIndex > sectionsLoadedIndex, "Expecting complete to fire after sectionsLoaded event");
LiveUnit.Assert.areEqual(Hub.LoadingState.complete, control.loadingState, "Loading state should finish in complete");
}, function () {
LiveUnit.Assert.fail("An error was reported by waitForReady");
}, function () {
if (control.loadingState === Hub.LoadingState.sectionsLoaded) {
sectionsLoadedIndex = i;
LiveUnit.Assert.isTrue(sectionsLoadedIndex > loadingIndex, "Sections loaded Event should fire after loading event");
i++;
} else if (control.loadingState === Hub.LoadingState.loading) {
loadingIndex = i;
i++;
} else {
LiveUnit.Assert.fail("Unrecognized loading state: " + control.loadingState);
}
});
}
function RemoveFromDOMTest(testHost, config) {
return WinJS.Promise.timeout().then(function () {
var control = testHost.querySelector(".win-hub").winControl;
testHost.removeChild(control.element);
testHost.innerHTML = "";
HubUtils.insertHub(testHost, config);
return InitTest(testHost, config);
});
}
function RehydrationTest(testHost, config) {
var control = testHost.querySelector(".win-hub").winControl;
return HubUtils.waitForReady(control)().
then(function () {
//scrollable region
var scrollRange = HubUtils.getScrollRange(control);
var scrollMax = scrollRange.max;
var scrollMin = scrollRange.min;
var scrollDest = 0;
if (scrollMin < scrollMax) {
scrollDest = Math.floor(Math.random() * (scrollMax - scrollMin) + scrollMin);
}
control.scrollPosition = scrollDest;
LiveUnit.Assert.areEqual(scrollDest, control.scrollPosition);
//remove the hub, wait for a layout, then readd it
//this simulates what a navigation would do
testHost.removeChild(control.element);
testHost.innerHTML = "";
return WinJS.Promise.timeout().then(function () { return scrollDest; });
}).
then(function (scrollDest) {
testHost.appendChild(control.element);
control.scrollPosition = scrollDest;
LiveUnit.Assert.areEqual(scrollDest, control.scrollPosition);
HubUtils.verifySections(control, config.sectionsArray, config.headerTemplate || control.headerTemplate);
});
}
function SwapOrientationTest(testHost, config) {
var control = testHost.querySelector(".win-hub").winControl;
return HubUtils.waitForReady(control)().
then(function () {
HubUtils.verifyOrientation(control, config.orientation);
//update the internal representation
if (config.orientation === WinJS.UI.Orientation.vertical) {
config.orientation = WinJS.UI.Orientation.horizontal;
} else {
config.orientation = WinJS.UI.Orientation.vertical;
}
control.orientation = config.orientation;
return HubUtils.waitForReady(control)();
}).
then(function () {
HubUtils.verifyOrientation(control, config.orientation);
});
}
function HeaderInvokedTest(testHost, config) {
var control = testHost.querySelector(".win-hub").winControl;
return new WinJS.Promise(function (c, e, p) {
//grab a map of all headers elements
HubUtils.waitForReady(control)().then(function () {
var headerElements = HubUtils.getAllHeaderElements(control);
LiveUnit.LoggingCore.logComment(headerElements.length + " headers found");
if (headerElements.length > 0) {
var interactiveHeaderCount = 0;
control.addEventListener(Hub._EventName.headerInvoked, function (ev) {
interactiveHeaderCount--;
LiveUnit.Assert.isFalse(config.sectionsArray[ev.detail.index].isHeaderStatic, "Header element " + ev.detail.index + " not expected to be interactive");
});
for (var i = 0; i < headerElements.length; i++) {
var element = headerElements[i];
if (!config.sectionsArray[i].isHeaderStatic) {
LiveUnit.LoggingCore.logComment("Header #" + i + " is interactive!");
interactiveHeaderCount++;
}
element.firstElementChild.click();
}
LiveUnit.Assert.areEqual(0, interactiveHeaderCount, "A header's invoke event was not fired");
c();
} else {
LiveUnit.LoggingCore.logComment("No headers found in this configuration, skipping test");
c();
}
});
});
}
function SwapHeaderTemplateTest(testHost, config) {
var control = testHost.querySelector(".win-hub").winControl;
return new WinJS.Promise(function (c, e, p) {
function myCustomTemplate(item) {
var el = document.createElement("div");
el.textContent = "Test";
return el;
}
var oldTemplate;
HubUtils.waitForReady(control)().then(function () {
oldTemplate = control.headerTemplate;
control.headerTemplate = myCustomTemplate;
return HubUtils.waitForReady(control)();
}).then(function () {
HubUtils.verifySections(control, config.sectionsArray, myCustomTemplate);
control.headerTemplate = null;
//verify that the headerTemplate actually changes
LiveUnit.Assert.areNotEqual(myCustomTemplate, control.headerTemplate);
LiveUnit.Assert.areNotEqual(config.headerTemplate, control.headerTemplate);
return HubUtils.waitForReady(control)();
}).done(function () {
HubUtils.verifySections(control, config.sectionsArray, control.headerTemplate);
//reset the template back to match the input config
control.headerTemplate = oldTemplate;
c();
});
});
}
function SetSectionOnScreenTest(testHost, config) {
var control = testHost.querySelector(".win-hub").winControl;
var sectionsLength = config.sectionsArray.length;
function setAndVerifySectionOnScreen(control, sectionOnScreen) {
return new WinJS.Promise(function (c, e, p) {
control.sectionOnScreen = sectionOnScreen;
HubUtils.waitForReady(control)().done(function () {
function verifySectionOnScreen(control, expectedValue) {
var scrollRange = HubUtils.getScrollRange(control);
var surfaceSpacers = HubUtils.getSurfaceSpacers(control);
var isLTR = (getComputedStyle(control.element).direction === "ltr");
var sectionElement = control.element.querySelectorAll("." + HubSection._ClassName.hubSection)[expectedValue];
var sectionElementRect = sectionElement.getBoundingClientRect();
var viewportRect = control._viewportElement.getBoundingClientRect();
//either the sectionOnScreen was updated successfully or control scrolled as far as possible
if (expectedValue === control.sectionOnScreen) {
//when section on screen is updated successfully, the alignment needs to be correct
if (control.orientation === WinJS.UI.Orientation.horizontal) {
//TODO switch this for RTL
if (isLTR) {
LiveUnit.Assert.isTrue(Math.abs(surfaceSpacers.left + viewportRect.left - sectionElementRect.left) <= .002, "Distance is more than .002 px");
} else {
LiveUnit.Assert.isTrue(Math.abs(viewportRect.right - surfaceSpacers.right - sectionElementRect.right) <= .002, "Distance is more than .002 px");
}
} else {
//vertical Hub
LiveUnit.Assert.isTrue(Math.abs(surfaceSpacers.top + viewportRect.top - sectionElementRect.top) <= .002, "Distance is more than .002 px");
}
} else {
//else the control is scrolled as far as possible
LiveUnit.Assert.isTrue(control.scrollPosition === scrollRange.max || control.scrollPosition === scrollRange.min, "Scroll position should be at max or min");
if (control.orientation === WinJS.UI.Orientation.horizontal) {
if (isLTR) {
LiveUnit.Assert.isTrue(sectionElementRect.left >= surfaceSpacers.left + viewportRect.left, "Left edge should be on screen");
} else {
//RTL
LiveUnit.Assert.isTrue(sectionElementRect.right <= viewportRect.right - surfaceSpacers.right, "Right edge should be on screen");
}
} else { //orientation === WinJS.UI.Orientation.vertical
LiveUnit.Assert.isTrue(sectionElementRect.top >= surfaceSpacers.top + viewportRect.top, "Top edge should be on screen");
}
}
}
verifySectionOnScreen(control, sectionOnScreen);
c();
});
});
}
function iterateAllSections(control, currentSection, decreasing) {
if (currentSection < sectionsLength && currentSection >= 0) {
return setAndVerifySectionOnScreen(control, currentSection).then(function () {
return iterateAllSections(control, decreasing ? currentSection - 1 : currentSection + 1, decreasing);
});
}
}
return HubUtils.waitForReady(control)().
then(function () {
var currentSectionOnScreen = control.sectionOnScreen;
var currentScrollPos = control.scrollPosition;
control.sectionOnScreen = currentSectionOnScreen;
LiveUnit.Assert.areEqual(currentSectionOnScreen, control.sectionOnScreen, "Expecting control to not move");
LiveUnit.Assert.areEqual(currentScrollPos, control.scrollPosition, "Expecting control to not scroll");
return iterateAllSections(control, currentSectionOnScreen, false);
}).then(function () {
var currentSectionOnScreen = control.sectionOnScreen;
return iterateAllSections(control, currentSectionOnScreen, true);
});
}
function GetSectionOnScreenTest(testHost, config) {
var control = testHost.querySelector(".win-hub").winControl;
return HubUtils.waitForReady(control)().
then(function () {
var currentScrollPosition = 42; //starting scroll position for test
var increment = 11; //how far to increment on each iteration
var scrollRange = HubUtils.getScrollRange(control);
var index = HubUtils.findCurrentSectionOnScreen(control);
LiveUnit.Assert.areEqual(index, control.sectionOnScreen);
function loop() {
return new WinJS.Promise(function (c, e, p) {
//set scroll position
currentScrollPosition = Math.min(scrollRange.max, currentScrollPosition + increment);
control.scrollPosition = currentScrollPosition;
WinJS.Utilities._setImmediate(function () {
//hit test for sectionOnScreen
var index = HubUtils.findCurrentSectionOnScreen(control);
LiveUnit.Assert.areEqual(index, control.sectionOnScreen);
c();
});
});
}
function continueCondition() {
return WinJS.Promise.wrap(currentScrollPosition < scrollRange.max);
}
//loop
return Helper.asyncWhile(continueCondition, loop);
});
}
function GetScrollPosTest(testHost, config) {
var control = testHost.querySelector(".win-hub").winControl;
return HubUtils.waitForReady(control)().
then(function () {
var scrollProperty = control.orientation === WinJS.UI.Orientation.horizontal ? "scrollLeft" : "scrollTop";
var scrollRange = HubUtils.getScrollRange(control);
var scroller = control.element.firstElementChild;
var currentScrollPosition = WinJS.Utilities.getScrollPosition(scroller)[scrollProperty];
var increment = 11;
function loop() {
return new WinJS.Promise(function (c) {
currentScrollPosition = Math.min(currentScrollPosition + increment, scrollRange.max);
var newPosition: any = {};
newPosition[scrollProperty] = currentScrollPosition;
WinJS.Utilities.setScrollPosition(scroller, newPosition);
Helper.waitForScroll(control._viewportElement).then(function () {
LiveUnit.Assert.areEqual(currentScrollPosition, control.scrollPosition);
c();
});
});
}
function continueCondition() {
return WinJS.Promise.wrap(currentScrollPosition < scrollRange.max);
}
return Helper.asyncWhile(continueCondition, loop);
});
}
function SetScrollPosTest(testHost, config) {
var control = testHost.querySelector(".win-hub").winControl;
return HubUtils.waitForReady(control)().
then(function () {
var scrollProperty = control.orientation === WinJS.UI.Orientation.horizontal ? "scrollLeft" : "scrollTop";
var scrollRange = HubUtils.getScrollRange(control);
var scroller = control.element.firstElementChild;
var currentScrollPosition = control.scrollPosition;
var increment = 11;
function loop() {
return new WinJS.Promise(function (c) {
currentScrollPosition = Math.min(currentScrollPosition + increment, scrollRange.max);
control.scrollPosition = currentScrollPosition;
Helper.waitForScroll(control._viewportElement).then(function () {
LiveUnit.Assert.areEqual(currentScrollPosition, WinJS.Utilities.getScrollPosition(scroller)[scrollProperty]);
c();
});
});
}
function continueCondition() {
return WinJS.Promise.wrap(currentScrollPosition < scrollRange.max);
}
return Helper.asyncWhile(continueCondition, loop);
});
}
function SwapSectionsTest(testHost, config) {
var control = testHost.querySelector(".win-hub").winControl;
var newSections = [new HubSection()];
var oldSections = control.sections;
return HubUtils.waitForReady(control)().
then(function () {
control.sections = new WinJS.Binding.List(newSections);
return HubUtils.waitForReady(control)();
}).
then(function () {
HubUtils.verifySections(control, newSections, control.headerTemplate);
control.sections = oldSections;
return HubUtils.waitForReady(control)();
}).
then(function () {
HubUtils.verifySections(control, oldSections.slice(), control.headerTemplate);
});
}
function DeleteAllTest(testHost, config) {
var control = testHost.querySelector(".win-hub").winControl;
return HubUtils.waitForReady(control)().
then(function () {
control.sections.length = 0;
return WinJS.Promise.timeout(WinJS.UI._animationTimeAdjustment(3000));
}).
then(function () {
LiveUnit.Assert.areEqual(0, document.body.querySelectorAll('progress').length, "Expecting no progress indicators in DOM");
});
}
export class BasicTests {
setUp() {
LiveUnit.LoggingCore.logComment("In setup");
var newNode = document.createElement("div");
newNode.id = hostId;
newNode.style.minHeight = "1024px";
newNode.style.minWidth = "768px";
newNode.style.height = "100%";
newNode.style.width = "100%";
document.body.appendChild(newNode);
}
tearDown() {
LiveUnit.LoggingCore.logComment("In tearDown");
var element = document.getElementById(hostId);
if (element) {
WinJS.Utilities.disposeSubTree(element);
document.body.removeChild(element);
}
}
// Test functions
}
HubUtils.test(BasicTests.prototype, hostSelector, "Init", InitTest, { priority: 0 });
HubUtils.test(BasicTests.prototype, hostSelector, "LoadingStateChanged", LoadingStateChangedTest), { priority: 0 };
HubUtils.test(BasicTests.prototype, hostSelector, "RemoveFromDOMTest", RemoveFromDOMTest, { priority: 0 });
HubUtils.test(BasicTests.prototype, hostSelector, "RehydrationTest", RehydrationTest, { priority: 0 });
HubUtils.test(BasicTests.prototype, hostSelector, "SwapOrientation", SwapOrientationTest, { priority: 0 });
HubUtils.test(BasicTests.prototype, hostSelector, "SwapHeaderTemplateTest", SwapHeaderTemplateTest, { priority: 0 });
HubUtils.test(BasicTests.prototype, hostSelector, "HeaderInvokedTest", HeaderInvokedTest, { priority: 0 });
HubUtils.test(BasicTests.prototype, hostSelector, "SetSectionOnScreenTest", SetSectionOnScreenTest, { priority: 0 });
HubUtils.test(BasicTests.prototype, hostSelector, "GetSectionOnScreenTest", GetSectionOnScreenTest, { priority: 0 });
HubUtils.test(BasicTests.prototype, hostSelector, "GetScrollPosTest", GetScrollPosTest, { priority: 0 });
HubUtils.test(BasicTests.prototype, hostSelector, "SetScrollPosTest", SetScrollPosTest, { priority: 0 });
HubUtils.test(BasicTests.prototype, hostSelector, "SwapSectionsTest", SwapSectionsTest, { priority: 0 });
HubUtils.test(BasicTests.prototype, hostSelector, "DeleteAll", DeleteAllTest, { priority: 1 });
}
LiveUnit.registerTestClass("HubTests.BasicTests"); | the_stack |
import { ActionSetState, ActionState } from '@aardvarkxr/aardvark-shared';
import { Action, InputInfo } from '@aardvarkxr/aardvark-shared';
import { ActionType, InputProcessor, twoHandBinding, InteractionProfile, Input, ActionSet, Device, InputState } from '@aardvarkxr/aardvark-shared';
jest.useFakeTimers();
beforeEach( async() =>
{
} );
afterEach( () =>
{
} );
export let k_actionSets: ActionSet[] =
[
{
name: "default",
localizedName: "Default",
suppressAppBindings: false,
actions:
[
{
name: "showRay",
localizedName: "Show Grab Ray",
type: ActionType.Boolean,
bindings: twoHandBinding( InteractionProfile.IndexController, Input.TriggerTouch )
}
]
},
{
name: "interact",
localizedName: "Grab and Click",
suppressAppBindings: true,
actions:
[
{
name: "grab",
localizedName: "Grab and Click",
type: ActionType.Boolean,
bindings: twoHandBinding( InteractionProfile.IndexController, Input.Trigger )
},
{
name: "menu",
localizedName: "Context Menu",
type: ActionType.Boolean,
bindings: twoHandBinding( InteractionProfile.IndexController, Input.A )
},
{
name: "floattest",
localizedName: "Context Menu",
type: ActionType.Float,
bindings: twoHandBinding( InteractionProfile.IndexController, Input.A )
},
{
name: "vector2test",
localizedName: "Context Menu",
type: ActionType.Vector2,
bindings: twoHandBinding( InteractionProfile.IndexController, Input.A )
}
]
},
];
function getActionsFromSet( actionSetName: string ) : Action[]
{
for( let as of k_actionSets )
{
if( as.name == actionSetName )
{
return as.actions;
}
}
return null;
}
function defaultState()
{
let state: InputState =
{
results:
{
default:
{
showRay :
{
left:
{
active: true,
value: false,
},
right:
{
active: true,
value: false,
}
}
},
interact:
{
grab :
{
left:
{
active: true,
value: false,
},
right:
{
active: true,
value: false,
}
},
menu :
{
left:
{
active: true,
value: false,
},
right:
{
active: true,
value: false,
}
},
floattest :
{
left:
{
active: true,
value: 0,
},
right:
{
active: true,
value: 0,
}
},
vector2test :
{
left:
{
active: true,
value: [ 0, 0 ],
},
right:
{
active: true,
value: [ 0, 0],
}
}
}
}
};
return state;
}
function filterStateForActiveActionSets( state: InputState, info: InputInfo )
{
let out: InputState = { results: {} };
for( let activeSet of info.activeActionSets )
{
let outSet: ActionSetState = { };
let actions = getActionsFromSet( activeSet.actionSetName );
for( let action of actions )
{
let outAction: ActionState< boolean | number | [ number, number ] > = {};
if( typeof activeSet.topLevelPaths == "object" && activeSet.topLevelPaths.length == 0)
{
throw new Error( "topLevelPaths can't be an empty array" );
}
let devicesWithDefaults = activeSet.topLevelPaths ?? [ Device.Left, Device.Right ];
if( devicesWithDefaults.includes( Device.Left ) )
{
outAction.left = state.results[ activeSet.actionSetName ][ action.name ].left;
}
if( devicesWithDefaults.includes( Device.Right ) )
{
outAction.right = state.results[ activeSet.actionSetName ][ action.name ].right;
}
outSet[ action.name ] = outAction;
}
out.results[ activeSet.actionSetName ] = outSet;
}
return out;
}
describe( "InputProcessor ", () =>
{
it( "boolean with values", async () =>
{
let ip = new InputProcessor( k_actionSets );
let rcb = 0;
let fcb = 0;
ip.registerBooleanCallbacks("default", "showRay", Device.Left, () => rcb++, () => fcb++ );
let state = defaultState();
ip.TEST_UpdateState( state );
expect( rcb ).toBe( 0 );
expect( fcb ).toBe( 0 );
state.results.default.showRay.left.value = true;
ip.TEST_UpdateState( state );
expect( rcb ).toBe( 1 );
expect( fcb ).toBe( 0 );
ip.TEST_UpdateState( state );
expect( rcb ).toBe( 1 );
expect( fcb ).toBe( 0 );
state.results.default.showRay.left.value = false;
ip.TEST_UpdateState( state );
expect( rcb ).toBe( 1 );
expect( fcb ).toBe( 1 );
state.results.default.showRay.left.value = true;
ip.TEST_UpdateState( state );
state.results.default.showRay.left.value = false;
ip.TEST_UpdateState( state );
state.results.default.showRay.left.value = true;
ip.TEST_UpdateState( state );
state.results.default.showRay.left.value = false;
ip.TEST_UpdateState( state );
state.results.default.showRay.left.value = true;
ip.TEST_UpdateState( state );
state.results.default.showRay.left.value = false;
ip.TEST_UpdateState( state );
expect( rcb ).toBe( 4 );
expect( fcb ).toBe( 4 );
});
it( "boolean with undefined", async () =>
{
let ip = new InputProcessor( k_actionSets );
let rcb = 0;
let fcb = 0;
ip.registerBooleanCallbacks("default", "showRay", Device.Left, () => rcb++, () => fcb++ );
let state = defaultState();
delete state.results.default;
ip.TEST_UpdateState( state );
expect( rcb ).toBe( 0 );
expect( fcb ).toBe( 0 );
state.results.default = { showRay: { left: { value : true, active: true } } };
ip.TEST_UpdateState( state );
expect( rcb ).toBe( 1 );
expect( fcb ).toBe( 0 );
ip.TEST_UpdateState( state );
expect( rcb ).toBe( 1 );
expect( fcb ).toBe( 0 );
state.results.default.showRay.left.value = false;
ip.TEST_UpdateState( state );
expect( rcb ).toBe( 1 );
expect( fcb ).toBe( 1 );
state.results.default.showRay.left.value = true;
ip.TEST_UpdateState( state );
delete state.results.default;
ip.TEST_UpdateState( state );
expect( rcb ).toBe( 2 );
expect( fcb ).toBe( 2 );
});
it( "float with values", async () =>
{
let ip = new InputProcessor( k_actionSets );
let lastFloat:number;
let calls = 0;
ip.registerFloatCallback("interact", "floattest", Device.Left,
( o: number, n: number ) =>
{
lastFloat = n;
calls++;
} );
let state = defaultState();
ip.TEST_UpdateState( state );
expect( lastFloat ).toBeUndefined();
expect( calls ).toBe( 0 );
state.results.interact.floattest.left.value = 0.47;
ip.TEST_UpdateState( state );
expect( lastFloat ).toBe( 0.47 );
expect( calls ).toBe( 1 );
ip.TEST_UpdateState( state );
expect( lastFloat ).toBe( 0.47 );
expect( calls ).toBe( 1 );
state.results.interact.floattest.left.value = 0;
ip.TEST_UpdateState( state );
expect( lastFloat ).toBe( 0 );
expect( calls ).toBe( 2 );
});
it( "vector2 with values", async () =>
{
let ip = new InputProcessor( k_actionSets );
let lastValue: [ number, number ];
let calls = 0;
ip.registerVector2Callback("interact", "vector2test", Device.Left,
( o: [ number, number ], n: [ number, number ] ) =>
{
lastValue = n;
calls++;
} );
let state = defaultState();
ip.TEST_UpdateState( state );
expect( lastValue ).toBeUndefined();
expect( calls ).toBe( 0 );
state.results.interact.vector2test.left.value = [ 0.147, -0.23 ];
ip.TEST_UpdateState( state );
expect( lastValue[0] ).toBe( 0.147 );
expect( lastValue[1] ).toBe( -0.23 );
expect( calls ).toBe( 1 );
ip.TEST_UpdateState( state );
expect( lastValue[0] ).toBe( 0.147 );
expect( lastValue[1] ).toBe( -0.23 );
expect( calls ).toBe( 1 );
state.results.interact.vector2test.left.value = [ 0, 0 ];
ip.TEST_UpdateState( state );
expect( lastValue[0] ).toBe( 0 );
expect( lastValue[1] ).toBe( 0 );
expect( calls ).toBe( 2 );
});
it( "action set registration", async () =>
{
let state = defaultState();
// set everything to true and let action set active state per device control what callbacks we get
state.results.default.showRay.left.value = true;
state.results.interact.grab.left.value = true;
state.results.interact.menu.left.value = true;
state.results.interact.floattest.left.value = 0.47;
state.results.interact.vector2test.left.value = [ 0.123, 0.456 ];
state.results.default.showRay.right.value = true;
state.results.interact.grab.right.value = true;
state.results.interact.menu.right.value = true;
state.results.interact.floattest.right.value = 0.47;
state.results.interact.vector2test.right.value = [ 0.123, 0.456 ];
let ip = new InputProcessor( k_actionSets, 1, ( info: InputInfo ) =>
{
return filterStateForActiveActionSets(
JSON.parse( JSON.stringify( state ) ) as InputState, info );
} );
let rcbShowRay = 0;
let fcbShowRay = 0;
ip.registerBooleanCallbacks("default", "showRay", Device.Left, () => rcbShowRay++, () => fcbShowRay++ );
let rcbGrab = 0;
let fcbGrab = 0;
ip.registerBooleanCallbacks("interact", "grab", Device.Right, () => rcbGrab++, () => fcbGrab++ );
// advance the timer, but it shouldn't be registered yet
jest.advanceTimersToNextTimer();
expect( rcbShowRay ).toBe( 0 );
expect( fcbShowRay ).toBe( 0 );
expect( rcbGrab ).toBe( 0 );
expect( fcbGrab ).toBe( 0 );
ip.activateActionSet( "default" );
jest.advanceTimersToNextTimer();
// after initial activation, the callback won't be called
expect( rcbShowRay ).toBe( 0 );
expect( fcbShowRay ).toBe( 0 );
state.results.default.showRay.left.value = false;
jest.advanceTimersToNextTimer();
// still nothing because the release is suppressed too
expect( rcbShowRay ).toBe( 0 );
expect( fcbShowRay ).toBe( 0 );
state.results.default.showRay.left.value = true;
jest.advanceTimersToNextTimer();
expect( rcbShowRay ).toBe( 1 );
expect( fcbShowRay ).toBe( 0 );
ip.deactivateActionSet( "default" );
jest.advanceTimersToNextTimer();
expect( rcbShowRay ).toBe( 1 );
expect( fcbShowRay ).toBe( 1 );
ip.activateActionSet( "interact", Device.Left );
jest.advanceTimersToNextTimer();
expect( rcbShowRay ).toBe( 1 );
expect( fcbShowRay ).toBe( 1 );
expect( rcbGrab ).toBe( 0 ); // these are 0 because the callback is on the right
expect( fcbGrab ).toBe( 0 );
ip.activateActionSet( "interact", Device.Right );
jest.advanceTimersToNextTimer();
expect( rcbGrab ).toBe( 0 ); // still 0 because of suppression
expect( fcbGrab ).toBe( 0 );
state.results.interact.grab.right.value = false;
jest.advanceTimersToNextTimer();
state.results.interact.grab.right.value = true;
jest.advanceTimersToNextTimer();
expect( rcbShowRay ).toBe( 1 );
expect( fcbShowRay ).toBe( 1 );
expect( rcbGrab ).toBe( 1 );
expect( fcbGrab ).toBe( 0 );
ip.deactivateActionSet( "interact", Device.Left );
jest.advanceTimersToNextTimer();
expect( rcbShowRay ).toBe( 1 );
expect( fcbShowRay ).toBe( 1 );
expect( rcbGrab ).toBe( 1 );
expect( fcbGrab ).toBe( 0 );
ip.deactivateActionSet( "interact", Device.Right );
jest.advanceTimersToNextTimer();
// release is 1 because we don't suppress the release when an action set is deactivated
expect( rcbShowRay ).toBe( 1 );
expect( fcbShowRay ).toBe( 1 );
expect( rcbGrab ).toBe( 1 );
expect( fcbGrab ).toBe( 1 );
ip.activateActionSet( "interact", [ Device.Left, Device.Right ] );
jest.advanceTimersToNextTimer();
state.results.interact.grab.right.value = false;
jest.advanceTimersToNextTimer();
state.results.interact.grab.right.value = true;
jest.advanceTimersToNextTimer();
expect( rcbShowRay ).toBe( 1 );
expect( fcbShowRay ).toBe( 1 );
expect( rcbGrab ).toBe( 2 );
expect( fcbGrab ).toBe( 1 );
ip.deactivateActionSet( "interact" );
jest.advanceTimersToNextTimer();
expect( rcbShowRay ).toBe( 1 );
expect( fcbShowRay ).toBe( 1 );
expect( rcbGrab ).toBe( 2 );
expect( fcbGrab ).toBe( 2 );
});
} ); | the_stack |
import { DummyError, Throwable } from "funfix-core"
import * as assert from "./asserts"
import {
Scheduler,
GlobalScheduler,
TestScheduler,
Duration,
ExecutionModel
} from "../../src/"
describe("GlobalScheduler", () => {
it("Scheduler.global.get() instanceof GlobalScheduler", () => {
assert.ok(Scheduler.global.get() instanceof GlobalScheduler)
})
it("executes stuff asynchronously with setImmediate", () => {
const s = new GlobalScheduler(true)
let wasExecuted = false
const p = new Promise(resolve => {
s.executeAsync(() => {
wasExecuted = true
resolve(1)
})
assert.not(wasExecuted)
})
assert.not(wasExecuted)
return p.then(r => {
assert.equal(r, 1)
assert.ok(wasExecuted)
})
})
it("executes stuff asynchronously with setTimeout", () => {
const s = new GlobalScheduler()
assert.not((s as any)._useSetImmediate)
let wasExecuted = false
const p = new Promise(resolve => {
s.executeAsync(() => {
wasExecuted = true
resolve(1)
})
assert.not(wasExecuted)
})
assert.not(wasExecuted)
return p.then(r => {
assert.equal(r, 1)
assert.ok(wasExecuted)
})
})
it("executes stuff synchronous", () => {
const s = new GlobalScheduler()
let count = 0
const loop = (n: number) => {
if (n > 0) s.trampoline(() => loop(n - 1))
count += 1
}
loop(5000)
assert.equal(count, 5001)
})
it("currentTimeMillis", () => {
const now = Date.now()
const time = Scheduler.global.get().currentTimeMillis()
assert.ok(time >= now)
})
function testErrorReporting(f: (ec: Scheduler, r: () => void) => void): () => Promise<void> {
return () => {
const dummy = new DummyError("dummy")
let reported: any = null
const p = new Promise<void>((resolve, _) => {
const ec = new GlobalScheduler(true, ExecutionModel.global.get(),
(r: any) => {
reported = r
resolve(undefined)
})
f(ec, () => { throw dummy })
})
return p.then(_ => {
assert.ok(reported, "reported != null")
assert.equal(reported.message, "dummy")
})
}
}
it("reports errors with trampoline",
testErrorReporting((ec, r) => ec.trampoline(r))
)
it("reports errors with executeAsync",
testErrorReporting((ec, r) => ec.executeAsync(r))
)
it("reports errors with scheduleOnce",
testErrorReporting((ec, r) => ec.scheduleOnce(1, r))
)
it("executes async with setImmediate", () => {
const ec = new GlobalScheduler(true)
const p = new Promise<boolean>((resolve, _) => {
ec.executeAsync(() => resolve(true))
})
return p.then(r => assert.ok(r))
})
it("executes async with setTimeout", () => {
const ec = new GlobalScheduler(false)
const p = new Promise<boolean>((resolve, _) => {
ec.executeAsync(() => resolve(true))
})
return p.then(r => assert.ok(r))
})
it("schedule with delay", () => {
const s = Scheduler.global.get()
let finishedAt = 0
const p = new Promise(resolve => {
s.scheduleOnce(50, () => {
finishedAt = s.currentTimeMillis()
resolve(1)
})
})
const now = s.currentTimeMillis()
return p.then(r => {
assert.equal(r, 1)
assert.ok(finishedAt - now >= 10)
})
})
it("schedule with delay should be cancelable", () => {
const s = Scheduler.global.get()
let finishedAt = 0
const ref = s.scheduleOnce(0, () => {
finishedAt = s.currentTimeMillis()
})
const p = new Promise(resolve => {
s.scheduleOnce(10, () => resolve(1))
})
ref.cancel()
return p.then(r => {
assert.equal(r, 1)
assert.equal(finishedAt, 0)
})
})
it("scheduleWithFixedDelay(number, number)", () => {
const s = Scheduler.global.get()
let times = 0
const ref = s.scheduleWithFixedDelay(0, 1, () => { times += 1 })
const p = new Promise(resolve => {
s.scheduleOnce(100, () => { ref.cancel(); resolve(1) })
})
return p.then(r => {
assert.equal(r, 1)
assert.ok(times >= 2)
})
})
it("scheduleWithFixedDelay(Duration, Duration)", () => {
const s = Scheduler.global.get()
let times = 0
const ref = s.scheduleWithFixedDelay(
Duration.millis(0),
Duration.millis(1),
() => { times += 1 }
)
const p = new Promise(resolve => {
s.scheduleOnce(100, () => { ref.cancel(); resolve(1) })
})
return p.then(r => {
assert.equal(r, 1)
assert.ok(times >= 2)
})
})
it("scheduleAtFixedRate(number, number)", () => {
const s = Scheduler.global.get()
let times = 0
const ref = s.scheduleAtFixedRate(0, 1, () => { times += 1 })
const p = new Promise(resolve => {
s.scheduleOnce(100, () => { ref.cancel(); resolve(1) })
})
return p.then(r => {
assert.equal(r, 1)
assert.ok(times >= 2)
})
})
it("scheduleAtFixedRate(Duration, Duration)", () => {
const s = Scheduler.global.get()
let times = 0
const ref = s.scheduleAtFixedRate(
Duration.millis(0),
Duration.millis(1),
() => { times += 1 }
)
const p = new Promise(resolve => {
s.scheduleOnce(100, () => { ref.cancel(); resolve(1) })
})
return p.then(r => {
assert.equal(r, 1)
assert.ok(times >= 2)
})
})
it("executionModel", () => {
const s = Scheduler.global.get()
assert.equal(s.executionModel, ExecutionModel.global.get())
const s2 = s.withExecutionModel(ExecutionModel.synchronous())
assert.equal(s2.executionModel.type, "synchronous")
assert.equal(s2.executionModel.recommendedBatchSize, 1 << 30)
const s3 = s.withExecutionModel(ExecutionModel.alwaysAsync())
assert.equal(s3.executionModel.type, "alwaysAsync")
assert.equal(s3.executionModel.recommendedBatchSize, 1)
const s4 = s.withExecutionModel(ExecutionModel.batched())
assert.equal(s4.executionModel.type, "batched")
assert.equal(s4.executionModel.recommendedBatchSize, 128)
const s5 = s.withExecutionModel(ExecutionModel.batched(200))
assert.equal(s5.executionModel.type, "batched")
assert.equal(s5.executionModel.recommendedBatchSize, 256)
})
})
describe("TestScheduler", () => {
it("executes random tasks in once batch", () => {
const s = new TestScheduler()
const count = 2000
let effect = 0
for (let i = 0; i < count; i++) {
const delay = Math.floor(Math.random() * 10) * 1000
if (delay === 0 && Math.floor(Math.random() * 10) % 2 === 0) {
s.executeAsync(() => { effect += 1 })
} else {
s.scheduleOnce(delay, () => { effect += 1 })
}
}
assert.equal(effect, 0)
assert.equal(s.tick(Duration.seconds(10)), count)
assert.equal(effect, count)
assert.not(s.hasTasksLeft())
})
it("executes random tasks in separate batches", () => {
const s = new TestScheduler()
const count = 2000
let effect = 0
for (let i = 0; i < count; i++) {
const delay = Math.floor(Math.random() * 10) * 1000
if (delay === 0 && Math.floor(Math.random() * 10) % 2 === 0) {
s.executeAsync(() => { effect += 1 })
} else {
s.scheduleOnce(delay, () => { effect += 1 })
}
}
assert.equal(effect, 0)
let executed = 0
for (let i = 0; i < 10; i++) executed += s.tick(Duration.seconds(1))
assert.equal(executed, count)
assert.equal(effect, count)
assert.not(s.hasTasksLeft())
})
it("nested execution", () => {
const s = new TestScheduler()
let effect = 0
s.executeAsync(() => {
effect += 1
s.executeAsync(() => {
s.executeAsync(() => { effect += 10 })
effect = effect * 2
})
})
assert.equal(effect, 0)
assert.equal(s.tick(), 3)
assert.equal(effect, 2 + 10)
})
it("nested scheduleOnce", () => {
const s = new TestScheduler()
let effect = 0
s.scheduleOnce(Duration.seconds(4), () => {
effect = effect * 2
})
s.scheduleOnce(1000, () => {
effect += 1
s.scheduleOnce(1000, () => {
s.scheduleOnce(1000, () => { effect += 10 })
effect = effect * 2
})
})
assert.equal(effect, 0)
assert.equal(s.tick(), 0)
assert.equal(s.tick(Duration.seconds(1)), 1)
assert.equal(effect, 1)
assert.ok(s.hasTasksLeft())
assert.equal(s.tick(Duration.seconds(1)), 1)
assert.equal(effect, 2)
assert.ok(s.hasTasksLeft())
assert.equal(s.tick(Duration.seconds(1)), 1)
assert.equal(effect, 2 + 10)
assert.ok(s.hasTasksLeft())
assert.equal(s.tick(Duration.seconds(1)), 1)
assert.equal(effect, (2 + 10) * 2)
assert.not(s.hasTasksLeft())
})
it("executes stuff synchronous", () => {
const s = new TestScheduler()
let count = 0
const loop = (n: number) => {
if (n > 0) s.trampoline(() => loop(n - 1))
count += 1
}
loop(5000)
assert.equal(count, 5001)
})
it("trampoline reports errors", () => {
const s = new TestScheduler()
let errorThrown = null
let triggered = false
s.trampoline(() => {
s.trampoline(() => { triggered = true })
// tslint:disable-next-line:no-string-throw
throw "dummy"
})
assert.equal(s.triggeredFailures().pop(), "dummy")
assert.ok(triggered)
})
it("schedule with delay should be cancelable", () => {
const s = new TestScheduler()
let effect = 0
s.executeAsync(() => { effect += 1 })
s.scheduleOnce(Duration.seconds(1), () => { effect += 1 })
const ref = s.scheduleOnce(Duration.seconds(2), () => { effect += 1 })
s.scheduleOnce(Duration.seconds(3), () => { effect += 1 })
ref.cancel()
assert.equal(s.tick(), 1)
assert.equal(s.tick(1000), 1)
assert.equal(s.tick(1000), 0)
assert.equal(s.tick(1000), 1)
assert.not(s.hasTasksLeft())
assert.equal(effect, 3)
assert.equal(s.currentTimeMillis(), 3000)
})
it("scheduleWithFixedDelay(number, number)", () => {
const s = new TestScheduler()
let times = 0
const ref = s.scheduleWithFixedDelay(1000, 2000, () => { times += 1 })
s.tick()
assert.equal(times, 0)
s.tick(1000)
assert.equal(times, 1)
s.tick(1000)
assert.equal(times, 1)
s.tick(1000)
assert.equal(times, 2)
s.tick(2000)
assert.equal(times, 3)
ref.cancel()
assert.not(s.hasTasksLeft())
s.tick(2000)
assert.equal(times, 3)
assert.equal(s.currentTimeMillis(), 7000)
})
it("scheduleWithFixedDelay(Duration, Duration)", () => {
const s = new TestScheduler()
let times = 0
const ref = s.scheduleWithFixedDelay(Duration.seconds(1), Duration.seconds(2), () => { times += 1 })
s.tick()
assert.equal(times, 0)
s.tick(1000)
assert.equal(times, 1)
s.tick(1000)
assert.equal(times, 1)
s.tick(1000)
assert.equal(times, 2)
s.tick(2000)
assert.equal(times, 3)
ref.cancel()
assert.not(s.hasTasksLeft())
s.tick(2000)
assert.equal(times, 3)
assert.equal(s.currentTimeMillis(), 7000)
})
it("scheduleAtFixedRate(number, number)", () => {
const s = new TestScheduler()
let times = 0
const ref = s.scheduleAtFixedRate(1000, 2000, () => { times += 1 })
s.tick()
assert.equal(times, 0)
s.tick(1000)
assert.equal(times, 1)
s.tick(1000)
assert.equal(times, 1)
s.tick(1000)
assert.equal(times, 2)
s.tick(2000)
assert.equal(times, 3)
ref.cancel()
assert.not(s.hasTasksLeft())
s.tick(2000)
assert.equal(times, 3)
assert.equal(s.currentTimeMillis(), 7000)
})
it("scheduleAtFixedRate(Duration, Duration)", () => {
const s = new TestScheduler()
let times = 0
const ref = s.scheduleAtFixedRate(Duration.seconds(1), Duration.seconds(2), () => { times += 1 })
s.tick()
assert.equal(times, 0)
s.tick(1000)
assert.equal(times, 1)
s.tick(1000)
assert.equal(times, 1)
s.tick(1000)
assert.equal(times, 2)
s.tick(2000)
assert.equal(times, 3)
ref.cancel()
assert.not(s.hasTasksLeft())
s.tick(2000)
assert.equal(times, 3)
})
it("errors get captured", () => {
let errors: Throwable[] = []
const s = new TestScheduler(err => errors.push(err))
const dummy = new DummyError("dummy")
s.executeAsync(() => { throw dummy })
s.executeAsync(() => { throw dummy })
s.tick()
assert.equal(errors.length, 2)
assert.equal(errors[0], dummy)
assert.equal(errors[1], dummy)
assert.equal(s.triggeredFailures().length, 2)
assert.equal(s.triggeredFailures()[0], dummy)
assert.equal(s.triggeredFailures()[1], dummy)
})
it("executionModel", () => {
const s = new TestScheduler()
assert.equal(s.executionModel, ExecutionModel.synchronous())
const s2 = s.withExecutionModel(ExecutionModel.synchronous())
assert.equal(s2.executionModel.type, "synchronous")
assert.equal(s2.executionModel.recommendedBatchSize, 1 << 30)
const s3 = s.withExecutionModel(ExecutionModel.alwaysAsync())
assert.equal(s3.executionModel.type, "alwaysAsync")
assert.equal(s3.executionModel.recommendedBatchSize, 1)
const s4 = s.withExecutionModel(ExecutionModel.batched())
assert.equal(s4.executionModel.type, "batched")
assert.equal(s4.executionModel.recommendedBatchSize, 128)
const s5 = s.withExecutionModel(ExecutionModel.batched(200))
assert.equal(s5.executionModel.type, "batched")
assert.equal(s5.executionModel.recommendedBatchSize, 256)
})
it("withExecutionModel copies tasks left to execute", () => {
let effect = 0
const ec1 = new TestScheduler()
ec1.tick(1000)
ec1.executeAsync(() => { effect += 1 })
ec1.executeAsync(() => { effect += 2 })
const ec2 = ec1.withExecutionModel(ExecutionModel.alwaysAsync())
assert.equal(ec2.currentTimeMillis(), ec1.currentTimeMillis())
assert.equal(effect, 0)
ec2.tick()
assert.equal(effect, 3)
})
it("executes step by step with tickOne", () => {
const ec = new TestScheduler()
let effect = 0
ec.executeAsync(() => effect += 10)
ec.executeAsync(() => effect += 20)
ec.scheduleOnce(1000, () => effect += 30)
assert.equal(effect, 0)
assert.ok(ec.tickOne())
assert.equal(effect, 20)
assert.ok(ec.tickOne())
assert.equal(effect, 30)
assert.not(ec.tickOne())
assert.equal(ec.tick(1000), 1)
assert.equal(effect, 60)
assert.not(ec.tickOne())
})
it("reports errors with tickOne", () => {
const ec = new TestScheduler()
const dummy = new DummyError("dummy")
ec.executeAsync(() => { throw dummy })
assert.equal(ec.triggeredFailures().length, 0)
assert.ok(ec.tickOne())
assert.equal(ec.triggeredFailures().length, 1)
assert.equal(ec.triggeredFailures()[0], dummy)
})
it("executes immediately for ExecutionModel.synchronous", () => {
const ec = new TestScheduler().withExecutionModel(ExecutionModel.synchronous())
let count = 0
for (let i = 0; i < 1024; i++)
ec.executeBatched(() => { count += 1 })
assert.equal(count, 1024)
})
it("executes asynchronously for ExecutionModel.alwaysAsync", () => {
const ec = new TestScheduler().withExecutionModel(ExecutionModel.alwaysAsync())
let count = 0
for (let i = 0; i < 1024; i++) {
const old = count
ec.executeBatched(() => { count += 1 })
assert.equal(count, old)
ec.tick()
assert.equal(count, old + 1)
}
})
it("executes in batches for ExecutionModel.batched", () => {
const em = ExecutionModel.batched()
const ec = new TestScheduler().withExecutionModel(em)
const batchSize = em.recommendedBatchSize
const total = batchSize * 8
let count = 0
for (let i = 0; i < total; i++)
ec.executeBatched(() => { count += 1 })
assert.equal(count, batchSize - 1)
assert.equal(ec.batchIndex, 127)
ec.tickOne()
assert.equal(count, batchSize)
assert.equal(ec.batchIndex, 0)
ec.tick()
assert.equal(count, total)
})
it("executes in batches for ExecutionModel.batched for recursive loops", () => {
const em = ExecutionModel.batched()
const ec = new TestScheduler().withExecutionModel(em)
const batchSize = em.recommendedBatchSize
const total = batchSize * 8
let count = 0
const loop = (idx: number) => ec.executeBatched(() => {
if (idx < total) {
count += 1
loop(idx + 1)
}
})
loop(0)
for (let i = 0; i < 8; i++) {
assert.equal(count, i * batchSize + batchSize - 1)
ec.tickOne()
}
assert.equal(count, total)
})
})
describe("ExecutionModel", () => {
it("alwaysAsync", () => {
const ref1 = ExecutionModel.alwaysAsync()
assert.equal(ref1.type, "alwaysAsync")
assert.equal(ref1.recommendedBatchSize, 1)
const ref2 = ExecutionModel.alwaysAsync()
assert.equal(ref1 === ref2, false)
assert.equal(ref1, ref2)
assert.equal(ref1.hashCode(), ref2.hashCode())
assert.notEqual(ref1.hashCode(), ExecutionModel.synchronous().hashCode())
})
it("synchronous", () => {
const ref1 = ExecutionModel.synchronous()
assert.equal(ref1.type, "synchronous")
assert.equal(ref1.recommendedBatchSize, 1 << 30)
const ref2 = ExecutionModel.synchronous()
assert.equal(ref1, ref2)
assert.equal(ref1.hashCode(), ref2.hashCode())
assert.notEqual(ref1.hashCode(), ExecutionModel.batched().hashCode())
})
it("batched()", () => {
const ref1 = ExecutionModel.batched()
assert.equal(ref1.type, "batched")
assert.equal(ref1.recommendedBatchSize, ExecutionModel.global.get().recommendedBatchSize)
const ref2 = ExecutionModel.global.get()
assert.equal(ref1, ref2)
assert.equal(ref1.hashCode(), ref2.hashCode())
assert.notEqual(ref1.hashCode(), ExecutionModel.alwaysAsync().hashCode())
})
it("batched(200)", () => {
const ref1 = ExecutionModel.batched(200)
assert.equal(ref1.type, "batched")
assert.equal(ref1.recommendedBatchSize, 256)
const ref2 = ExecutionModel.batched(200)
assert.equal(ref1, ref2)
assert.equal(ref1.hashCode(), ref2.hashCode())
assert.notEqual(ref1.hashCode(), ExecutionModel.alwaysAsync().hashCode())
})
}) | the_stack |
import 'reflect-metadata';
import { singleton, container } from 'tsyringe';
import cloneDeep from 'lodash/cloneDeep';
import { Component } from 'mo/react/component';
import {
FileTypes,
FileType,
FolderTreeEvent,
IFolderTree,
IFolderTreeModel,
IFolderTreeSubItem,
IFolderTreeNodeProps,
} from 'mo/model/workbench/explorer/folderTree';
import { TreeViewUtil } from '../../../common/treeUtil';
import { ExplorerService, IExplorerService } from './explorerService';
import { IMenuItemProps } from 'mo/components';
import logger from 'mo/common/logger';
import { BuiltinService, IBuiltinService } from 'mo/services';
import type { UniqueId } from 'mo/common/types';
export interface IFolderTreeService extends Component<IFolderTree> {
/**
* Reset the FolderTreeService state
*/
reset(): void;
/**
* Add data into folder tree
* @param data
* @param id - Except adding a root folder, the id is required
*/
add(data: IFolderTreeNodeProps, id?: UniqueId): void;
/**
* Remove specific data in folder tree
* @param id
*/
remove(id: UniqueId): void;
/**
* Update specific data in folder tree
* @param data - The `id` property is required in data
*/
update(data: IFolderTreeNodeProps): void;
/**
* Get specific data in folder tree
* @param id
*/
get(id: UniqueId): IFolderTreeNodeProps | null;
/**
* get the current treeNode's parentNode
* @param id
*/
getParentNode(id: UniqueId): IFolderTreeNodeProps | null;
/**
* Get the context menus for file
*/
getFileContextMenu: () => IMenuItemProps[];
/**
* Get the context menus for folder
*/
getFolderContextMenu: () => IMenuItemProps[];
/**
* Get the expandKeys in folderTree
*/
getExpandKeys: () => UniqueId[];
/**
* Set the expandKeys for folderTree
*/
setExpandKeys: (expandKeys: UniqueId[]) => void;
/**
* Active specific node,
* or unactive any node in folder tree
* @param id
*/
setActive(id?: UniqueId): void;
/**
* Set a entry page for folder tree
* @param entry
*/
setEntry(entry: React.ReactNode): void;
/**
* Set the context menus for file
* @param menus
*/
setFileContextMenu: (menus: IMenuItemProps[]) => void;
/**
* Set the context menus for folder
* @param menus
*/
setFolderContextMenu: (menus: IMenuItemProps[]) => void;
/**
* Listen to event about clicking rename button
* @param callback
*/
onRename(callback: (id: UniqueId) => void): void;
/**
* Listen to remove a node
* @param callback
*/
onRemove(callback: (id: UniqueId) => void): void;
/**
* Listen to update file or folder name
* @param callback
*/
onUpdateFileName(callback: (file: IFolderTreeNodeProps) => void): void;
/**
* Listen to select a file
* @param callback
*/
onSelectFile(callback: (file: IFolderTreeNodeProps) => void): void;
/**
* Listen to drop event
* @param treeData
*/
onDropTree(
callback: (
source: IFolderTreeNodeProps,
target: IFolderTreeNodeProps
) => void
): void;
/**
* Listen to right click event
* @param callback
*/
onRightClick(
callback: (
treeData: IFolderTreeNodeProps,
menus: IMenuItemProps[]
) => void
): void;
/**
* Listen to create a node for folder tree
* @param callback
*/
onCreate(callback: (type: FileType, nodeId?: UniqueId) => void): void;
/**
* Listen to the click event about the context menu except for built-in menus
* @param callback
*/
onContextMenu(
callback: (
contextMenu: IMenuItemProps,
treeNode?: IFolderTreeNodeProps
) => void
): void;
/**
* Callback for load folder tree data
* @param callback
*/
onLoadData(
callback: (
treeNode: IFolderTreeNodeProps,
callback: (treeNode: IFolderTreeNodeProps) => void
) => void
): void;
/**
* Callback for expanding tree node
* @param callback
*/
onExpandKeys(callback: (expandKeys: UniqueId[]) => void): void;
/**
* Toggle whether to enable sorting, which is disabled by default.
*/
toggleAutoSort(): void;
}
@singleton()
export class FolderTreeService
extends Component<IFolderTree>
implements IFolderTreeService
{
protected state: IFolderTree;
private readonly explorerService: IExplorerService;
private readonly builtinService: IBuiltinService;
private fileContextMenu: IMenuItemProps[] = [];
private folderContextMenu: IMenuItemProps[] = [];
constructor() {
super();
this.state = container.resolve(IFolderTreeModel);
this.explorerService = container.resolve(ExplorerService);
this.builtinService = container.resolve(BuiltinService);
}
private isHiddenFile(file: IFolderTreeNodeProps) {
return !!file.name?.startsWith('.');
}
private sortTree(tree: IFolderTreeNodeProps[]) {
tree.sort((pre, cur) => {
// folder before file
if (pre.isLeaf !== cur.isLeaf) {
return pre.isLeaf! > cur.isLeaf! ? 1 : -1;
}
// in general, both have name
if (pre.name && cur.name) {
const isHiddenFilePre = Number(this.isHiddenFile(pre));
const isHiddenFileCur = Number(this.isHiddenFile(cur));
// one is hidden file and another is not
if (isHiddenFilePre ^ isHiddenFileCur) {
return isHiddenFilePre ? -1 : 1;
}
// both are hidden files
if (isHiddenFilePre & isHiddenFilePre) {
// hidden file
return pre.name
.substring(1)
.localeCompare(cur.name.substring(1));
}
return pre.name.localeCompare(cur.name!);
}
// the node which is creating would without name
return pre.isEditable ? -1 : 1;
});
tree.forEach((treeNode) => this.sortTree(treeNode.children || []));
}
public reset() {
this.setState({
folderTree: {
contextMenu: [],
current: null,
folderPanelContextMenu: [],
data: [],
},
entry: undefined,
});
}
public getFileContextMenu() {
return this.fileContextMenu;
}
public getParentNode(id: UniqueId): IFolderTreeNodeProps | null {
const root = this.state.folderTree?.data?.[0];
if (!root) return null;
const treeHelper = new TreeViewUtil<IFolderTreeNodeProps>(root);
const node = treeHelper.getHashMap(id);
if (!node) return null;
return node.parent ? treeHelper.getNode(node.parent) : null;
}
public setFileContextMenu(menus: IMenuItemProps[]) {
this.fileContextMenu = menus;
}
public getFolderContextMenu() {
return this.folderContextMenu;
}
public setFolderContextMenu(menus: IMenuItemProps[]) {
this.folderContextMenu = menus;
}
public getExpandKeys() {
return this.state.folderTree?.expandKeys || [];
}
public setExpandKeys(expandKeys: UniqueId[]) {
const { folderTree } = this.state;
this.setState({
folderTree: { ...folderTree, expandKeys },
});
}
private setCurrentFolderLocation(data: IFolderTreeNodeProps, id: UniqueId) {
const children = data.children;
const { tree } = this.getCurrentRootFolderInfo(id);
// The tree exist in certainly, because it was prejudged in the previous processing
const parentIndex = tree!.getHashMap(id);
data.location = `${parentIndex!.node!.location}/${data.name}`;
if (children?.length) {
children.forEach((child) => {
child.location = `${data.location}/${child.name}`;
});
}
}
/**
* Returns the node of root folder in folderTree
*/
private getRootFolderById(id: UniqueId) {
const stateData = this.state.folderTree?.data || [];
for (let index = 0; index < stateData.length; index++) {
const folder = stateData[index];
const treeInstance = new TreeViewUtil<IFolderTreeNodeProps>(folder);
if (treeInstance.getNode(id)) {
return folder;
}
}
return null;
}
private addRootFolder(folder: IFolderTreeNodeProps) {
const { folderTree, autoSort } = this.state;
if (folderTree?.data?.length) {
// if root folder exists, then do nothing
return;
}
if (autoSort) {
this.sortTree(folder.children || []);
}
this.setState({
folderTree: { ...folderTree, data: [folder] },
});
const { SAMPLE_FOLDER_PANEL_ID } = this.builtinService.getConstants();
this.explorerService.updatePanel({
id: SAMPLE_FOLDER_PANEL_ID,
name: folder.name || 'Default Root Folder',
});
}
private getRootFolderIndex(id: UniqueId) {
const data = this.state.folderTree?.data || [];
const index = data.findIndex((folder) => folder.id === id);
return index;
}
private getCurrentRootFolderInfo(id: UniqueId) {
const currentRootFolder = this.getRootFolderById(id);
if (!currentRootFolder) {
return {
currentRootFolder: null,
index: -1,
tree: null,
};
}
const index = this.getRootFolderIndex(currentRootFolder.id!);
const tree = new TreeViewUtil<IFolderTreeNodeProps>(currentRootFolder);
return {
currentRootFolder,
index,
tree,
};
}
// Get the position of file by type
// We considered by default that the list is sorted in fileType
private getPosOfType(
type: keyof typeof FileTypes,
folderList: IFolderTreeNodeProps[]
) {
if (!folderList.length) return 0;
if (type === FileTypes.Folder || type === FileTypes.RootFolder) {
return 0;
}
// find the first file type
const index = folderList.findIndex(
(list) => list.fileType === FileTypes.File
);
return index === -1 ? folderList.length : index;
}
public add(data: IFolderTreeNodeProps, id?: UniqueId): void {
const isRootFolder = data.fileType === 'RootFolder';
const { autoSort } = this.state;
if (isRootFolder) {
this.addRootFolder(data);
return;
}
if (!id && id !== 0)
throw new Error('File node or folder node both need id');
const cloneData = this.state.folderTree?.data || [];
const { tree, index } = this.getCurrentRootFolderInfo(id);
// this index is root folder index
if (index <= -1) {
logger.error('Please check id again, there is not folder tree');
return;
}
const currentIndex = tree!.getHashMap(id)!;
if (currentIndex.node.fileType === FileTypes.File) {
data.location =
currentIndex.node.location?.replace(
/(?<=\/)[^\/]+$/,
`${data.name}`
) || '';
const parentNode = tree!.getNode(currentIndex.parent!)!;
const pos = this.getPosOfType(
data.fileType!,
parentNode.children || []
);
tree!.insertNode(data, currentIndex.parent!, pos);
} else {
this.setCurrentFolderLocation(data, id);
const pos = this.getPosOfType(
data.fileType!,
currentIndex.node.children || []
);
tree?.insertNode(data, currentIndex.id, pos);
}
cloneData[index] = tree!.obj;
if (autoSort) {
this.sortTree(cloneData[index].children || []);
}
this.setState({
folderTree: {
...this.state.folderTree,
data: cloneDeep(cloneData),
},
});
}
public remove(id: UniqueId) {
const folderTree: IFolderTreeSubItem = cloneDeep(
this.getState().folderTree || {}
);
const nextData = folderTree.data || [];
const { tree, index } = this.getCurrentRootFolderInfo(id);
if (!tree || index === -1) {
logger.error(
`There is unable to find a tree node whose id is ${id}`
);
return;
}
tree.removeNode(id);
if (index > -1) nextData[index] = tree.obj;
this.setState({
folderTree,
});
}
public update(data: IFolderTreeNodeProps) {
const { id, ...restData } = data;
const { autoSort } = this.state;
if (!id && id !== 0) throw new Error('Id is required in updating data');
const folderTree: IFolderTreeSubItem = cloneDeep(
this.getState().folderTree || {}
);
const nextData = folderTree.data || [];
const { tree, index } = this.getCurrentRootFolderInfo(id);
if (!tree) {
logger.error(
`There is unable to find a tree node whose id is ${id}`
);
return;
}
tree.updateNode(id, restData);
if (index > -1) {
nextData[index] = tree.obj;
if (autoSort) {
this.sortTree(nextData[index].children || []);
}
}
this.setState({
folderTree,
});
}
public get(id: UniqueId) {
const { tree } = this.getCurrentRootFolderInfo(id);
if (!tree) {
return null;
}
const node = tree.getNode(id);
return node;
}
public setActive(id?: UniqueId) {
const { folderTree } = this.state;
const pendingActiveNode =
typeof id === 'undefined' ? null : this.get(id);
this.setState({
folderTree: {
...folderTree,
current: pendingActiveNode,
},
});
}
public setEntry(entry: React.ReactNode) {
this.setState({
entry,
});
}
public onRename(callback: (id: UniqueId) => void) {
this.subscribe(FolderTreeEvent.onRename, callback);
}
public onRemove(callback: (id: UniqueId) => void) {
this.subscribe(FolderTreeEvent.onDelete, callback);
}
public onUpdateFileName(callback: (file: IFolderTreeNodeProps) => void) {
this.subscribe(FolderTreeEvent.onUpdateFileName, callback);
}
public onSelectFile(callback: (file: IFolderTreeNodeProps) => void) {
this.subscribe(FolderTreeEvent.onSelectFile, callback);
}
public onDropTree = (
callback: (
source: IFolderTreeNodeProps,
target: IFolderTreeNodeProps
) => void
) => {
this.subscribe(FolderTreeEvent.onDrop, callback);
};
public onRightClick = (
callback: (
treeData: IFolderTreeNodeProps,
menus: IMenuItemProps[]
) => void
) => {
this.subscribe(FolderTreeEvent.onRightClick, callback);
};
public onCreate = (
callback: (type: FileType, nodeId?: UniqueId) => void
) => {
this.subscribe(FolderTreeEvent.onCreate, callback);
};
public onContextMenu = (
callback: (
contextMenu: IMenuItemProps,
treeNode?: IFolderTreeNodeProps
) => void
) => {
this.subscribe(FolderTreeEvent.onContextMenuClick, callback);
};
public onLoadData = (
callback: (
treeNode: IFolderTreeNodeProps,
callback: (treeNode: IFolderTreeNodeProps) => void
) => void
) => {
this.subscribe(FolderTreeEvent.onLoadData, callback);
};
public onExpandKeys = (callback: (expandKeys: UniqueId[]) => void) => {
this.subscribe(FolderTreeEvent.onExpandKeys, callback);
};
public toggleAutoSort() {
this.setState({ autoSort: !this.state.autoSort });
}
} | the_stack |
import { Readable } from 'stream';
import { LinkQueueFifo } from '@comunica/actor-rdf-resolve-hypermedia-links-queue-fifo';
import type { ILink } from '@comunica/bus-rdf-resolve-hypermedia-links';
import type { ILinkQueue } from '@comunica/bus-rdf-resolve-hypermedia-links-queue';
import type * as RDF from '@rdfjs/types';
import { ArrayIterator, wrap } from 'asynciterator';
import { DataFactory } from 'rdf-data-factory';
import type { ISourceState } from '../lib/LinkedRdfSourcesAsyncRdfIterator';
import { LinkedRdfSourcesAsyncRdfIterator } from '../lib/LinkedRdfSourcesAsyncRdfIterator';
const DF = new DataFactory();
const v = DF.variable('v');
// Dummy class for testing
// input is array of arrays, with every array corresponding to a page
class Dummy extends LinkedRdfSourcesAsyncRdfIterator {
public data: RDF.Quad[][];
public linkQueue: ILinkQueue = new LinkQueueFifo();
public constructor(data: RDF.Quad[][], subject: RDF.Term, predicate: RDF.Term, object: RDF.Term, graph: RDF.Term,
firstUrl: string) {
super(10, subject, predicate, object, graph, firstUrl);
this.data = data;
}
public async getLinkQueue(): Promise<ILinkQueue> {
return this.linkQueue;
}
protected async getSourceLinks(metadata: Record<string, any>): Promise<ILink[]> {
return metadata.next ? [{ url: metadata.next }] : [];
}
protected getPage(url: string) {
return url.startsWith('P') ? Number.parseInt(url.slice(1), 10) : 0;
}
protected async getSource(link: ILink): Promise<ISourceState> {
const requestedPage = this.getPage(link.url);
if (requestedPage >= this.data.length) {
return {
link,
handledDatasets: { [link.url]: true },
metadata: { requestedPage },
source: <any> {
match() {
const it = new ArrayIterator<RDF.Quad>([], { autoStart: false });
it.setProperty('metadata', { subseq: true });
return it;
},
},
};
}
return {
link,
handledDatasets: { [link.url]: true },
metadata: { requestedPage, firstPageToken: true, next: `P${requestedPage + 1}` },
source: <any> {
match: () => {
const it = new ArrayIterator<RDF.Quad>([ ...this.data[requestedPage] ], { autoStart: false });
it.setProperty('metadata', { subseq: true });
return it;
},
},
};
}
}
// Dummy class with a rejecting getNextSource
class InvalidDummy extends Dummy {
protected getSource(link: ILink): Promise<ISourceState> {
return Promise.reject(new Error('NextSource error'));
}
}
// Dummy class with a rejecting getNextSource on the second page
class InvalidDummyNext extends Dummy {
protected getSource(link: ILink): Promise<ISourceState> {
if (this.getPage(link.url) >= 1) {
return Promise.reject(new Error('NextSource2 error'));
}
return super.getSource(link);
}
}
// Dummy class with a metadata override event on the first page
class DummyMetaOverride extends Dummy {
protected async getSource(link: ILink): Promise<ISourceState> {
const requestedPage = this.getPage(link.url);
if (requestedPage >= this.data.length) {
return {
link,
handledDatasets: { [link.url]: true },
metadata: { requestedPage },
source: <any> {
match() {
const it = new ArrayIterator<RDF.Quad>([], { autoStart: false });
it.setProperty('metadata', { subseq: true });
return it;
},
},
};
}
return {
link,
handledDatasets: { [link.url]: true },
metadata: { firstPageToken: true, next: `P${requestedPage + 1}` },
source: <any> {
match: () => {
const quads = new ArrayIterator<RDF.Quad>([ ...this.data[requestedPage] ], { autoStart: false });
quads.on('newListener', () => quads.setProperty('metadata', { next: `P${requestedPage + 1}`, override: true }));
return quads;
},
},
};
}
}
// Dummy class with a metadata override event before end event
class DummyMetaOverrideEarly extends Dummy {
protected async getSource(link: ILink): Promise<ISourceState> {
return {
link,
handledDatasets: { [link.url]: true },
metadata: { firstPageToken: true },
source: <any> {
match() {
const slowReadable = new Readable();
slowReadable._read = () => {
setTimeout(() => slowReadable.push(null), 100);
};
const quads = wrap(slowReadable, { autoStart: false });
quads.setProperty('metadata', { override: true });
return quads;
},
},
};
}
}
// Dummy class with a metadata override event after end event
class DummyMetaOverrideLate extends Dummy {
protected async getSource(link: ILink): Promise<ISourceState> {
return {
link,
handledDatasets: { [link.url]: true },
metadata: { firstPageToken: true },
source: <any> {
match() {
const quads = new ArrayIterator<RDF.Quad>([], { autoStart: false });
quads.on('end', () => {
setTimeout(() => {
quads.setProperty('metadata', { override: true });
}, 100);
});
return quads;
},
},
};
}
}
// Dummy class that produces multiple next page links
class DummyMultiple extends Dummy {
protected async getSourceLinks(metadata: Record<string, any>): Promise<ILink[]> {
return metadata.next ? [{ url: metadata.next }, { url: metadata.next }] : [];
}
}
// Dummy class that emits an error in the source stream
class DummyError extends Dummy {
protected async getSource(link: ILink): Promise<ISourceState> {
return {
link,
handledDatasets: { [link.url]: true },
metadata: { next: 'NEXT' },
source: <any> {
match() {
const quads = new ArrayIterator<RDF.Quad>([], { autoStart: false });
quads.on('newListener', event => {
if (event === 'end') {
quads.emit('error', new Error('Emitted error!'));
}
});
return quads;
},
},
};
}
}
// Dummy class that produces multiple next page links
class DummyErrorLinks extends Dummy {
protected async getSourceLinks(metadata: Record<string, any>): Promise<ILink[]> {
throw new Error('DummyErrorLinks');
}
}
// Dummy class that rejects on getLinkQueue
class DummyErrorLinkQueueFirst extends Dummy {
public getLinkQueue(): Promise<ILinkQueue> {
return Promise.reject(new Error('DummyErrorLinkQueueFirst'));
}
}
// Dummy class that rejects on getLinkQueue when called for the second time
class DummyErrorLinkQueueLater extends Dummy {
public calls = 0;
public getLinkQueue(): Promise<ILinkQueue> {
if (this.calls++ === 0) {
return super.getLinkQueue();
}
return Promise.reject(new Error('DummyErrorLinkQueueLater'));
}
}
describe('LinkedRdfSourcesAsyncRdfIterator', () => {
describe('A LinkedRdfSourcesAsyncRdfIterator instance', () => {
it('handles a single page', done => {
const data = [[
[ 'a', 'b', 'c' ],
[ 'd', 'e', 'f' ],
[ 'g', 'h', 'i' ],
]];
const quads = toTerms(data);
const it = new Dummy(quads, v, v, v, v, 'first');
jest.spyOn(<any> it, 'handleNextUrl');
const result: any = [];
it.on('data', d => result.push(d));
it.on('end', () => {
expect(result).toEqual(flatten(quads));
expect((<any> it).handleNextUrl).toHaveBeenCalledTimes(2);
expect((<any> it).handleNextUrl).toHaveBeenNthCalledWith(1, {
link: { url: 'first' },
handledDatasets: { first: true },
metadata: { requestedPage: 0, firstPageToken: true, next: 'P1', subseq: true },
source: expect.anything(),
});
expect((<any> it).handleNextUrl).toHaveBeenNthCalledWith(2, {
link: { url: 'P1' },
handledDatasets: { P1: true },
metadata: { requestedPage: 1, subseq: true },
source: expect.anything(),
});
done();
});
});
it('handles metadata for a single page after consuming data', async() => {
const data = [[
[ 'a', 'b', 'c' ],
[ 'd', 'e', 'f' ],
[ 'g', 'h', 'i' ],
]];
const quads = toTerms(data);
const it = new Dummy(quads, v, v, v, v, 'first');
jest.spyOn(<any> it, 'handleNextUrl');
await new Promise<void>(resolve => {
const result: any = [];
it.on('data', d => result.push(d));
it.on('end', () => {
expect(result).toEqual(flatten(quads));
resolve();
});
});
expect(await new Promise(resolve => it.getProperty('metadata', resolve))).toEqual({
firstPageToken: true,
next: 'P1',
requestedPage: 0,
subseq: true,
});
});
it('handles metadata for a single page before consuming data', async() => {
const data = [[
[ 'a', 'b', 'c' ],
[ 'd', 'e', 'f' ],
[ 'g', 'h', 'i' ],
]];
const quads = toTerms(data);
const it = new Dummy(quads, v, v, v, v, 'first');
jest.spyOn(<any> it, 'handleNextUrl');
expect(await new Promise(resolve => it.getProperty('metadata', resolve))).toEqual({
firstPageToken: true,
next: 'P1',
requestedPage: 0,
subseq: true,
});
await new Promise<void>(resolve => {
const result: any = [];
it.on('data', d => result.push(d));
it.on('end', () => {
expect(result).toEqual(flatten(quads));
resolve();
});
});
});
it('handles a single empty page', done => {
const data = [[]];
const quads = toTerms(data);
const it = new Dummy(quads, v, v, v, v, 'first');
jest.spyOn(<any> it, 'handleNextUrl');
const result: any = [];
it.on('data', d => result.push(d));
it.on('end', () => {
expect(result).toEqual([]);
done();
});
});
it('handles metadata for a single empty page after consuming data', async() => {
const data = [[]];
const quads = toTerms(data);
const it = new Dummy(quads, v, v, v, v, 'first');
jest.spyOn(<any> it, 'handleNextUrl');
await new Promise<void>(resolve => {
const result: any = [];
it.on('data', d => result.push(d));
it.on('end', () => {
expect(result).toEqual(flatten(quads));
resolve();
});
});
expect(await new Promise(resolve => it.getProperty('metadata', resolve))).toEqual({
firstPageToken: true,
next: 'P1',
requestedPage: 0,
subseq: true,
});
});
it('handles metadata for a single empty page before consuming data', async() => {
const data = [[]];
const quads = toTerms(data);
const it = new Dummy(quads, v, v, v, v, 'first');
jest.spyOn(<any> it, 'handleNextUrl');
expect(await new Promise(resolve => it.getProperty('metadata', resolve))).toEqual({
firstPageToken: true,
next: 'P1',
requestedPage: 0,
subseq: true,
});
await new Promise<void>(resolve => {
const result: any = [];
it.on('data', d => result.push(d));
it.on('end', () => {
expect(result).toEqual(flatten(quads));
resolve();
});
});
});
it('handles a single page when the first source is pre-loaded', done => {
const data = [[
[ 'a', 'b', 'c' ],
[ 'd', 'e', 'f' ],
[ 'g', 'h', 'i' ],
]];
const quads = toTerms(data);
const it = new Dummy(quads, v, v, v, v, 'first');
it.setSourcesState();
jest.spyOn(<any> it, 'handleNextUrl');
const result: any = [];
it.on('data', d => result.push(d));
it.on('end', () => {
expect(result).toEqual(flatten(quads));
expect((<any> it).handleNextUrl).toHaveBeenCalledTimes(2);
expect((<any> it).handleNextUrl).toHaveBeenNthCalledWith(1, {
link: { url: 'first' },
handledDatasets: { first: true },
metadata: { requestedPage: 0, firstPageToken: true, next: 'P1', subseq: true },
source: expect.anything(),
});
expect((<any> it).handleNextUrl).toHaveBeenNthCalledWith(2, {
link: { url: 'P1' },
handledDatasets: { P1: true },
metadata: { requestedPage: 1, subseq: true },
source: expect.anything(),
});
done();
});
});
it('handles a single page when the first source is pre-loaded from another iterator', done => {
const data = [[
[ 'a', 'b', 'c' ],
[ 'd', 'e', 'f' ],
[ 'g', 'h', 'i' ],
]];
const quads = toTerms(data);
const it1 = new Dummy(quads, v, v, v, v, 'first');
it1.setSourcesState();
const it2 = new Dummy(quads, v, v, v, v, 'first');
it2.setSourcesState(it1.sourcesState);
jest.spyOn(<any> it2, 'handleNextUrl');
const result: any = [];
it2.on('data', d => result.push(d));
it2.on('end', () => {
expect(result).toEqual(flatten(quads));
expect((<any> it2).handleNextUrl).toHaveBeenCalledTimes(2);
expect((<any> it2).handleNextUrl).toHaveBeenNthCalledWith(1, {
link: { url: 'first' },
handledDatasets: { first: true },
metadata: { requestedPage: 0, firstPageToken: true, next: 'P1', subseq: true },
source: expect.anything(),
});
expect((<any> it2).handleNextUrl).toHaveBeenNthCalledWith(2, {
link: { url: 'P1' },
handledDatasets: { P1: true },
metadata: { requestedPage: 1, subseq: true },
source: expect.anything(),
});
done();
});
});
it('handles multiple pages', done => {
const data = [
[
[ 'a', 'b', 'c' ],
[ 'd', 'e', 'f' ],
[ 'g', 'h', 'i' ],
],
[
[ 'a', 'b', '1' ],
[ 'd', 'e', '2' ],
[ 'g', 'h', '3' ],
],
[
[ 'a', 'b', '4' ],
[ 'd', 'e', '5' ],
[ 'g', 'h', '6' ],
],
];
const quads = toTerms(data);
const it = new Dummy(quads, v, v, v, v, 'first');
jest.spyOn(<any> it, 'handleNextUrl');
const result: any = [];
it.on('data', d => result.push(d));
it.on('end', () => {
expect(result).toEqual(flatten(quads));
expect((<any> it).handleNextUrl).toHaveBeenCalledTimes(4);
expect((<any> it).handleNextUrl).toHaveBeenNthCalledWith(1, {
link: { url: 'first' },
handledDatasets: { first: true },
metadata: { requestedPage: 0, firstPageToken: true, next: 'P1', subseq: true },
source: expect.anything(),
});
expect((<any> it).handleNextUrl).toHaveBeenNthCalledWith(2, {
link: { url: 'P1' },
handledDatasets: { P1: true },
metadata: { requestedPage: 1, firstPageToken: true, next: 'P2', subseq: true },
source: expect.anything(),
});
expect((<any> it).handleNextUrl).toHaveBeenNthCalledWith(3, {
link: { url: 'P2' },
handledDatasets: { P2: true },
metadata: { requestedPage: 2, firstPageToken: true, next: 'P3', subseq: true },
source: expect.anything(),
});
expect((<any> it).handleNextUrl).toHaveBeenNthCalledWith(4, {
link: { url: 'P3' },
handledDatasets: { P3: true },
metadata: { requestedPage: 3, subseq: true },
source: expect.anything(),
});
done();
});
});
it('handles multiple pages when the first source is pre-loaded', done => {
const data = [
[
[ 'a', 'b', 'c' ],
[ 'd', 'e', 'f' ],
[ 'g', 'h', 'i' ],
],
[
[ 'a', 'b', '1' ],
[ 'd', 'e', '2' ],
[ 'g', 'h', '3' ],
],
[
[ 'a', 'b', '4' ],
[ 'd', 'e', '5' ],
[ 'g', 'h', '6' ],
],
];
const quads = toTerms(data);
const it = new Dummy(quads, v, v, v, v, 'first');
it.setSourcesState();
jest.spyOn(<any> it, 'handleNextUrl');
const result: any = [];
it.on('data', d => result.push(d));
it.on('end', () => {
expect(result).toEqual(flatten(quads));
expect((<any> it).handleNextUrl).toHaveBeenCalledTimes(4);
expect((<any> it).handleNextUrl).toHaveBeenNthCalledWith(1, {
link: { url: 'first' },
handledDatasets: { first: true },
metadata: { requestedPage: 0, firstPageToken: true, next: 'P1', subseq: true },
source: expect.anything(),
});
expect((<any> it).handleNextUrl).toHaveBeenNthCalledWith(2, {
link: { url: 'P1' },
handledDatasets: { P1: true },
metadata: { requestedPage: 1, firstPageToken: true, next: 'P2', subseq: true },
source: expect.anything(),
});
expect((<any> it).handleNextUrl).toHaveBeenNthCalledWith(3, {
link: { url: 'P2' },
handledDatasets: { P2: true },
metadata: { requestedPage: 2, firstPageToken: true, next: 'P3', subseq: true },
source: expect.anything(),
});
expect((<any> it).handleNextUrl).toHaveBeenNthCalledWith(4, {
link: { url: 'P3' },
handledDatasets: { P3: true },
metadata: { requestedPage: 3, subseq: true },
source: expect.anything(),
});
done();
});
});
it('handles multiple pages with multiple next page links', done => {
const data = [
[
[ 'a', 'b', 'c' ],
[ 'd', 'e', 'f' ],
[ 'g', 'h', 'i' ],
],
[
[ 'a', 'b', '1' ],
[ 'd', 'e', '2' ],
[ 'g', 'h', '3' ],
],
];
const quads = toTerms(data);
const it = new DummyMultiple(quads, v, v, v, v, 'first');
jest.spyOn(<any> it, 'handleNextUrl');
const result: any = [];
it.on('data', (d: any) => result.push(d));
it.on('end', () => {
expect(result).toEqual(flatten(toTerms([
[
[ 'a', 'b', 'c' ],
[ 'd', 'e', 'f' ],
[ 'g', 'h', 'i' ],
],
[
[ 'a', 'b', '1' ],
[ 'd', 'e', '2' ],
[ 'g', 'h', '3' ],
],
[
[ 'a', 'b', '1' ],
[ 'd', 'e', '2' ],
[ 'g', 'h', '3' ],
],
])));
expect((<any> it).handleNextUrl).toHaveBeenCalledTimes(7);
expect((<any> it).handleNextUrl).toHaveBeenNthCalledWith(1, {
link: { url: 'first' },
handledDatasets: { first: true },
metadata: { requestedPage: 0, firstPageToken: true, next: 'P1', subseq: true },
source: expect.anything(),
});
expect((<any> it).handleNextUrl).toHaveBeenNthCalledWith(2, {
link: { url: 'P1' },
handledDatasets: { P1: true },
metadata: { requestedPage: 1, firstPageToken: true, next: 'P2', subseq: true },
source: expect.anything(),
});
expect((<any> it).handleNextUrl).toHaveBeenNthCalledWith(3, {
link: { url: 'P1' },
handledDatasets: { P1: true },
metadata: { requestedPage: 1, firstPageToken: true, next: 'P2', subseq: true },
source: expect.anything(),
});
expect((<any> it).handleNextUrl).toHaveBeenNthCalledWith(4, {
link: { url: 'P2' },
handledDatasets: { P2: true },
metadata: { requestedPage: 2, subseq: true },
source: expect.anything(),
});
expect((<any> it).handleNextUrl).toHaveBeenNthCalledWith(5, {
link: { url: 'P2' },
handledDatasets: { P2: true },
metadata: { requestedPage: 2, subseq: true },
source: expect.anything(),
});
expect((<any> it).handleNextUrl).toHaveBeenNthCalledWith(6, {
link: { url: 'P2' },
handledDatasets: { P2: true },
metadata: { requestedPage: 2, subseq: true },
source: expect.anything(),
});
expect((<any> it).handleNextUrl).toHaveBeenNthCalledWith(7, {
link: { url: 'P2' },
handledDatasets: { P2: true },
metadata: { requestedPage: 2, subseq: true },
source: expect.anything(),
});
done();
});
});
it('catches invalid getNextSource results', async() => {
const it = new InvalidDummy([[]], v, v, v, v, 'first');
expect(await new Promise((resolve, reject) => {
it.on('error', resolve);
it.on('end', reject);
it.on('data', () => {
// Do nothing
});
})).toEqual(new Error('NextSource error'));
});
it('catches invalid getNextSource results on next page', async() => {
const it = new InvalidDummyNext([[], []], v, v, v, v, 'first');
expect(await new Promise((resolve, reject) => {
it.on('error', resolve);
it.on('end', reject);
it.on('data', () => {
// Do nothing
});
})).toEqual(new Error('NextSource2 error'));
});
it('handles metadata overriding on first page', done => {
const data = [
[
[ 'a', 'b', 'c' ],
[ 'd', 'e', 'f' ],
[ 'g', 'h', 'i' ],
],
[
[ 'a', 'b', '1' ],
[ 'd', 'e', '2' ],
[ 'g', 'h', '3' ],
],
];
const quads = toTerms(data);
const it = new DummyMetaOverride(quads, v, v, v, v, 'first');
jest.spyOn(<any> it, 'handleNextUrl');
const result: any = [];
it.on('data', d => result.push(d));
it.on('end', () => {
expect(result).toEqual(flatten(quads));
expect((<any> it).handleNextUrl).toHaveBeenCalledTimes(3);
expect((<any> it).handleNextUrl).toHaveBeenNthCalledWith(1, {
link: { url: 'first' },
handledDatasets: { first: true },
metadata: { firstPageToken: true, next: 'P1', override: true },
source: expect.anything(),
});
expect((<any> it).handleNextUrl).toHaveBeenNthCalledWith(2, {
link: { url: 'P1' },
handledDatasets: { P1: true },
metadata: { firstPageToken: true, next: 'P2', override: true },
source: expect.anything(),
});
expect((<any> it).handleNextUrl).toHaveBeenNthCalledWith(3, {
link: { url: 'P2' },
handledDatasets: { P2: true },
metadata: { requestedPage: 2, subseq: true },
source: expect.anything(),
});
done();
});
});
it('handles metadata event emitted before the end event', done => {
const data: any = [];
const quads = toTerms(data);
const it = new DummyMetaOverrideEarly(quads, v, v, v, v, 'first');
jest.spyOn(<any> it, 'handleNextUrl');
const result: any = [];
it.on('data', d => result.push(d));
it.on('end', () => {
expect(result).toEqual(flatten(quads));
expect((<any> it).handleNextUrl).toHaveBeenCalledTimes(1);
expect((<any> it).handleNextUrl).toHaveBeenNthCalledWith(1, {
link: { url: 'first' },
handledDatasets: { first: true },
metadata: { firstPageToken: true, override: true },
source: expect.anything(),
});
done();
});
});
it('handles metadata event emitted after the end event', done => {
const data: any = [];
const quads = toTerms(data);
const it = new DummyMetaOverrideLate(quads, v, v, v, v, 'first');
jest.spyOn(<any> it, 'handleNextUrl');
const result: any = [];
it.on('data', d => result.push(d));
it.on('end', () => {
expect(result).toEqual(flatten(quads));
expect((<any> it).handleNextUrl).toHaveBeenCalledTimes(1);
expect((<any> it).handleNextUrl).toHaveBeenNthCalledWith(1, {
link: { url: 'first' },
handledDatasets: { first: true },
metadata: { firstPageToken: true, override: true },
source: expect.anything(),
});
done();
});
});
it('calling _read while already iterating should not do anything', () => {
const data = [[
[ 'a', 'b', 'c' ],
[ 'd', 'e', 'f' ],
[ 'g', 'h', 'i' ],
]];
const quads = toTerms(data);
const it = new Dummy(quads, v, v, v, v, 'first');
jest.spyOn(<any> it, 'handleNextUrl');
(<any> it).started = true;
(<any> it).iterating = true;
(<any> it)._read(1, () => {
// Do nothing
});
expect((<any> it).handleNextUrl).not.toHaveBeenCalled();
});
it('delegates error events from the source', async() => {
const it = new DummyError([[], []], v, v, v, v, 'first');
await expect(new Promise((resolve, reject) => {
it.on('error', reject);
it.on('end', resolve);
it.on('data', () => {
// Do nothing
});
})).rejects.toThrow(new Error('Emitted error!'));
});
it('delegates error events from getSourceLinks', async() => {
const it = new DummyErrorLinks([[], []], v, v, v, v, 'first');
await expect(new Promise((resolve, reject) => {
it.on('error', reject);
it.on('end', resolve);
it.on('data', () => {
// Do nothing
});
})).rejects.toThrow(new Error('DummyErrorLinks'));
});
it('delegates error events from rejecting link queue fetching', async() => {
const it = new DummyErrorLinkQueueFirst([[], []], v, v, v, v, 'first');
await expect(new Promise((resolve, reject) => {
it.on('error', reject);
it.on('end', resolve);
it.on('data', () => {
// Do nothing
});
})).rejects.toThrow(new Error('DummyErrorLinkQueueFirst'));
});
it('delegates error events from later rejecting link queue fetching', async() => {
const it = new DummyErrorLinkQueueLater([[], []], v, v, v, v, 'first');
await expect(new Promise((resolve, reject) => {
it.on('error', reject);
it.on('end', resolve);
it.on('data', () => {
// Do nothing
});
})).rejects.toThrow(new Error('DummyErrorLinkQueueLater'));
});
});
});
function toTerms(data: any) {
return data.map((page: any) => page.map((terms: any) => DF.literal.call(null, terms)));
}
function flatten(a: any) {
// eslint-disable-next-line prefer-spread
return [].concat.apply([], a);
} | the_stack |
import { Consumer as KafkaJsConsumer, PartitionAssigner, Assignment, PartitionAssigners, AssignerProtocol, SeekEntry, IHeaders } from "kafkajs";
import { URLSearchParams } from "url";
import * as vscode from "vscode";
import { ClientAccessor } from ".";
import { getWorkspaceSettings, InitialConsumerOffset, ClusterSettings } from "../settings";
import { addQueryParameter, Client, ConnectionOptions } from "./client";
import { deserialize, MessageFormat, SerializationdResult, SerializationSetting } from "./serialization";
interface ConsumerOptions extends ConnectionOptions {
consumerGroupId: string;
topicId: string;
fromOffset: InitialConsumerOffset | string;
partitions?: number[];
messageKeyFormat?: MessageFormat;
messageKeyFormatSettings?: SerializationSetting[];
messageValueFormat?: MessageFormat;
messageValueFormatSettings?: SerializationSetting[];
}
export interface RecordReceivedEvent {
uri: vscode.Uri;
record: ConsumedRecord;
}
export interface ConsumedRecord {
topic: string;
value: string | Buffer | null | SerializationdResult;
offset?: string;
partition?: number;
key?: string | Buffer | SerializationdResult;
headers?: IHeaders;
}
export interface ConsumerHeader {
name: string;
value: string | Buffer | null | SerializationdResult
}
export interface ConsumerChangedStatusEvent {
uri: vscode.Uri;
status: "created" | "rebalancing" | "rebalanced";
}
export enum ConsumerLaunchState {
idle,
starting,
started,
closing,
closed
}
export interface ConsumerCollectionChangedEvent {
consumers: Consumer[];
}
export class Consumer implements vscode.Disposable {
private kafkaClient?: Client;
private consumer?: KafkaJsConsumer;
private onDidReceiveMessageEmitter = new vscode.EventEmitter<RecordReceivedEvent>();
private onDidReceiveErrorEmitter = new vscode.EventEmitter<any>();
private onDidChangeStatusEmitter = new vscode.EventEmitter<ConsumerChangedStatusEvent>();
public onDidReceiveRecord = this.onDidReceiveMessageEmitter.event;
public onDidReceiveError = this.onDidReceiveErrorEmitter.event;
public onDidChangeStatus = this.onDidChangeStatusEmitter.event;
public readonly clusterId: string;
public readonly options: ConsumerOptions;
public state: ConsumerLaunchState = ConsumerLaunchState.idle;
public error: any;
constructor(public uri: vscode.Uri, clusterSettings: ClusterSettings, private clientAccessor: ClientAccessor) {
const { clusterId, consumerGroupId, topicId, fromOffset, partitions, messageKeyFormat, messageKeyFormatSettings, messageValueFormat,messageValueFormatSettings } = extractConsumerInfoUri(uri);
this.clusterId = clusterId;
const cluster = clusterSettings.get(clusterId);
try {
if (!cluster) {
throw new Error(`Cannot create consumer, unknown cluster ${clusterId}`);
}
const settings = getWorkspaceSettings();
this.options = {
clusterProviderId: cluster.clusterProviderId,
bootstrap: cluster.bootstrap,
saslOption: cluster.saslOption,
consumerGroupId: consumerGroupId,
topicId,
fromOffset: fromOffset || settings.consumerOffset,
partitions: parsePartitions(partitions),
messageKeyFormat,
messageKeyFormatSettings,
messageValueFormat,
messageValueFormatSettings
};
}
catch (e) {
this.error = e;
throw e;
}
}
/***
* Starts a new consumer group that subscribes to the provided topic.
* Received messages and/or errors are emitted via events.
*/
async start(): Promise<void> {
const partitions = this.options.partitions;
const partitionAssigner = this.getPartitionAssigner(partitions);
const fromOffset = this.options.fromOffset;
const topic = this.options.topicId;
this.kafkaClient = this.clientAccessor.get(this.clusterId);
this.consumer = await this.kafkaClient.consumer({
groupId: this.options.consumerGroupId, retry: { retries: 3 },
partitionAssigners: [
partitionAssigner
]
});
await this.consumer.connect();
const subscribeOptions = this.createSubscribeOptions(topic, fromOffset);
await this.consumer.subscribe(subscribeOptions);
this.consumer.run({
eachMessage: async ({ topic, partition, message }) => {
message.key = deserialize(message.key, this.options.messageKeyFormat, this.options.messageKeyFormatSettings);
message.value = deserialize(message.value, this.options.messageValueFormat, this.options.messageValueFormatSettings);
this.onDidReceiveMessageEmitter.fire({
uri: this.uri,
record: { topic: topic, partition: partition, ...message },
});
},
});
const offsetAsNumber = (fromOffset && subscribeOptions.fromBeginning === undefined);
if (partitions || offsetAsNumber) {
const definedOffset = offsetAsNumber ? fromOffset : undefined;
const topicOffsets = !definedOffset ? await this.kafkaClient?.fetchTopicOffsets(topic) : undefined;
const definedPartitions = await this.getPartitions(topic, partitions);
for (let i = 0; i < definedPartitions.length; i++) {
const partition = definedPartitions[i];
const offset = definedOffset || await this.getOffsetToSeek(topicOffsets, fromOffset, partition);
this.consumer.seek({ topic, partition, offset });
}
}
}
private async getPartitions(topic: string, partitions?: number[]): Promise<number[]> {
if (partitions) {
// returns the customized partitions
return partitions;
}
// returns the topics partitions
return this.kafkaClient?.fetchTopicPartitions(topic) || [0];
}
private async getOffsetToSeek(topicOffsets: Array<SeekEntry & { high: string; low: string }> | undefined, fromOffset: string, partition: number): Promise<string> {
const result = topicOffsets?.find(p => p.partition === partition);
if (!result) {
return '0';
}
if (fromOffset === "latest") {
return result.high;
}
return result.low;
}
private getPartitionAssigner(partitions?: number[]): PartitionAssigner {
if (!partitions) {
return PartitionAssigners.roundRobin;
}
const userData = Buffer.alloc(0);
return ({ cluster }) => ({
name: 'AssignedPartitionsAssigner',
version: 1,
async assign({ members, topics }) {
const sortedMembers = members.map(({ memberId }) => memberId).sort();
const firstMember = sortedMembers[0];
const assignment = {
[firstMember]: {} as Assignment,
};
topics.forEach(topic => {
assignment[firstMember][topic] = partitions;
});
return Object.keys(assignment).map(memberId => ({
memberId,
memberAssignment: AssignerProtocol.MemberAssignment.encode({
version: this.version,
assignment: assignment[memberId],
userData,
}),
}));
},
protocol({ topics }) {
return {
name: this.name,
metadata: AssignerProtocol.MemberMetadata.encode({
version: this.version,
topics,
userData,
})
};
}
});
}
private createSubscribeOptions(topic: string, fromOffset?: string): { topic: string, fromBeginning?: boolean } {
if (fromOffset === "earliest" || fromOffset === "latest") {
const fromBeginning = fromOffset === "earliest";
return { topic, fromBeginning };
}
return { topic };
}
async dispose(): Promise<void> {
if (this.consumer) {
await this.consumer.disconnect();
}
this.onDidReceiveErrorEmitter.dispose();
this.onDidReceiveMessageEmitter.dispose();
}
}
/**
* A collection of consumers.
*/
export class ConsumerCollection implements vscode.Disposable {
private consumers: { [id: string]: Consumer } = {};
private disposables: vscode.Disposable[] = [];
private onDidChangeCollectionEmitter = new vscode.EventEmitter<ConsumerCollectionChangedEvent>();
public onDidChangeCollection = this.onDidChangeCollectionEmitter.event;
constructor(private clusterSettings: ClusterSettings, private clientAccessor: ClientAccessor) {
}
/**
* Creates a new consumer for a provided uri.
*/
async create(uri: vscode.Uri): Promise<Consumer> {
// Create the consumer
const consumer = new Consumer(uri, this.clusterSettings, this.clientAccessor);
this.consumers[uri.toString()] = consumer;
// Fire an event to notify that Consumer is starting
consumer.state = ConsumerLaunchState.starting;
this.onDidChangeCollectionEmitter.fire({
consumers: [consumer]
});
// Start the consumer
await consumer.start()
.catch(e => {
delete this.consumers[uri.toString()];
consumer.state = ConsumerLaunchState.idle;
consumer.error = e;
throw e;
})
.finally(() => {
// Fire an event to notify that consumer state changed
// with a delay because when start is done quickly
// the trace 'Consumer: started' is not displayed.
setTimeout(() => {
if (!consumer.error) {
consumer.state = ConsumerLaunchState.started;
}
this.onDidChangeCollectionEmitter.fire({
consumers: [consumer]
});
}, 200);
});
return consumer;
}
/**
* Retrieve the number of active consumers
*/
length(): number {
return Object.keys(this.consumers).length;
}
/**
* Retrieve an existing consumer if exists.
*/
get(uri: vscode.Uri): Consumer | null {
if (!this.has(uri)) {
return null;
}
return this.consumers[uri.toString()];
}
/**
* Retrieve all consumers
*/
getAll(): Consumer[] {
return Object.keys(this.consumers).map((c) => this.consumers[c]);
}
/**
* Return the consumer of the given cluster associated with the consumer group id.
*
* @param clusterId
* @param consumerGroupId
*/
getByConsumerGroupId(clusterId: string, consumerGroupId: string): Consumer | undefined {
return this.getAll()
.find(c => clusterId === c.clusterId && c.options.consumerGroupId === consumerGroupId);
}
/**
* Closes an existing consumer if exists.
*/
async close(uri: vscode.Uri): Promise<void> {
const consumer = this.get(uri);
if (consumer === null) {
return;
}
// Fire an event to notify that consumer is closing
consumer.state = ConsumerLaunchState.closing;
this.onDidChangeCollectionEmitter.fire({
consumers: [consumer]
});
await consumer.dispose();
delete this.consumers[uri.toString()];
// Fire an event to notify that consumer is closed
consumer.state = ConsumerLaunchState.closed;
this.onDidChangeCollectionEmitter.fire({
consumers: [consumer]
});
}
/**
* Check whether a consumer exists.
*/
has(uri: vscode.Uri): boolean {
return this.consumers.hasOwnProperty(uri.toString());
}
dispose(): void {
this.disposeConsumers();
this.disposables.forEach((d) => d.dispose());
this.onDidChangeCollectionEmitter.dispose();
}
disposeConsumers(): void {
Object.keys(this.consumers).forEach((key) => {
this.consumers[key].dispose();
});
this.consumers = {};
}
}
// ---------- Consumer URI utilities
export interface ConsumerInfoUri {
clusterId: string;
consumerGroupId: string;
topicId: InitialConsumerOffset | string;
fromOffset?: string;
partitions?: string;
messageKeyFormat?: MessageFormat;
messageKeyFormatSettings?: SerializationSetting[];
messageValueFormat?: MessageFormat;
messageValueFormatSettings?: SerializationSetting[];
}
const TOPIC_QUERY_PARAMETER = 'topic';
const FROM_QUERY_PARAMETER = 'from';
const PARTITIONS_QUERY_PARAMETER = 'partitions';
const KEY_FORMAT_QUERY_PARAMETER = 'key';
const KEY_FORMAT_SETTINGS_QUERY_PARAMETER = 'key-settings';
const VALUE_FORMAT_QUERY_PARAMETER = 'value';
const VALUE_FORMAT_SETTINGS_QUERY_PARAMETER = 'value-settings';
export function createConsumerUri(info: ConsumerInfoUri): vscode.Uri {
const path = `kafka:${info.clusterId}/${info.consumerGroupId}`;
let query = '';
query = addQueryParameter(query, TOPIC_QUERY_PARAMETER, info.topicId);
query = addQueryParameter(query, FROM_QUERY_PARAMETER, info.fromOffset);
query = addQueryParameter(query, PARTITIONS_QUERY_PARAMETER, info.partitions);
query = addQueryParameter(query, KEY_FORMAT_QUERY_PARAMETER, info.messageKeyFormat);
query = addQueryParameter(query, KEY_FORMAT_SETTINGS_QUERY_PARAMETER, info.messageKeyFormatSettings?.map(p => p.value).join(','));
query = addQueryParameter(query, VALUE_FORMAT_QUERY_PARAMETER, info.messageValueFormat);
query = addQueryParameter(query, VALUE_FORMAT_SETTINGS_QUERY_PARAMETER, info.messageValueFormatSettings?.map(p => p.value).join(','));
return vscode.Uri.parse(path + query);
}
export function extractConsumerInfoUri(uri: vscode.Uri): ConsumerInfoUri {
const [clusterId, consumerGroupId] = uri.path.split("/");
const urlParams = new URLSearchParams(uri.query);
const topicId = urlParams.get(TOPIC_QUERY_PARAMETER) || '';
const from = urlParams.get(FROM_QUERY_PARAMETER);
const partitions = urlParams.get(PARTITIONS_QUERY_PARAMETER);
const messageKeyFormat = urlParams.get(KEY_FORMAT_QUERY_PARAMETER);
const messageKeyFormatSettings = urlParams.get(KEY_FORMAT_SETTINGS_QUERY_PARAMETER);
const messageValueFormat = urlParams.get(VALUE_FORMAT_QUERY_PARAMETER);
const messageValueFormatSettings = urlParams.get(VALUE_FORMAT_SETTINGS_QUERY_PARAMETER);
const result: ConsumerInfoUri = {
clusterId,
consumerGroupId,
topicId
};
if (from && from.trim().length > 0) {
result.fromOffset = from;
}
if (partitions && partitions.trim().length > 0) {
result.partitions = partitions;
}
if (messageKeyFormat && messageKeyFormat.trim().length > 0) {
result.messageKeyFormat = messageKeyFormat as MessageFormat;
}
if (messageKeyFormatSettings) {
const settings = messageKeyFormatSettings.split(',').
map(value => <SerializationSetting>{ value });
result.messageKeyFormatSettings = settings;
}
if (messageValueFormat && messageValueFormat.trim().length > 0) {
result.messageValueFormat = messageValueFormat as MessageFormat;
}
if (messageValueFormatSettings) {
const settings = messageValueFormatSettings.split(',').
map(value => <SerializationSetting>{ value });
result.messageValueFormatSettings = settings;
}
return result;
}
export function parsePartitions(partitions?: string): number[] | undefined {
partitions = partitions?.trim();
if (partitions && partitions.length > 0) {
let from: string | undefined = undefined;
let to: string | undefined = undefined;
const result = new Set<number>();
const add = function (from: string | undefined, to: string | undefined) {
if (!from) {
return;
}
const fromAsNumber = parseInt(from, 10);
const toAsNumber = to ? parseInt(to, 10) : fromAsNumber;
for (let i = fromAsNumber; i <= toAsNumber; i++) {
result.add(i);
}
};
for (let i = 0; i < partitions.length; i++) {
const c = partitions.charAt(i);
if (c === ' ') {
continue;
} else if (c === ',') {
add(from, to);
from = undefined;
to = undefined;
} else if (c === '-') {
to = '';
} else if (!isNaN(parseInt(c, 10))) {
if (to !== undefined) {
to += c;
} else {
from = from || '';
from += c;
}
} else {
throw new Error(`Unexpected character '${c}' in partitions expression.`);
}
}
add(from, to);
// returns sorted and distinct partitions
return result.size > 0 ? Array.from(result).sort() : undefined;
}
return undefined;
} | the_stack |
import {
IAuthentication,
IConnectionFactory,
RecognitionMode,
RecognizerConfig,
ServiceRecognizerBase,
SpeechServiceConfig,
TranslationConnectionFactory,
TranslationServiceRecognizer,
} from "../common.speech/Exports";
import { marshalPromiseToCallbacks } from "../common/Exports";
import { AudioConfigImpl } from "./Audio/AudioConfig";
import { Connection } from "./Connection";
import { Contracts } from "./Contracts";
import {
AudioConfig,
PropertyCollection,
PropertyId,
Recognizer,
TranslationRecognitionCanceledEventArgs,
TranslationRecognitionEventArgs,
TranslationRecognitionResult,
TranslationSynthesisEventArgs,
} from "./Exports";
import { SpeechTranslationConfig, SpeechTranslationConfigImpl } from "./SpeechTranslationConfig";
/**
* Translation recognizer
* @class TranslationRecognizer
*/
export class TranslationRecognizer extends Recognizer {
private privDisposedTranslationRecognizer: boolean;
/**
* Initializes an instance of the TranslationRecognizer.
* @constructor
* @param {SpeechTranslationConfig} speechConfig - Set of properties to configure this recognizer.
* @param {AudioConfig} audioConfig - An optional audio config associated with the recognizer
*/
public constructor(speechConfig: SpeechTranslationConfig, audioConfig?: AudioConfig) {
const configImpl = speechConfig as SpeechTranslationConfigImpl;
Contracts.throwIfNull(configImpl, "speechConfig");
super(audioConfig, configImpl.properties, new TranslationConnectionFactory());
this.privDisposedTranslationRecognizer = false;
if (this.properties.getProperty(PropertyId.SpeechServiceConnection_TranslationVoice, undefined) !== undefined) {
Contracts.throwIfNullOrWhitespace(
this.properties.getProperty(PropertyId.SpeechServiceConnection_TranslationVoice),
PropertyId[PropertyId.SpeechServiceConnection_TranslationVoice]);
}
Contracts.throwIfNullOrWhitespace(
this.properties.getProperty(PropertyId.SpeechServiceConnection_TranslationToLanguages),
PropertyId[PropertyId.SpeechServiceConnection_TranslationToLanguages]);
Contracts.throwIfNullOrWhitespace(this.properties.getProperty(
PropertyId.SpeechServiceConnection_RecoLanguage),
PropertyId[PropertyId.SpeechServiceConnection_RecoLanguage]);
}
/**
* The event recognizing signals that an intermediate recognition result is received.
* @member TranslationRecognizer.prototype.recognizing
* @function
* @public
*/
public recognizing: (sender: TranslationRecognizer, event: TranslationRecognitionEventArgs) => void;
/**
* The event recognized signals that a final recognition result is received.
* @member TranslationRecognizer.prototype.recognized
* @function
* @public
*/
public recognized: (sender: TranslationRecognizer, event: TranslationRecognitionEventArgs) => void;
/**
* The event canceled signals that an error occurred during recognition.
* @member TranslationRecognizer.prototype.canceled
* @function
* @public
*/
public canceled: (sender: TranslationRecognizer, event: TranslationRecognitionCanceledEventArgs) => void;
/**
* The event synthesizing signals that a translation synthesis result is received.
* @member TranslationRecognizer.prototype.synthesizing
* @function
* @public
*/
public synthesizing: (sender: TranslationRecognizer, event: TranslationSynthesisEventArgs) => void;
/**
* Gets the language name that was set when the recognizer was created.
* @member TranslationRecognizer.prototype.speechRecognitionLanguage
* @function
* @public
* @returns {string} Gets the language name that was set when the recognizer was created.
*/
public get speechRecognitionLanguage(): string {
Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer);
return this.properties.getProperty(PropertyId.SpeechServiceConnection_RecoLanguage);
}
/**
* Gets target languages for translation that were set when the recognizer was created.
* The language is specified in BCP-47 format. The translation will provide translated text for each of language.
* @member TranslationRecognizer.prototype.targetLanguages
* @function
* @public
* @returns {string[]} Gets target languages for translation that were set when the recognizer was created.
*/
public get targetLanguages(): string[] {
Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer);
return this.properties.getProperty(PropertyId.SpeechServiceConnection_TranslationToLanguages).split(",");
}
/**
* Gets the name of output voice.
* @member TranslationRecognizer.prototype.voiceName
* @function
* @public
* @returns {string} the name of output voice.
*/
public get voiceName(): string {
Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer);
return this.properties.getProperty(PropertyId.SpeechServiceConnection_TranslationVoice, undefined);
}
/**
* Gets the authorization token used to communicate with the service.
* @member TranslationRecognizer.prototype.authorizationToken
* @function
* @public
* @returns {string} Authorization token.
*/
public get authorizationToken(): string {
return this.properties.getProperty(PropertyId.SpeechServiceAuthorization_Token);
}
/**
* Gets/Sets the authorization token used to communicate with the service.
* @member TranslationRecognizer.prototype.authorizationToken
* @function
* @public
* @param {string} value - Authorization token.
*/
public set authorizationToken(value: string) {
this.properties.setProperty(PropertyId.SpeechServiceAuthorization_Token, value);
}
/**
* The collection of properties and their values defined for this TranslationRecognizer.
* @member TranslationRecognizer.prototype.properties
* @function
* @public
* @returns {PropertyCollection} The collection of properties and their values defined for this TranslationRecognizer.
*/
public get properties(): PropertyCollection {
return this.privProperties;
}
/**
* Starts recognition and translation, and stops after the first utterance is recognized.
* The task returns the translation text as result.
* Note: recognizeOnceAsync returns when the first utterance has been recognized, so it is suitableonly
* for single shot recognition like command or query. For long-running recognition,
* use startContinuousRecognitionAsync() instead.
* @member TranslationRecognizer.prototype.recognizeOnceAsync
* @function
* @public
* @param cb - Callback that received the result when the translation has completed.
* @param err - Callback invoked in case of an error.
*/
public recognizeOnceAsync(cb?: (e: TranslationRecognitionResult) => void, err?: (e: string) => void): void {
Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer);
marshalPromiseToCallbacks(this.recognizeOnceAsyncImpl(RecognitionMode.Conversation), cb, err);
}
/**
* Starts recognition and translation, until stopContinuousRecognitionAsync() is called.
* User must subscribe to events to receive translation results.
* @member TranslationRecognizer.prototype.startContinuousRecognitionAsync
* @function
* @public
* @param cb - Callback that received the translation has started.
* @param err - Callback invoked in case of an error.
*/
public startContinuousRecognitionAsync(cb?: () => void, err?: (e: string) => void): void {
marshalPromiseToCallbacks(this.startContinuousRecognitionAsyncImpl(RecognitionMode.Conversation), cb, err);
}
/**
* Stops continuous recognition and translation.
* @member TranslationRecognizer.prototype.stopContinuousRecognitionAsync
* @function
* @public
* @param cb - Callback that received the translation has stopped.
* @param err - Callback invoked in case of an error.
*/
public stopContinuousRecognitionAsync(cb?: () => void, err?: (e: string) => void): void {
marshalPromiseToCallbacks(this.stopContinuousRecognitionAsyncImpl(), cb, err);
}
/**
* dynamically remove a language from list of target language
* (can be used while recognition is ongoing)
* @member TranslationRecognizer.prototype.removeTargetLanguage
* @function
* @param lang - language to be removed
* @public
*/
public removeTargetLanguage(lang: string): void {
Contracts.throwIfNullOrUndefined(lang, "language to be removed");
if (this.properties.getProperty(PropertyId.SpeechServiceConnection_TranslationToLanguages, undefined) !== undefined) {
const languages: string[] = this.properties.getProperty(PropertyId.SpeechServiceConnection_TranslationToLanguages).split(",");
const index: number = languages.indexOf(lang);
if (index > -1) {
languages.splice(index, 1);
this.properties.setProperty(PropertyId.SpeechServiceConnection_TranslationToLanguages, languages.join(","));
this.updateLanguages(languages);
}
}
}
/**
* dynamically add a language to list of target language
* (can be used while recognition is ongoing)
* @member TranslationRecognizer.prototype.addTargetLanguage
* @function
* @param lang - language to be added
* @public
*/
public addTargetLanguage(lang: string): void {
Contracts.throwIfNullOrUndefined(lang, "language to be added");
let languages: string[] = [];
if (this.properties.getProperty(PropertyId.SpeechServiceConnection_TranslationToLanguages, undefined) !== undefined) {
languages = this.properties.getProperty(PropertyId.SpeechServiceConnection_TranslationToLanguages).split(",");
if (!languages.includes(lang)) {
languages.push(lang);
this.properties.setProperty(PropertyId.SpeechServiceConnection_TranslationToLanguages, languages.join(","));
}
} else {
this.properties.setProperty(PropertyId.SpeechServiceConnection_TranslationToLanguages, lang);
languages = [lang];
}
this.updateLanguages(languages);
}
/**
* closes all external resources held by an instance of this class.
* @member TranslationRecognizer.prototype.close
* @function
* @public
*/
public close(cb?: () => void, errorCb?: (error: string) => void): void {
Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer);
marshalPromiseToCallbacks(this.dispose(true), cb, errorCb);
}
/**
* handles ConnectionEstablishedEvent for conversation translation scenarios.
* @member TranslationRecognizer.prototype.onConnection
* @function
* @public
*/
/* tslint:disable:no-empty */
public onConnection(): void { }
/**
* handles disconnection events for conversation translation scenarios.
* @member TranslationRecognizer.prototype.onDisconnection
* @function
* @public
*/
/* tslint:disable:no-empty */
public async onDisconnection(): Promise<void> { }
protected async dispose(disposing: boolean): Promise<void> {
if (this.privDisposedTranslationRecognizer) {
return;
}
this.privDisposedTranslationRecognizer = true;
if (disposing) {
await this.implRecognizerStop();
await super.dispose(disposing);
}
}
protected createRecognizerConfig(speechConfig: SpeechServiceConfig): RecognizerConfig {
return new RecognizerConfig(speechConfig, this.properties);
}
protected createServiceRecognizer(
authentication: IAuthentication,
connectionFactory: IConnectionFactory,
audioConfig: AudioConfig,
recognizerConfig: RecognizerConfig): ServiceRecognizerBase {
const configImpl: AudioConfigImpl = audioConfig as AudioConfigImpl;
return new TranslationServiceRecognizer(authentication, connectionFactory, configImpl, recognizerConfig, this);
}
private updateLanguages(languages: string[]): void {
const conn: Connection = Connection.fromRecognizer(this);
if (!!conn) {
conn.setMessageProperty("speech.context", "translationcontext", {to: languages});
conn.sendMessageAsync("event", JSON.stringify({
id: "translation",
name: "updateLanguage",
to: languages
}));
}
}
} | the_stack |
import {
ChangeDetectorRef,
ElementRef,
EventEmitter,
Injectable,
Renderer2,
} from '@angular/core';
import { WindowRef } from '@spartacus/core';
import { EventListenerUtils } from '@spartacus/epd-visualization/root';
@Injectable({
providedIn: 'any',
})
export class VisualViewerAnimationSliderService {
public constructor(
private elementRef: ElementRef,
private windowRef: WindowRef,
private renderer: Renderer2,
private changeDetectorRef: ChangeDetectorRef
) {
this.eventListenerUtils.initialize(this.renderer);
}
public initialize(): void {
this.updateEventBindings();
this.setupResizeObserver();
this.setInitialized();
}
private setInitialized() {
this._initialized = true;
this.initializedChange.emit(true);
this.initializedChange.complete();
}
public get initialized(): boolean {
return this._initialized;
}
private _initialized = false;
public initializedChange = new EventEmitter<boolean>();
/**
* Slider value. Value is in the range [0-1].
*/
set value(value: number) {
value = this.clampToRange(value);
if (this._value === value) {
return;
}
this._value = value;
this.valueChange.emit(this.value);
}
get value() {
return this._value;
}
private _value: number = 0;
valueChange: EventEmitter<number> = new EventEmitter();
set disabled(disabled: boolean) {
if (this._disabled === disabled) {
return;
}
this._disabled = disabled;
this.updateEventBindings();
}
get disabled() {
return this._disabled;
}
private _disabled: boolean = false;
set hidden(hidden: boolean) {
if (this._hidden === hidden) {
return;
}
this._hidden = hidden;
// Ensure handle position is recalculated when the animation slider visibility changes
// Fixes a bug in which the initial position of the slider handle is incorrect
// because the bar width is calculated while the animation slider is hidden (noticeable in RTL mode)
this.changeDetectorRef.detectChanges();
}
get hidden(): boolean {
return this._hidden;
}
private _hidden: boolean;
get position(): number {
return this.valueToPosition(this.value);
}
get rightToLeft(): boolean {
return this.windowRef.document.documentElement.dir === 'rtl';
}
set barElement(barElement: ElementRef) {
this._barElement = barElement;
}
get barElement(): ElementRef {
return this._barElement;
}
_barElement: ElementRef;
set handleElement(handleElement: ElementRef) {
this._handleElement = handleElement;
}
get handleElement(): ElementRef {
return this._handleElement;
}
_handleElement: ElementRef;
private set resizeObserver(resizeObserver: ResizeObserver | undefined) {
this._resizeObserver = resizeObserver;
}
private get resizeObserver() {
return this._resizeObserver;
}
private _resizeObserver?: ResizeObserver = undefined;
private eventListenerUtils = new EventListenerUtils();
private set touchIdentifier(touchIdentifier: number | undefined) {
this._touchIdentifier = touchIdentifier;
}
private get touchIdentifier(): number | undefined {
return this._touchIdentifier;
}
private _touchIdentifier?: number = undefined;
private getClientWidth(elementRef: ElementRef): number | undefined {
if (!elementRef || !elementRef.nativeElement) {
return undefined;
}
const clientRect = this.getClientRect(elementRef);
return clientRect.right - clientRect.left;
}
private getClientRect(elementRef: ElementRef): DOMRect {
return elementRef.nativeElement.getBoundingClientRect();
}
private resizeObserverSupported(): boolean {
return window.ResizeObserver !== undefined;
}
private setupResizeObserver() {
if (this.resizeObserverSupported()) {
this.resizeObserver = new ResizeObserver(this.onResize.bind(this));
this.resizeObserver.observe(this.elementRef.nativeElement);
}
}
private onResize() {
// Ensure handle position is recalculated on resize
this.changeDetectorRef.detectChanges();
}
sizeChange = new EventEmitter();
private updateEventBindings(): void {
if (this.disabled) {
this.eventListenerUtils.detachAllEventListeners(document);
this.eventListenerUtils.detachAllEventListeners(
this.barElement.nativeElement
);
this.eventListenerUtils.detachAllEventListeners(
this.handleElement.nativeElement
);
} else {
this.eventListenerUtils.attachEventListener(
this.handleElement.nativeElement,
'mousedown',
this.onMouseDown.bind(this)
);
this.eventListenerUtils.attachEventListener(
this.barElement.nativeElement,
'mousedown',
this.onMouseDownOnBar.bind(this)
);
this.eventListenerUtils.attachEventListener(
this.handleElement.nativeElement,
'touchstart',
this.onTouchStart.bind(this)
);
this.eventListenerUtils.attachEventListener(
this.barElement.nativeElement,
'touchstart',
this.onTouchStartOnBar.bind(this)
);
this.eventListenerUtils.attachEventListener(
this.handleElement.nativeElement,
'focus',
this.onHandleFocus.bind(this)
);
}
}
get handleWidth(): number {
return this.getClientWidth(this.handleElement) ?? 0;
}
get barWidth(): number {
return this.getClientWidth(this.barElement) ?? 0;
}
get handleMaxPosition(): number {
return this.barWidth - this.handleWidth;
}
private valueToPosition(value: number): number {
let position: number = this.clampToRange(value);
if (this.rightToLeft) {
position = 1 - position;
}
return position * this.handleMaxPosition;
}
private positionToValue(position: number): number {
let value: number = position / this.handleMaxPosition;
if (this.rightToLeft) {
value = 1 - value;
}
return value;
}
private findTouch(
touchList: TouchList,
touchIdentifier?: number
): Touch | undefined {
for (let i = 0; i < touchList.length; i++) {
const touch = touchList.item(i) as Touch;
if (touch.identifier === touchIdentifier) {
return touch;
}
}
return undefined;
}
private get sliderClientPosition(): number {
return this.getClientRect(this.elementRef).left;
}
private onTouchStart(event: TouchEvent): void {
event.stopPropagation();
event.preventDefault();
if (this.touchIdentifier !== undefined) {
return;
}
this.eventListenerUtils.detachEventListeners(document, 'touchmove');
this.eventListenerUtils.attachEventListener(
document,
'touchmove',
this.onTouchMove.bind(this)
);
this.eventListenerUtils.detachEventListeners(document, 'touchend');
this.eventListenerUtils.attachEventListener(
document,
'touchend',
this.onTouchEnd.bind(this)
);
this.touchIdentifier = (event.changedTouches as TouchList)[0].identifier;
}
private onTouchStartOnBar(event: TouchEvent): void {
this.onTouchStart(event);
this.onTouchMove(event);
}
private onMouseDown(event: MouseEvent): void {
event.stopPropagation();
event.preventDefault();
this.eventListenerUtils.detachEventListeners(document, 'mousemove');
this.eventListenerUtils.attachEventListener(
document,
'mousemove',
this.onMouseMove.bind(this)
);
this.eventListenerUtils.detachEventListeners(document, 'mouseup');
this.eventListenerUtils.attachEventListener(
document,
'mouseup',
this.onMouseUp.bind(this)
);
}
private onMouseDownOnBar(event: MouseEvent): void {
this.onMouseDown(event);
this.onMouseMove(event);
}
private onMouseMove(event: MouseEvent): void {
const position =
event.clientX - this.sliderClientPosition - this.handleWidth / 2;
this.applyValue(this.positionToValue(position));
}
private onMouseUp(_event: MouseEvent): void {
this.eventListenerUtils.detachEventListeners(document, 'mousemove');
this.eventListenerUtils.detachEventListeners(document, 'mouseup');
}
private onTouchMove(event: TouchEvent): void {
let touchInitiatedOnSlider = this.findTouch(
event.changedTouches,
this.touchIdentifier
);
if (touchInitiatedOnSlider === undefined) {
return;
}
let touch = this.findTouch(event.touches, this.touchIdentifier) as Touch;
const position: number =
touch.clientX - this.sliderClientPosition - this.handleWidth / 2;
this.applyValue(this.positionToValue(position));
}
private onTouchEnd(event: TouchEvent): void {
let touchInitiatedOnSlider = this.findTouch(
event.changedTouches,
this.touchIdentifier
);
if (touchInitiatedOnSlider === undefined) {
return;
}
this.touchIdentifier = undefined;
this.eventListenerUtils.detachEventListeners(document, 'touchmove');
this.eventListenerUtils.detachEventListeners(document, 'touchend');
}
private onHandleFocus(): void {
const nativeElement = this.handleElement.nativeElement;
this.eventListenerUtils.attachEventListener(
nativeElement,
'blur',
this.onHandleBlur.bind(this)
);
this.eventListenerUtils.attachEventListener(
nativeElement,
'keydown',
this.onKeyboardEvent.bind(this)
);
}
private onHandleBlur(): void {
const nativeElement = this.handleElement.nativeElement;
this.eventListenerUtils.detachEventListeners(nativeElement, 'blur');
this.eventListenerUtils.detachEventListeners(nativeElement, 'keydown');
this.eventListenerUtils.detachEventListeners(nativeElement, 'keyup');
}
private onKeyboardEvent(event: KeyboardEvent): void {
const keyHandler = this.getKeyHandler(event.code, this.rightToLeft);
if (keyHandler === undefined) {
return;
}
event.preventDefault();
this.applyValue(keyHandler(this.value));
}
protected readonly stepDelta = 1 / 50;
protected readonly pageDelta = 1 / 10;
private getKeyHandler(
keyCode: string,
rightToLeft: boolean
): ((value: number) => number) | undefined {
let increaseStep = (currentValue: number) => currentValue + this.stepDelta;
let decreaseStep = (currentValue: number) => currentValue - this.stepDelta;
let increasePage = (currentValue: number) => currentValue + this.pageDelta;
let decreasePage = (currentValue: number) => currentValue - this.pageDelta;
let stepLeft = rightToLeft ? increaseStep : decreaseStep;
let stepRight = rightToLeft ? decreaseStep : increaseStep;
let home = () => 0;
let end = () => 1;
switch (keyCode) {
case 'ArrowUp':
return increaseStep;
case 'ArrowDown':
return decreaseStep;
case 'ArrowLeft':
return stepLeft;
case 'ArrowRight':
return stepRight;
case 'PageUp':
return increasePage;
case 'PageDown':
return decreasePage;
case 'Home':
return home;
case 'End':
return end;
default:
return undefined;
}
}
private applyValue(value: number): void {
value = this.clampToRange(value);
if (this.value !== value) {
this.value = value;
this.valueChange.emit(this.value);
}
}
private clampToRange(value: number): number {
return Math.min(Math.max(value, 0), 1);
}
} | the_stack |
import { ValueComponentProps, ValueComponent, VNode, mountComponent, createVNode } from 'jeact';
import './index.less';
export interface SingleCascaderOption {
value: any;
label: string;
selected?: boolean;
parent?: SingleCascaderOption;
children?: SingleCascaderOption[];
}
export interface SingleCascaderComponentProps extends ValueComponentProps<any[]> {
placeholder?: string;
options?: any[];
valueField?: string;
labelField?: string;
childrenField?: string;
cacheName?: string;
value?: any;
}
export class SingleCascaderComponent extends ValueComponent<any[]> {
placeholder: string;
valueField: string;
labelField: string;
childrenField: string;
value: any;
cacheName: string;
private _options: any[] = [];
get options(): any[] {
return this._options;
}
set options(value: any[]) {
this._options = value;
this.convertedOptions = this.convert(
value,
this.valueField,
this.labelField,
this.childrenField,
null,
this.value,
);
this.leafOptions = this.leafChildren(this.convertedOptions);
if (this.selectedOptions.length) {
this.selectedIndexes = this.getSelectedIndexes(this.selectedOptions[0]);
this.selectedString = this.getSelectedString(this.selectedOptions[0]);
}
this.loadCommonOption();
this.update();
}
convertedOptions: SingleCascaderOption[];
readonly saveCommonMax = 10;
open = false;
commonOptions: SingleCascaderOption[] = [];
showCommon = true;
selectedIndexes: number[] = [];
selectedString = '';
leafOptions: SingleCascaderOption[] = [];
searchText = '';
searchOptions: any[] = [];
showSearch = false;
get columns(): SingleCascaderOption[][] {
let list = this.convertedOptions;
const result = [list];
for (let i = 0; this.selectedIndexes[i] != null; i++) {
const selectedIndex = this.selectedIndexes[i];
if (
list[selectedIndex] &&
list[selectedIndex].children &&
list[selectedIndex].children.length > 0
) {
list = list[selectedIndex].children;
result.push(list);
} else {
break;
}
}
return result;
}
get selectedOptions(): SingleCascaderOption[] {
return this.leafOptions.filter((value) => value.selected);
}
constructor(args: SingleCascaderComponentProps) {
super(args);
}
writeValue(value: string) {
this.value = value;
if (this.convertedOptions != null) {
this.leafOptions.forEach(
(value1) => (value1.selected = String(this.value) === String(value1.value)),
);
if (this.selectedOptions.length) {
this.selectedIndexes = this.getSelectedIndexes(this.selectedOptions[0]);
this.selectedString = this.getSelectedString(this.selectedOptions[0]);
}
this.update();
}
}
// 组件声明周期hook,当组件创建后调用,此时尚未挂载DOM
beforeMount() {}
// 组件声明周期hook,当组件挂载DOM后调用
mounted() {
document.addEventListener(
'click',
(e: any) => {
if (this.refs.popup) {
const path = e.path || (e.composedPath && e.composedPath());
if (
!(this.refs.popup as HTMLElement).contains(e.target) &&
!path.includes(this.refs.popup)
) {
this.closePopup();
}
}
if (this.refs.search) {
const path = e.path || (e.composedPath && e.composedPath());
if (
!(this.refs.search as HTMLElement).contains(e.target) &&
!path.includes(this.refs.search)
) {
this.closeSearchPopup();
}
}
},
true,
);
}
// 选择
selectOption(option: SingleCascaderOption, level?: number, index?: number) {
if (level != null && index != null) {
this.nextLevel(level, index);
} else {
this.selectedIndexes = this.getSelectedIndexes(option);
}
if (this.isLeaf(option)) {
this.leafOptions.forEach((item) => (item.selected = false));
option.selected = true;
this.selectedString = this.getSelectedString(option);
this.saveCommonOption(option);
this.onChange(option.value);
this.closePopup();
}
this.update();
}
// 展开下一级菜单
nextLevel(level: number, index: number) {
this.selectedIndexes = this.selectedIndexes.slice(0, level);
this.selectedIndexes[level] = index;
this.update();
}
getSelectedIndexes(option: SingleCascaderOption): number[] {
const indexes = [];
let selectedOption = option;
while (selectedOption.parent) {
const index = selectedOption.parent.children.findIndex(
(val) => String(val.value) === String(selectedOption.value),
);
selectedOption = selectedOption.parent;
indexes.unshift(index);
}
// 获取第一级index
const firstIndex = this.convertedOptions.findIndex(
(val) => String(val.value) === String(selectedOption.value),
);
indexes.unshift(firstIndex);
return indexes;
}
getSelectedString(option: SingleCascaderOption): string {
const stringArr = [];
let selectedOption = option;
while (selectedOption.parent) {
const o = selectedOption.parent.children.find(
(val) => String(val.value) === String(selectedOption.value),
);
selectedOption = selectedOption.parent;
stringArr.unshift(o);
}
// 获取第一级index
const firstOption = this.convertedOptions.find(
(val) => String(val.value) === String(selectedOption.value),
);
stringArr.unshift(firstOption);
return stringArr.map((val) => val.label).join(' > ');
}
clear = () => {
this.searchText = '';
this.searchOptions = [];
this.selectedOptions.forEach((value) => {
value.selected = false;
});
this.selectedIndexes = [];
this.selectedString = '';
this.update();
this.onChange([]);
};
searchInput = (e: InputEvent) => {
this.searchText = e.target['value'];
this.update();
};
searchKeydown = (e: KeyboardEvent) => {
if (e.code === 'Enter') {
e.preventDefault();
e.stopPropagation();
this.searchChange();
}
};
searchChange = () => {
if (!this.searchText) {
this.searchOptions = [];
return;
}
const searchedOptionsLinked = this.searchChildren(this.convertedOptions, this.searchText);
this.searchOptions = searchedOptionsLinked.map((value) => {
const text = value.map((value1) => value1.label).join(' > ');
return {
text,
html: text.replace(RegExp(this.searchText, 'ig'), (str) => str.fontcolor('red')),
ids: value.map((value1) => value1.value),
originOption: value[value.length - 1],
};
});
this.openSearchPopup();
this.update();
};
// 递归搜索children
searchChildren(options: SingleCascaderOption[], searchText: string): SingleCascaderOption[][] {
if (!options) {
return [];
}
const lowerCaseSearchText = searchText.toLowerCase();
const searchedOptions = options.filter((value) =>
(value.label || '').toLowerCase().includes(lowerCaseSearchText),
);
const childrenOptionsLinked = this.leafChildrenLinked(searchedOptions);
const notSearchedOptions = options.filter(
(value) => !(value.label || '').toLowerCase().includes(lowerCaseSearchText),
);
const searchedOptionsLinked = notSearchedOptions
.filter((value) => !this.isLeaf(value))
.flatMap((value) => {
return this.searchChildren(value.children, searchText).map((value1) => [value, ...value1]);
});
return [...searchedOptionsLinked, ...childrenOptionsLinked];
}
// options到叶子节点的数组的数组
leafChildrenLinked(options: SingleCascaderOption[]): SingleCascaderOption[][] {
if (!options) {
return [];
}
const leafLinked = options.filter((value) => this.isLeaf(value)).map((value) => [value]);
const childrenLeafLinked = options
.filter((value) => !this.isLeaf(value))
.flatMap((value) => {
// 所有子节点和当前节点,拼成链
return this.leafChildrenLinked(value.children).map((value1) => [value, ...value1]);
});
return [...leafLinked, ...childrenLeafLinked];
}
// 打开搜索弹窗
openSearchPopup = () => {
this.showSearch = true;
this.update();
};
// 关闭搜索弹窗
closeSearchPopup() {
this.showSearch = false;
this.update();
}
openPopup = (e: Event) => {
e.stopPropagation();
this.open = true;
this.update();
};
closePopup() {
this.open = false;
this.searchText = '';
this.searchOptions = [];
this.closeSearchPopup();
this.update();
}
switchCommon = () => {
this.showCommon = !this.showCommon;
this.update();
};
// 格式化外部option为内部option
convert(
options: any[],
valueField,
labelField,
childrenField,
parent: SingleCascaderOption,
value?: any,
): SingleCascaderOption[] {
return (options || []).map((option) => {
const obj: SingleCascaderOption = {
value: option[valueField],
label: option[labelField],
selected: String(value || '') === String(option[valueField]),
parent,
};
obj.children = this.convert(
option[childrenField] || [],
valueField,
labelField,
childrenField,
obj,
value,
);
return obj;
});
}
// 获取所有叶子节点
leafChildren(options: SingleCascaderOption[]): SingleCascaderOption[] {
const childrenLeaf = options.flatMap((value) => this.leafChildren(value.children));
const leaf = options.filter((value) => this.isLeaf(value));
return [...childrenLeaf, ...leaf];
}
isLeaf(option: SingleCascaderOption): boolean {
return !option.children || !option.children.length;
}
// 保存常用选择到localStorage中
saveCommonOption(option: SingleCascaderOption) {
if (this.commonOptions.includes(option) || this.cacheName == null) {
return;
}
this.commonOptions.unshift(option);
if (this.commonOptions.length > this.saveCommonMax) {
this.commonOptions = this.commonOptions.slice(0, this.saveCommonMax);
}
const commonOptions = this.commonOptions.map((value) => value.value);
localStorage.setItem(this.cacheName, JSON.stringify(commonOptions));
}
// 加载localStorage中的常用选择
loadCommonOption() {
const commonOptions: string[] = JSON.parse(localStorage.getItem(this.cacheName)) || [];
this.commonOptions = commonOptions
.map((value) => this.leafOptions.find((value1) => value1.value === value))
.filter((value) => value);
}
render() {
let popup: VNode;
if (this.open) {
popup = (
<div class="bgx-popup" ref="popup">
{/*搜索栏*/}
<div class="bgx-search-bar">
<div class="bgx-search-input" ref="search">
<div class="input-group">
<input
type="text"
class="form-control input-sm"
value={this.searchText}
placeholder="请输入搜索关键字"
oninput={(e) => this.searchInput(e)}
onkeydown={(e) => this.searchKeydown(e)}
onfocus={this.openSearchPopup}
/>
<span class="input-group-btn">
<button class="btn btn-primary btn-sm" type="button" onclick={this.searchChange}>
搜索
</button>
</span>
</div>
{this.searchText && this.showSearch && (
<div class="bgx-search-popup">
{this.searchOptions.length > 1 ? (
<div class="bgx-search-options">
{this.searchOptions.map((value) => (
<div
key={value.ids}
class={[
'bgx-search-option',
this.selectedOptions.includes(value.originOption)
? 'bgx-option-selected'
: '',
].join(' ')}
onclick={() => this.selectOption(value.originOption)}
>
<span dangerouslySetInnerHTML={value.html}></span>
</div>
))}
</div>
) : (
<div class="no-search-result">暂无搜索结果</div>
)}
</div>
)}
</div>
<button class="btn btn-default btn-sm" type="button" onclick={this.clear}>
清空
</button>
</div>
{/*常用选择*/}
<div class="bgx-commonly-used">
<div class="bgx-commonly-used-head">
<label>常用选择</label>
<i onclick={this.switchCommon}>{this.showCommon ? '-' : '+'}</i>
</div>
<div class="bgx-commonly-used-options">
{this.showCommon &&
this.commonOptions.length > 1 &&
this.commonOptions.map((value) => (
<label
key={value.value}
class={[
'bgx-label bgx-commonly-used-option',
this.selectedOptions.includes(value) ? 'bgx-option-selected' : '',
].join(' ')}
onclick={() => this.selectOption(value)}
>
<span>{value.label}</span>
</label>
))}
</div>
</div>
{/*options*/}
<div class="bgx-options">
{this.columns.map(
(value, level) =>
value && (
<div class="bgx-column">
{value.map((value1, index) => (
<div
class={[
'bgx-option',
value1.children && value1.children.length > 0 ? 'bgx-option-next' : '',
index === this.selectedIndexes[level] ? 'bgx-option-selected' : '',
].join(' ')}
onclick={() => this.selectOption(value1, level, index)}
>
<div class="bgx-option-text" title={value1.label}>
{value1.label}
</div>
</div>
))}
</div>
),
)}
</div>
</div>
);
}
return (
<div class="bgx-single-cascader" ref="selector">
<div class="input-group">
<input
type="text"
class="form-control input-sm bgx-input"
value={this.selectedString}
placeholder={this.placeholder}
onclick={this.openPopup}
aria-describedby="basic-addon2"
readonly
/>
</div>
{popup}
</div>
);
}
}
// 挂载为jquery插件
mountComponent({
name: 'singleCascader',
componentType: SingleCascaderComponent,
props: ['valueField', 'labelField', 'childrenField', 'placeholder', 'cacheName'],
}); | the_stack |
import { Workbook } from './../src/workbook';
import { Utils } from './../spec/utils.spec';
describe('Branching Coverage', () => {
it('builtInProperties', (done) => {
let book: Workbook = new Workbook({
builtInProperties: {
author: undefined,
comments: undefined,
category: undefined,
company: undefined,
manager: undefined,
subject: undefined,
title: undefined,
createdDate: undefined
},
worksheets: [{
name: 'FreezeTopRow',
freeze: { row: 2 },
}]
}, 'xlsx');
book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'builtInProperties.xlsx');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
});
it('Rows Add', (done) => {
let book: Workbook = new Workbook({
worksheets: [
{
name: 'Rows Add',
rows: [
{ index: 1, cells: [{ index: 1, value: "This is text" }] },
{ index: 3, cells: [{ index: 1, mergeColumn: 1 }] },
{ index: 4, cells: [{ index: 1, value: "This is text" }, { index: 3, value: "Column Insert" }, { index: 3, value: "New" }] },
{ index: 5, cells: [{ index: 1, value: "This is text" }, { index: 2, value: "Column Insert" }, { index: 2, value: "New" }] },
{ index: 7, cells: [{ index: 1, value: "This is text" }, { index: 2, value: "Column Insert" }, { index: 2, value: "New" }] },
],
}]
}, 'xlsx');
book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'Rows-Add.xlsx');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
});
it('ColumnIndex', (done) => {
try {
let book: Workbook = new Workbook({
worksheets: [
{
name: 'Rows Add',
columns: [
/*column -> 1*/{
width: 100,
}
],
rows: [
{ index: 1, cells: [{ index: 1, value: "This is text" }] },
],
}]
}, 'xlsx');
book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'ColumnWidth.xlsx');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
} catch (error) {
expect("Column index is missing.").toEqual(error.message);
done();
}
});
it('RowIndex', (done) => {
try {
let book: Workbook = new Workbook({
worksheets: [
{
name: 'Rows Add',
rows: [
{ cells: [{ index: 1, value: "This is text" }] },
],
}]
}, 'xlsx');
book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'RowIndex.xlsx');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
} catch (error) {
expect("Row index is missing.").toEqual(error.message);
done();
}
});
it('CellIndex', (done) => {
try {
let book: Workbook = new Workbook({
worksheets: [
{
name: 'Rows Add',
rows: [
{ index: 1, cells: [{ value: "This is text" }] },
],
}]
}, 'xlsx');
book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'CellIndex.xlsx');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
} catch (error) {
expect("Cell index is missing.").toEqual(error.message);
done();
}
});
it('Worksheet', (done) => {
try {
let book: Workbook = new Workbook({
}, 'xlsx');
book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'Worksheet.xlsx');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
} catch (error) {
expect("Worksheet is expected.").toEqual(error.message);
done();
}
});
it('AllBorders', (done) => {
let book: Workbook = new Workbook({
worksheets: [
{
name: 'Rows Add',
rows: [
/*row -> 11*/ {
index: 1, cells: [
/*column ->1*/
{
index: 1, value: 'all borders',
/*Cell Style - All Borders(left, right, top, bottom)
Allowed line styles 'thin', 'medium', 'thick'
*/
style: {
borders: { color: '#C67878', lineStyle: 'thick' }
}
}]
},
/*row -> 11*/ {
index: 2, cells: [
/*column ->1*/
{
index: 1, value: 'all borders',
/*Cell Style - All Borders(left, right, top, bottom)
Allowed line styles 'thin', 'medium', 'thick'
*/
style: {
borders: { color: '#C67978', lineStyle: 'thin' }
}
}]
},
/*row -> 11*/ {
index: 3, cells: [
/*column ->1*/
{
index: 1, value: 'all borders',
/*Cell Style - All Borders(left, right, top, bottom)
Allowed line styles 'thin', 'medium', 'thick'
*/
style: {
borders: { color: '#C67978', lineStyle: 'medium' }
}
}]
},
],
}]
}, 'xlsx');
book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'AllBorders.xlsx');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
});
it('EmptyCell', (done) => {
let book: Workbook = new Workbook({
worksheets: [
{
name: 'Rows Add',
rows: [
{ index: 1, cells: [{ index: 1, style: { numberFormat: 'C' } } ] },
],
}]
}, 'xlsx');
book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'EmptyCell.xlsx');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
});
// it('Wrong save type', (done) => {
// try {
// let book: Workbook = new Workbook({
// worksheets: [
// {
// name: 'Rows Add',
// rows: [
// { index: 1, cells: [{ index: 1 }, { index: 2, value: "test" }] },
// ],
// }]
// }, 'csv');
// book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => {
// if (Utils.isDownloadEnabled) {
// Utils.download(xlBlob.blobData, 'Wrong-save-type.xlsx');
// }
// let reader: FileReader = new FileReader();
// reader.readAsArrayBuffer(xlBlob.blobData);
// reader.onload = (): void => {
// if (reader.readyState == 2) { // DONE == 2
// expect(reader.result.byteLength).toBeGreaterThanOrEqual(0);
// done();
// }
// }
// });
// } catch (error) {
// expect('Save type and file extension is different.').toEqual(error.message);
// done();
// }
// });
it('PrintTitleCoverage', (done) => {
let book: Workbook = new Workbook({
worksheets: [
{
name: 'PrintTitlesRow',
printTitle: { fromRow: 1 },
},
{
name: 'PrintTitlesCol',
printTitle: { fromColumn: 1 },
},
{
name: 'PrintTitles',
printTitle: {},
},
]
}, 'xlsx');
book.saveAsBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PrintTitleCoverage.xlsx');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
});
}); | the_stack |
import { Utils } from '@rpgjs/common'
import { RpgClientEngine } from './RpgClientEngine';
// keyboard handling
const keyCodeTable = {
3: 'break',
8: 'backspace', // backspace / delete
9: 'tab',
12: 'clear',
13: 'enter',
16: 'shift',
17: 'ctrl',
18: 'alt',
19: 'pause/break',
20: 'caps lock',
27: 'escape',
28: 'conversion',
29: 'non-conversion',
32: 'space',
33: 'page up',
34: 'page down',
35: 'end',
36: 'home',
37: 'left',
38: 'up',
39: 'right',
40: 'down',
41: 'select',
42: 'print',
43: 'execute',
44: 'Print Screen',
45: 'insert',
46: 'delete',
48: '0',
49: '1',
50: '2',
51: '3',
52: '4',
53: '5',
54: '6',
55: '7',
56: '8',
57: '9',
58: ':',
59: 'semicolon (firefox), equals',
60: '<',
61: 'equals (firefox)',
63: 'ß',
64: '@',
65: 'a',
66: 'b',
67: 'c',
68: 'd',
69: 'e',
70: 'f',
71: 'g',
72: 'h',
73: 'i',
74: 'j',
75: 'k',
76: 'l',
77: 'm',
78: 'n',
79: 'o',
80: 'p',
81: 'q',
82: 'r',
83: 's',
84: 't',
85: 'u',
86: 'v',
87: 'w',
88: 'x',
89: 'y',
90: 'z',
91: 'Windows Key / Left ⌘ / Chromebook Search key',
92: 'right window key',
93: 'Windows Menu / Right ⌘',
96: 'numpad 0',
97: 'numpad 1',
98: 'numpad 2',
99: 'numpad 3',
100: 'numpad 4',
101: 'numpad 5',
102: 'numpad 6',
103: 'numpad 7',
104: 'numpad 8',
105: 'numpad 9',
106: 'multiply',
107: 'add',
108: 'numpad period (firefox)',
109: 'subtract',
110: 'decimal point',
111: 'divide',
112: 'f1',
113: 'f2',
114: 'f3',
115: 'f4',
116: 'f5',
117: 'f6',
118: 'f7',
119: 'f8',
120: 'f9',
121: 'f10',
122: 'f11',
123: 'f12',
124: 'f13',
125: 'f14',
126: 'f15',
127: 'f16',
128: 'f17',
129: 'f18',
130: 'f19',
131: 'f20',
132: 'f21',
133: 'f22',
134: 'f23',
135: 'f24',
144: 'num lock',
145: 'scroll lock',
160: '^',
161: '!',
163: '#',
164: '$',
165: 'ù',
166: 'page backward',
167: 'page forward',
169: 'closing paren (AZERTY)',
170: '*',
171: '~ + * key',
173: 'minus (firefox), mute/unmute',
174: 'decrease volume level',
175: 'increase volume level',
176: 'next',
177: 'previous',
178: 'stop',
179: 'play/pause',
180: 'e-mail',
181: 'mute/unmute (firefox)',
182: 'decrease volume level (firefox)',
183: 'increase volume level (firefox)',
186: 'semi-colon / ñ',
187: 'equal sign',
188: 'comma',
189: 'dash',
190: 'period',
191: 'forward slash / ç',
192: 'grave accent / ñ / æ',
193: '?, / or °',
194: 'numpad period (chrome)',
219: 'open bracket',
220: 'back slash',
221: 'close bracket / å',
222: 'single quote / ø',
223: '`',
224: 'left or right ⌘ key (firefox)',
225: 'altgr',
226: '< /git >',
230: 'GNOME Compose Key',
231: 'ç',
233: 'XF86Forward',
234: 'XF86Back',
240: 'alphanumeric',
242: 'hiragana/katakana',
243: 'half-width/full-width',
244: 'kanji',
255: 'toggle touchpad'
};
const { isArray } = Utils
const inverse = (obj) => {
const newObj = {}
for (let key in obj) {
const val = obj[key]
newObj[val] = key
}
return newObj
}
const inverseKeyCodeTable = inverse(keyCodeTable)
export interface ControlOptions {
repeat?: boolean
bind: string | string[]
method?: Function
}
export interface Controls {
[controlName: string]: ControlOptions
}
type BoundKey = { actionName: string, options: any }
export class KeyboardControls {
private gameEngine
private keyState = {}
private boundKeys = {}
private stop = false
private lastKeyPressed
private _controlsOptions = {}
constructor(private clientEngine: RpgClientEngine) {
const { globalConfig } = clientEngine
this.gameEngine = clientEngine.gameEngine;
this.setupListeners();
if (globalConfig.inputs) this.setInputs(globalConfig.inputs)
this.gameEngine.on('client__preStep', () => {
for (let keyName of Object.keys(this.boundKeys)) {
if (this.keyState[keyName] && this.keyState[keyName].isDown) {
const { repeat, method } = this.boundKeys[keyName].options
// handle repeat press
if (repeat || this.keyState[keyName].count == 0) {
// callback to get live parameters if function
let parameters = this.boundKeys[keyName].parameters;
if (typeof parameters === "function") {
parameters = parameters();
}
if (method) {
method(this.boundKeys[keyName])
}
else {
this.clientEngine.sendInput(this.boundKeys[keyName].actionName);
}
this.keyState[keyName].count++;
}
}
}
});
}
private setupListeners() {
document.addEventListener('keydown', (e) => { this.onKeyChange(e, true);});
document.addEventListener('keyup', (e) => { this.onKeyChange(e, false);});
}
private bindKey(keys, actionName, options, parameters?) {
if (!Array.isArray(keys)) keys = [keys];
let keyOptions = Object.assign({
repeat: false
}, options);
keys.forEach(keyName => {
this.boundKeys[keyName] = { actionName, options: keyOptions, parameters: parameters };
});
}
private applyKeyDown(name: string) {
const code = inverseKeyCodeTable[name]
const e: any = new Event('keydown')
e.keyCode = code
this.onKeyChange(e, true)
}
private applyKeyUp(name: string) {
const code = inverseKeyCodeTable[name]
const e: any = new Event('keyup')
e.keyCode = code
this.onKeyChange(e, false)
}
private applyKeyPress(name: string) {
this.applyKeyDown(name)
setTimeout(() => {
this.applyKeyUp(name)
}, 200)
}
private onKeyChange(e, isDown) {
e = e || window.event;
let keyName = keyCodeTable[e.keyCode];
const isStopped = this.stop
if (isDown) this.clientEngine.keyChange.next(keyName)
if (isStopped) return
if (keyName && this.boundKeys[keyName]) {
if (this.keyState[keyName] == null) {
this.keyState[keyName] = {
count: 0
};
}
this.keyState[keyName].isDown = isDown;
// key up, reset press count
if (!isDown) this.keyState[keyName].count = 0;
// keep reference to the last key pressed to avoid duplicates
this.lastKeyPressed = isDown ? e.keyCode : null;
// this.renderer.onKeyChange({ keyName, isDown });
e.preventDefault();
}
}
/**
* From the name of the entry, we retrieve the control information
*
* ```ts
* import { Input } from '@rpgjs/client'
*
* // In method hooks, client is RpgClientEngine
* client.controls.getControl(Input.Enter)
* if (control) {
* console.log(control.actionName) // action
* }
* ```
* @title Get Control
* @method getControl(inputName)
* @param {string} inputName
* @returns { { actionName: string, options: any } | undefined }
* @memberof KeyboardControls
*/
getControl(inputName: string): BoundKey | undefined {
return this.boundKeys[inputName]
}
/**
* Triggers an input according to the name of the control
*
* ```ts
* import { Control } from '@rpgjs/client'
*
* // In method hooks, client is RpgClientEngine
* client.controls.applyControl(Control.Action)
* ```
*
* You can put a second parameter or indicate on whether the key is pressed or released
*
* ```ts
* import { Control } from '@rpgjs/client'
*
* client.controls.applyControl(Control.Up, true) // keydown
* client.controls.applyControl(Control.Up, false) // keyup
* ```
* @title Apply Control
* @method applyControl(controlName,isDown)
* @param {string} controlName
* @param {boolean} [isDown]
* @memberof KeyboardControls
*/
applyControl(controlName: string, isDown?: boolean | undefined) {
const control = this._controlsOptions[controlName]
if (control) {
const input = isArray(control.bind) ? control.bind[0] : control.bind
if (isDown === undefined) {
this.applyKeyPress(input as string)
}
else if (isDown) {
this.applyKeyDown(input as string)
}
else {
this.applyKeyUp(input as string)
}
}
}
/**
* Stop listening to the inputs. Pressing a key won't do anything
*
* @title Stop Inputs
* @method stopInputs()
* @returns {void}
* @memberof KeyboardControls
*/
stopInputs() {
this.stop = true
}
/**
* Listen to the inputs again
*
* @title Listen Inputs
* @method listenInputs()
* @returns {void}
* @memberof KeyboardControls
*/
listenInputs() {
this.stop = false
}
/**
* Assign custom inputs to the scene
*
* The object is the following:
*
* * the key of the object is the name of the control. Either it is existing controls (Up, Dow, Left, Right, Action, Back) or customized controls
* * The value is an object representing control information:
* * repeat {boolean} The key can be held down to repeat the action. (false by default)
* * bind {string | string[]} To which key is linked the control
* * method {Function} Function to be triggered. If you do not set this property, the name of the control is sent directly to the server.
*
* ```ts
* import { Control, Input } from '@rpgjs/client'
*
* // In method hooks, client is RpgClientEngine
* client.controls.setInputs({
[Control.Up]: {
repeat: true,
bind: Input.Up
},
[Control.Down]: {
repeat: true,
bind: Input.Down
},
[Control.Right]: {
repeat: true,
bind: Input.Right
},
[Control.Left]: {
repeat: true,
bind: Input.Left
},
[Control.Action]: {
bind: [Input.Space, Input.Enter]
},
[Control.Back]: {
bind: Input.Escape
},
// The myscustom1 control is sent to the server when the A key is pressed.
mycustom1: {
bind: Input.A
},
// the myAction method is executed when the B key is pressed
mycustom2: {
bind: Input.B,
method({ actionName }) {
console.log('cool', actionName)
}
}
})
*
* ```
* @enum {string} Control
*
* Control.Up | up
* Control.Down | down
* Control.Left | left
* Control.Right | right
* Control.Action | action
* Control.Back | back
* @title Set Inputs
* @method setInputs(inputs)
* @param {object} inputs
* @memberof KeyboardControls
*/
setInputs(inputs: Controls) {
if (!inputs) return
this.boundKeys = {}
for (let control in inputs) {
const option = inputs[control]
const { method, bind } = option
if (method) {
option.method = method
}
let inputsKey: any = bind
if (!isArray(inputsKey)) {
inputsKey = [bind]
}
for (let input of inputsKey) {
this.bindKey(input, control, option)
}
}
this._controlsOptions = inputs
}
} | the_stack |
import { Component, OnInit } from '@angular/core';
import { KafkaService } from '../../service/kafka.service';
import { Router, ActivatedRoute } from '@angular/router';
import { KafkaTopic } from '../../model/kafka-topic';
import { MetronAlerts } from '../../shared/metron-alerts';
import { SensorParserConfigService } from '../../service/sensor-parser-config.service';
import { StormService } from '../../service/storm.service';
import { TopologyStatus } from '../../model/topology-status';
import { SensorParserConfigHistoryService } from '../../service/sensor-parser-config-history.service';
import { SensorParserConfigHistory } from '../../model/sensor-parser-config-history';
import { SensorEnrichmentConfigService } from '../../service/sensor-enrichment-config.service';
import { SensorEnrichmentConfig } from '../../model/sensor-enrichment-config';
import { RiskLevelRule } from '../../model/risk-level-rule';
import { HdfsService } from '../../service/hdfs.service';
import { RestError } from '../../model/rest-error';
import { GrokValidationService } from '../../service/grok-validation.service';
import { SensorParserConfig } from '../../model/sensor-parser-config';
@Component({
selector: 'metron-config-sensor-parser-readonly',
templateUrl: 'sensor-parser-config-readonly.component.html',
styleUrls: ['sensor-parser-config-readonly.component.scss']
})
export class SensorParserConfigReadonlyComponent implements OnInit {
selectedSensorName: string;
startStopInProgress: boolean = false;
kafkaTopic: KafkaTopic = new KafkaTopic();
sensorParserConfigHistory: SensorParserConfigHistory = new SensorParserConfigHistory();
sensorParserConfig: SensorParserConfig = new SensorParserConfig();
topologyStatus: TopologyStatus = new TopologyStatus();
sensorEnrichmentConfig: SensorEnrichmentConfig = new SensorEnrichmentConfig();
grokStatement = {};
transformsConfigKeys: string[] = [];
transformsConfigMap: {} = {};
rules: RiskLevelRule[] = [];
transformLinkText = 'show more';
threatTriageLinkText = 'show more';
editViewMetaData: {
label?: string;
value?: string;
type?: string;
model?: string;
boldTitle?: boolean;
}[] = [
{ type: 'SEPARATOR', model: '', value: '' },
{
label: 'PARSER',
model: 'sensorParserConfigHistory',
value: 'parserClassName'
},
{
label: 'LAST UPDATED',
model: 'sensorParserConfigHistory',
value: 'modifiedByDate'
},
{
label: 'LAST EDITOR',
model: 'sensorParserConfigHistory',
value: 'modifiedBy'
},
{ label: 'STATE', model: 'topologyStatus', value: 'sensorStatus' },
{
label: 'ORIGINATOR',
model: 'sensorParserConfigHistory',
value: 'createdBy'
},
{
label: 'CREATION DATE',
model: 'sensorParserConfigHistory',
value: 'createdDate'
},
{ type: 'SPACER', model: '', value: '' },
{
label: 'STORM',
model: 'topologyStatus',
value: 'status',
boldTitle: true
},
{ label: 'LATENCY', model: 'topologyStatus', value: 'latency' },
{ label: 'THROUGHPUT', model: 'topologyStatus', value: 'throughput' },
{ label: 'EMITTED(10 MIN)', model: 'topologyStatus', value: 'emitted' },
{ label: 'ACKED(10 MIN)', model: 'topologyStatus', value: 'acked' },
{ label: 'NUM WORKERS', model: 'sensorParserConfig', value: 'numWorkers' },
{ label: 'NUM ACKERS', model: 'sensorParserConfig', value: 'numAckers' },
{
label: 'SPOUT PARALLELISM',
model: 'sensorParserConfig',
value: 'spoutParallelism'
},
{
label: 'SPOUT NUM TASKS',
model: 'sensorParserConfig',
value: 'spoutNumTasks'
},
{
label: 'PARSER PARALLELISM',
model: 'sensorParserConfig',
value: 'parserParallelism'
},
{
label: 'PARSER NUM TASKS',
model: 'sensorParserConfig',
value: 'parserNumTasks'
},
{
label: 'ERROR WRITER PARALLELISM',
model: 'sensorParserConfig',
value: 'errorWriterParallelism'
},
{
label: 'ERROR NUM TASKS',
model: 'sensorParserConfig',
value: 'errorWriterNumTasks'
},
{ type: 'SPACER', model: '', value: '' },
{
label: 'KAFKA',
model: 'kafkaTopic',
value: 'currentKafkaStatus',
boldTitle: true
},
{ label: 'PARTITONS', model: 'kafkaTopic', value: 'numPartitions' },
{
label: 'REPLICATION FACTOR',
model: 'kafkaTopic',
value: 'replicationFactor'
},
{ type: 'SEPARATOR', model: '', value: '' },
{ label: '', model: 'grokStatement', value: 'grokPattern' },
{ type: 'TITLE', model: '', value: 'Schema' },
{ label: '', model: 'transforms', value: '' },
{ type: 'SEPARATOR', model: '', value: '' },
{ type: 'TITLE', model: '', value: 'Threat Triage Rules' },
{ label: '', model: 'threatTriageRules', value: '' }
];
constructor(
private sensorParserConfigHistoryService: SensorParserConfigHistoryService,
private sensorParserConfigService: SensorParserConfigService,
private sensorEnrichmentService: SensorEnrichmentConfigService,
private stormService: StormService,
private kafkaService: KafkaService,
private hdfsService: HdfsService,
private grokValidationService: GrokValidationService,
private activatedRoute: ActivatedRoute,
private router: Router,
private metronAlerts: MetronAlerts
) {}
getSensorInfo(): void {
this.sensorParserConfigHistoryService
.get(this.selectedSensorName)
.subscribe((results: SensorParserConfigHistory) => {
this.sensorParserConfigHistory = results;
this.sensorParserConfig = this.sensorParserConfigHistory.config;
this.setGrokStatement();
this.setTransformsConfigKeys();
let items = this.sensorParserConfigHistory.config.parserClassName.split(
'.'
);
this.sensorParserConfigHistory['parserClassName'] = items[
items.length - 1
]
.replace('Basic', '')
.replace('Parser', '');
});
}
getSensorStatusService() {
this.stormService.getStatus(this.selectedSensorName).subscribe(
(results: TopologyStatus) => {
this.topologyStatus = results;
},
error => {
this.topologyStatus.status = 'Stopped';
}
);
}
getKafkaData(): void {
this.kafkaService.get(this.selectedSensorName).subscribe(
(results: KafkaTopic) => {
this.kafkaTopic = results;
this.kafkaService.sample(this.selectedSensorName).subscribe(
(sampleData: string) => {
this.kafkaTopic['currentKafkaStatus'] =
sampleData && sampleData.length > 0 ? 'Emitting' : 'Not Emitting';
},
error => {
this.kafkaTopic['currentKafkaStatus'] = 'Not Emitting';
}
);
},
error => {
this.kafkaTopic['currentKafkaStatus'] = 'No Kafka Topic';
}
);
}
getEnrichmentData() {
this.sensorEnrichmentService
.get(this.selectedSensorName)
.subscribe(sensorEnrichmentConfig => {
this.sensorEnrichmentConfig = sensorEnrichmentConfig;
this.rules =
sensorEnrichmentConfig.threatIntel.triageConfig.riskLevelRules;
});
}
getTopologyStatus(key: string): string {
if (key === 'latency') {
return this.topologyStatus.latency >= 0
? this.topologyStatus.latency + 'ms'
: '-';
} else if (key === 'throughput') {
return this.topologyStatus.throughput >= 0
? Math.round(this.topologyStatus.throughput * 100) / 100 + 'kb/s'
: '-';
} else if (key === 'emitted') {
return this.topologyStatus.emitted >= 0
? this.topologyStatus.emitted + ''
: '-';
} else if (key === 'acked') {
return this.topologyStatus.acked >= 0
? this.topologyStatus.acked + ''
: '-';
} else if (key === 'sensorStatus') {
if (this.topologyStatus.status === 'ACTIVE') {
return 'Enabled';
} else if (this.topologyStatus.status === 'INACTIVE') {
return 'Disabled';
} else {
return '-';
}
} else if (key === 'status') {
if (this.topologyStatus.status === 'ACTIVE') {
return 'Running';
} else if (this.topologyStatus.status === 'INACTIVE') {
return 'Disabled';
} else {
return 'Stopped';
}
}
return this.topologyStatus[key] ? this.topologyStatus[key] : '-';
}
ngOnInit() {
this.activatedRoute.params.subscribe(params => {
this.selectedSensorName = params['id'];
this.getData();
});
}
getData() {
this.startStopInProgress = false;
this.getSensorInfo();
this.getSensorStatusService();
this.getKafkaData();
this.getEnrichmentData();
}
setGrokStatement() {
if (
this.sensorParserConfigHistory.config &&
this.sensorParserConfigHistory.config.parserConfig
) {
let path = this.sensorParserConfigHistory.config.parserConfig['grokPath'];
if (path) {
this.hdfsService.read(path).subscribe(
contents => {
this.grokStatement = contents;
},
(hdfsError: RestError) => {
this.grokValidationService.getStatement(path).subscribe(
contents => {
this.grokStatement = contents;
},
(grokError: RestError) => {
this.metronAlerts.showErrorMessage(
'Could not find grok statement in HDFS or classpath at ' +
path
);
}
);
}
);
}
}
}
setTransformsConfigKeys() {
if (
this.sensorParserConfigHistory.config &&
this.sensorParserConfigHistory.config.fieldTransformations &&
this.sensorParserConfigHistory.config.fieldTransformations.length > 0
) {
this.transformsConfigKeys = [];
for (let transforms of this.sensorParserConfigHistory.config
.fieldTransformations) {
if (transforms.config) {
for (let key of Object.keys(transforms.config)) {
if (this.transformsConfigKeys.indexOf(key) === -1) {
this.transformsConfigMap[key] = [];
this.transformsConfigKeys.push(key);
}
this.transformsConfigMap[key].push(transforms.config[key]);
}
}
}
this.transformsConfigKeys = this.transformsConfigKeys.sort();
}
}
getTransformsOutput(): string {
if (
this.sensorParserConfigHistory.config &&
this.sensorParserConfigHistory.config.fieldTransformations &&
this.sensorParserConfigHistory.config.fieldTransformations.length > 0
) {
let output = [];
for (let transforms of this.sensorParserConfigHistory.config
.fieldTransformations) {
if (transforms.output) {
output = output.concat(transforms.output);
}
}
output = output.sort().filter(function(item, pos, self) {
return self.indexOf(item) === pos;
});
return output.join(', ');
}
return '-';
}
goBack() {
this.router.navigateByUrl('/sensors');
}
onEditSensor() {
this.router.navigateByUrl(
'/sensors(dialog:sensors-config/' + this.selectedSensorName + ')'
);
}
onStartSensor() {
this.toggleStartStopInProgress();
let name = this.selectedSensorName;
this.stormService.startParser(name).subscribe(
result => {
this.metronAlerts.showSuccessMessage('Started sensor ' + name);
this.toggleStartStopInProgress();
this.getData();
},
error => {
this.metronAlerts.showErrorMessage('Unable to start sensor ' + name);
this.toggleStartStopInProgress();
}
);
}
onStopSensor() {
this.toggleStartStopInProgress();
let name = this.selectedSensorName;
this.stormService.stopParser(name).subscribe(
result => {
this.metronAlerts.showSuccessMessage('Stopped sensor ' + name);
this.toggleStartStopInProgress();
this.getData();
},
error => {
this.metronAlerts.showErrorMessage('Unable to stop sensor ' + name);
this.toggleStartStopInProgress();
}
);
}
onEnableSensor() {
this.toggleStartStopInProgress();
let name = this.selectedSensorName;
this.stormService.activateParser(name).subscribe(
result => {
this.metronAlerts.showSuccessMessage('Enabled sensor ' + name);
this.toggleStartStopInProgress();
this.getData();
},
error => {
this.metronAlerts.showErrorMessage('Unable to enabled sensor ' + name);
this.toggleStartStopInProgress();
}
);
}
onDisableSensor() {
this.toggleStartStopInProgress();
let name = this.selectedSensorName;
this.stormService.deactivateParser(name).subscribe(
result => {
this.metronAlerts.showSuccessMessage('Disabled sensor ' + name);
this.toggleStartStopInProgress();
this.getData();
},
error => {
this.metronAlerts.showErrorMessage('Unable to disable sensor ' + name);
this.toggleStartStopInProgress();
}
);
}
onDeleteSensor() {
this.toggleStartStopInProgress();
let name = this.selectedSensorName;
this.sensorParserConfigService.deleteSensorParserConfig(name).subscribe(
result => {
this.metronAlerts.showSuccessMessage('Deleted sensor ' + name);
this.toggleStartStopInProgress();
this.sensorParserConfigService.dataChangedSource.next([name]);
this.goBack();
},
error => {
this.metronAlerts.showErrorMessage('Unable to delete sensor ' + name);
this.toggleStartStopInProgress();
}
);
}
toggleStartStopInProgress() {
this.startStopInProgress = !this.startStopInProgress;
}
getRuleDisplayName(): string {
return this.rules.map(x => this.getDisplayName(x)).join(', ');
}
getDisplayName(riskLevelRule: RiskLevelRule): string {
if (riskLevelRule.name) {
return riskLevelRule.name;
} else {
return riskLevelRule.rule ? riskLevelRule.rule : '';
}
}
toggleTransformLink() {
return (this.transformLinkText =
this.transformLinkText === 'show more' ? 'show less' : 'show more');
}
toggleThreatTriageLink() {
return (this.threatTriageLinkText =
this.threatTriageLinkText === 'show more' ? 'show less' : 'show more');
}
isStartHidden() {
return (
this.topologyStatus.status === 'ACTIVE' ||
this.topologyStatus.status === 'INACTIVE'
);
}
isStopHidden() {
return (
this.topologyStatus.status === 'KILLED' ||
this.topologyStatus.status === 'Stopped'
);
}
isEnableHidden() {
return (
this.topologyStatus.status === 'ACTIVE' ||
this.topologyStatus.status === 'KILLED' ||
this.topologyStatus.status === 'Stopped'
);
}
isDisableHidden() {
return (
this.topologyStatus.status === 'INACTIVE' ||
this.topologyStatus.status === 'KILLED' ||
this.topologyStatus.status === 'Stopped'
);
}
} | the_stack |
import {
DecodeRawTransactionResult,
VerboseRawTransactionResult
} from "bitcoin-com-rest"
import * as chai from "chai"
import * as util from "util"
import { BITBOX, REST_URL } from "../../lib/BITBOX"
import { RawTransactions } from "../../lib/RawTransactions"
import axios from "axios"
import * as sinon from "sinon"
// consts
const bitbox: BITBOX = new BITBOX()
const assert: Chai.AssertStatic = chai.assert
const rtMock = require("./mocks/rawtransactions-mock")
// Used for debugging
util.inspect.defaultOptions = { depth: 1 }
describe("#RawTransactions", (): void => {
let sandbox: any
beforeEach(() => (sandbox = sinon.sandbox.create()))
afterEach(() => sandbox.restore())
describe("#RawTransactionsConstructor", (): void => {
it("should create instance of RawTransactions", (): void => {
const rawtransactions: RawTransactions = new RawTransactions()
assert.equal(rawtransactions instanceof RawTransactions, true)
})
it("should have a restURL property", (): void => {
const rawtransactions: RawTransactions = new RawTransactions()
assert.equal(rawtransactions.restURL, REST_URL)
})
})
describe("#decodeRawTransaction", (): void => {
it("should decode tx for a single hex", async (): Promise<any> => {
// Mock the call to rest to prevent live network calls.
const resolved = new Promise(r => r({ data: rtMock.decodedTx }))
sandbox.stub(axios, "get").returns(resolved)
const hex: string =
"0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000"
const result:
| DecodeRawTransactionResult
| DecodeRawTransactionResult[] = await bitbox.RawTransactions.decodeRawTransaction(
hex
)
//console.log(`result: ${JSON.stringify(result,null,2)}`)
assert.hasAnyKeys(result, [
"txid",
"hash",
"size",
"version",
"locktime",
"vin",
"vout"
])
if (!Array.isArray(result)) {
assert.isArray(result.vin)
assert.isArray(result.vout)
}
})
it("should decode an array of tx hexes", async (): Promise<any> => {
// Mock the call to rest to prevent live network calls.
const testData = [rtMock.decodedTx, rtMock.decodedTx]
const resolved = new Promise(r => r({ data: testData }))
sandbox.stub(axios, "post").returns(resolved)
const hexes: string[] = [
"0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000",
"0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000"
]
const result:
| DecodeRawTransactionResult
| DecodeRawTransactionResult[] = await bitbox.RawTransactions.decodeRawTransaction(
hexes
)
assert.isArray(result)
if (Array.isArray(result)) {
assert.hasAnyKeys(result[0], [
"txid",
"hash",
"size",
"version",
"locktime",
"vin",
"vout"
])
assert.isArray(result[0].vin)
assert.isArray(result[0].vout)
}
})
it(`should pass error from server to user`, async (): Promise<any> => {
try {
// Mock out data for unit test, to prevent live network call.
sandbox
.stub(axios, "get")
.throws("error", "Input must be a string or array of strings")
const addr: any = 12345
await bitbox.RawTransactions.decodeRawTransaction(addr)
assert.equal(true, false, "Unexpected result!")
} catch (err) {
//console.log(`err: ${util.inspect(err)}`)
assert.include(
err.message,
`Input must be a string or array of strings`
)
}
})
})
describe("#getRawTransaction", (): void => {
it("should decode a single txid, with concise output", async (): Promise<
any
> => {
// Mock the call to rest to prevent live network calls.
const resolved = new Promise(r => r({ data: rtMock.rawTx }))
sandbox.stub(axios, "get").returns(resolved)
const txid: string =
"23213453b4642a73b4fc30d3112d72549ca153a8707255b14373b59e43558de1"
const verbose: boolean = false
const result:
| VerboseRawTransactionResult
| VerboseRawTransactionResult[]
| string
| string[] = await bitbox.RawTransactions.getRawTransaction(
txid,
verbose
)
//console.log(`result: ${JSON.stringify(result,null,2)}`)
assert.isString(result)
})
it("should decode a single txid, with verbose output", async (): Promise<
any
> => {
// Mock the call to rest to prevent live network calls.
const resolved = new Promise(r => r({ data: rtMock.decodedTx }))
sandbox.stub(axios, "get").returns(resolved)
const txid: string =
"23213453b4642a73b4fc30d3112d72549ca153a8707255b14373b59e43558de1"
const verbose: boolean = true
const result:
| VerboseRawTransactionResult
| VerboseRawTransactionResult[]
| string
| string[] = await bitbox.RawTransactions.getRawTransaction(
txid,
verbose
)
//console.log(`result: ${JSON.stringify(result,null,2)}`)
assert.hasAnyKeys(result, [
"hex",
"txid",
"hash",
"size",
"version",
"locktime",
"vin",
"vout",
"blockhash",
"confirmations",
"time",
"blocktime"
])
if (!Array.isArray(result) && result instanceof Object) {
assert.isArray(result.vin)
assert.isArray(result.vout)
}
})
it("should decode an array of txids, with a concise output", async (): Promise<
any
> => {
// Mock the call to rest to prevent live network calls.
const testData = [rtMock.rawTx, rtMock.rawTx]
const resolved = new Promise(r => r({ data: testData }))
sandbox.stub(axios, "post").returns(resolved)
const txid: string[] = [
"23213453b4642a73b4fc30d3112d72549ca153a8707255b14373b59e43558de1",
"b25d24fbb42d84812ed2cb55797f10fdec41afc7906ab563d1ec8c8676a2037f"
]
const verbose: boolean = false
const result:
| VerboseRawTransactionResult
| VerboseRawTransactionResult[]
| string
| string[] = await bitbox.RawTransactions.getRawTransaction(
txid,
verbose
)
assert.isArray(result)
if (Array.isArray(result)) assert.isString(result[0])
})
it("should decode an array of txids, with a verbose output", async (): Promise<
any
> => {
// Mock the call to rest to prevent live network calls.
const testData = [rtMock.decodedTx, rtMock.decodedTx]
const resolved = new Promise(r => r({ data: testData }))
sandbox.stub(axios, "post").returns(resolved)
const txid: string[] = [
"23213453b4642a73b4fc30d3112d72549ca153a8707255b14373b59e43558de1",
"b25d24fbb42d84812ed2cb55797f10fdec41afc7906ab563d1ec8c8676a2037f"
]
const verbose: boolean = true
const result:
| VerboseRawTransactionResult
| VerboseRawTransactionResult[]
| string
| string[] = await bitbox.RawTransactions.getRawTransaction(
txid,
verbose
)
assert.isArray(result)
if (Array.isArray(result)) {
assert.hasAnyKeys(result[0], [
"hex",
"txid",
"hash",
"size",
"version",
"locktime",
"vin",
"vout",
"blockhash",
"confirmations",
"time",
"blocktime"
])
// TODO uncomment this test and fix ts error
// assert.isArray(result[0].vin);
// assert.isArray(result[0].vout);
}
})
it(`should pass error from server to user`, async (): Promise<any> => {
try {
// Mock out data for unit test, to prevent live network call.
sandbox
.stub(axios, "get")
.throws("error", "Input must be a string or array of strings")
const txid: any = 12345
await bitbox.RawTransactions.getRawTransaction(txid, false)
assert.equal(true, false, "Unexpected result!")
} catch (err) {
//console.log(`err: ${util.inspect(err)}`)
assert.include(
err.message,
`Input must be a string or array of strings`
)
}
})
})
describe("#decodeScript", () => {
it("should decode script for a single hex", async (): Promise<any> => {
// Mock the call to rest to prevent live network calls.
const resolved = new Promise(r => r({ data: rtMock.decodedScript }))
sandbox.stub(axios, "get").returns(resolved)
const hex: string =
"4830450221009a51e00ec3524a7389592bc27bea4af5104a59510f5f0cfafa64bbd5c164ca2e02206c2a8bbb47eabdeed52f17d7df668d521600286406930426e3a9415fe10ed592012102e6e1423f7abde8b70bca3e78a7d030e5efabd3eb35c19302542b5fe7879c1a16"
const result = await bitbox.RawTransactions.decodeScript(hex)
//console.log(`result: ${JSON.stringify(result,null,2)}`)
assert.hasAllKeys(result, ["asm", "type", "p2sh"])
})
it("should decode an array of tx hexes", async () => {
// Mock the call to rest to prevent live network calls.
const testData = [rtMock.decodedScript, rtMock.decodedScript]
const resolved = new Promise(r => r({ data: testData }))
sandbox.stub(axios, "post").returns(resolved)
const hexes = [
"4830450221009a51e00ec3524a7389592bc27bea4af5104a59510f5f0cfafa64bbd5c164ca2e02206c2a8bbb47eabdeed52f17d7df668d521600286406930426e3a9415fe10ed592012102e6e1423f7abde8b70bca3e78a7d030e5efabd3eb35c19302542b5fe7879c1a16",
"4830450221009a51e00ec3524a7389592bc27bea4af5104a59510f5f0cfafa64bbd5c164ca2e02206c2a8bbb47eabdeed52f17d7df668d521600286406930426e3a9415fe10ed592012102e6e1423f7abde8b70bca3e78a7d030e5efabd3eb35c19302542b5fe7879c1a16"
]
const result = await bitbox.RawTransactions.decodeScript(hexes)
//console.log(`result ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.hasAnyKeys(result[0], ["asm", "type", "p2sh"])
})
it(`should pass error from server to user`, async (): Promise<any> => {
try {
// Mock out data for unit test, to prevent live network call.
sandbox
.stub(axios, "get")
.throws("error", "Input must be a string or array of strings")
const hexes: any = 12345
await bitbox.RawTransactions.decodeScript(hexes)
assert.equal(true, false, "Unexpected result!")
} catch (err) {
//console.log(`err: ${util.inspect(err)}`)
assert.include(
err.message,
`Input must be a string or array of strings`
)
}
})
})
/*
Testing sendRawTransaction isn't really possible with an integration test,
as the endpoint really needs an e2e test to be properly tested. The tests
below expect error messages returned from the server, but at least test
that the server is responding on those endpoints, and responds consistently.
*/
describe("sendRawTransaction", () => {
it("should send a single transaction hex", async (): Promise<any> => {
try {
// Mock out data for unit test, to prevent live network call.
sandbox.stub(axios, "get").throws({ error: "Missing inputs" })
const hex: string =
"01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000"
await bitbox.RawTransactions.sendRawTransaction(hex)
assert.equal(true, false, "Unexpected result!")
} catch (err) {
//console.log(`err: ${util.inspect(err)}`)
assert.hasAllKeys(err, ["error"])
assert.include(err.error, "Missing inputs")
}
})
it("should send an array of tx hexes", async (): Promise<any> => {
try {
// Mock out data for unit test, to prevent live network call.
sandbox.stub(axios, "post").throws({ error: "Missing inputs" })
const hexes: string[] = [
"01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000",
"01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000"
]
const result = await bitbox.RawTransactions.sendRawTransaction(hexes)
} catch (err) {
// console.log(`err: ${util.inspect(err)}`)
assert.hasAllKeys(err, ["error"])
assert.include(err.error, "Missing inputs")
}
})
})
}) | the_stack |
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types";
import { CloudWatchEventsClient } from "./CloudWatchEventsClient";
import {
ActivateEventSourceCommand,
ActivateEventSourceCommandInput,
ActivateEventSourceCommandOutput,
} from "./commands/ActivateEventSourceCommand";
import {
CancelReplayCommand,
CancelReplayCommandInput,
CancelReplayCommandOutput,
} from "./commands/CancelReplayCommand";
import {
CreateApiDestinationCommand,
CreateApiDestinationCommandInput,
CreateApiDestinationCommandOutput,
} from "./commands/CreateApiDestinationCommand";
import {
CreateArchiveCommand,
CreateArchiveCommandInput,
CreateArchiveCommandOutput,
} from "./commands/CreateArchiveCommand";
import {
CreateConnectionCommand,
CreateConnectionCommandInput,
CreateConnectionCommandOutput,
} from "./commands/CreateConnectionCommand";
import {
CreateEventBusCommand,
CreateEventBusCommandInput,
CreateEventBusCommandOutput,
} from "./commands/CreateEventBusCommand";
import {
CreatePartnerEventSourceCommand,
CreatePartnerEventSourceCommandInput,
CreatePartnerEventSourceCommandOutput,
} from "./commands/CreatePartnerEventSourceCommand";
import {
DeactivateEventSourceCommand,
DeactivateEventSourceCommandInput,
DeactivateEventSourceCommandOutput,
} from "./commands/DeactivateEventSourceCommand";
import {
DeauthorizeConnectionCommand,
DeauthorizeConnectionCommandInput,
DeauthorizeConnectionCommandOutput,
} from "./commands/DeauthorizeConnectionCommand";
import {
DeleteApiDestinationCommand,
DeleteApiDestinationCommandInput,
DeleteApiDestinationCommandOutput,
} from "./commands/DeleteApiDestinationCommand";
import {
DeleteArchiveCommand,
DeleteArchiveCommandInput,
DeleteArchiveCommandOutput,
} from "./commands/DeleteArchiveCommand";
import {
DeleteConnectionCommand,
DeleteConnectionCommandInput,
DeleteConnectionCommandOutput,
} from "./commands/DeleteConnectionCommand";
import {
DeleteEventBusCommand,
DeleteEventBusCommandInput,
DeleteEventBusCommandOutput,
} from "./commands/DeleteEventBusCommand";
import {
DeletePartnerEventSourceCommand,
DeletePartnerEventSourceCommandInput,
DeletePartnerEventSourceCommandOutput,
} from "./commands/DeletePartnerEventSourceCommand";
import { DeleteRuleCommand, DeleteRuleCommandInput, DeleteRuleCommandOutput } from "./commands/DeleteRuleCommand";
import {
DescribeApiDestinationCommand,
DescribeApiDestinationCommandInput,
DescribeApiDestinationCommandOutput,
} from "./commands/DescribeApiDestinationCommand";
import {
DescribeArchiveCommand,
DescribeArchiveCommandInput,
DescribeArchiveCommandOutput,
} from "./commands/DescribeArchiveCommand";
import {
DescribeConnectionCommand,
DescribeConnectionCommandInput,
DescribeConnectionCommandOutput,
} from "./commands/DescribeConnectionCommand";
import {
DescribeEventBusCommand,
DescribeEventBusCommandInput,
DescribeEventBusCommandOutput,
} from "./commands/DescribeEventBusCommand";
import {
DescribeEventSourceCommand,
DescribeEventSourceCommandInput,
DescribeEventSourceCommandOutput,
} from "./commands/DescribeEventSourceCommand";
import {
DescribePartnerEventSourceCommand,
DescribePartnerEventSourceCommandInput,
DescribePartnerEventSourceCommandOutput,
} from "./commands/DescribePartnerEventSourceCommand";
import {
DescribeReplayCommand,
DescribeReplayCommandInput,
DescribeReplayCommandOutput,
} from "./commands/DescribeReplayCommand";
import {
DescribeRuleCommand,
DescribeRuleCommandInput,
DescribeRuleCommandOutput,
} from "./commands/DescribeRuleCommand";
import { DisableRuleCommand, DisableRuleCommandInput, DisableRuleCommandOutput } from "./commands/DisableRuleCommand";
import { EnableRuleCommand, EnableRuleCommandInput, EnableRuleCommandOutput } from "./commands/EnableRuleCommand";
import {
ListApiDestinationsCommand,
ListApiDestinationsCommandInput,
ListApiDestinationsCommandOutput,
} from "./commands/ListApiDestinationsCommand";
import {
ListArchivesCommand,
ListArchivesCommandInput,
ListArchivesCommandOutput,
} from "./commands/ListArchivesCommand";
import {
ListConnectionsCommand,
ListConnectionsCommandInput,
ListConnectionsCommandOutput,
} from "./commands/ListConnectionsCommand";
import {
ListEventBusesCommand,
ListEventBusesCommandInput,
ListEventBusesCommandOutput,
} from "./commands/ListEventBusesCommand";
import {
ListEventSourcesCommand,
ListEventSourcesCommandInput,
ListEventSourcesCommandOutput,
} from "./commands/ListEventSourcesCommand";
import {
ListPartnerEventSourceAccountsCommand,
ListPartnerEventSourceAccountsCommandInput,
ListPartnerEventSourceAccountsCommandOutput,
} from "./commands/ListPartnerEventSourceAccountsCommand";
import {
ListPartnerEventSourcesCommand,
ListPartnerEventSourcesCommandInput,
ListPartnerEventSourcesCommandOutput,
} from "./commands/ListPartnerEventSourcesCommand";
import { ListReplaysCommand, ListReplaysCommandInput, ListReplaysCommandOutput } from "./commands/ListReplaysCommand";
import {
ListRuleNamesByTargetCommand,
ListRuleNamesByTargetCommandInput,
ListRuleNamesByTargetCommandOutput,
} from "./commands/ListRuleNamesByTargetCommand";
import { ListRulesCommand, ListRulesCommandInput, ListRulesCommandOutput } from "./commands/ListRulesCommand";
import {
ListTagsForResourceCommand,
ListTagsForResourceCommandInput,
ListTagsForResourceCommandOutput,
} from "./commands/ListTagsForResourceCommand";
import {
ListTargetsByRuleCommand,
ListTargetsByRuleCommandInput,
ListTargetsByRuleCommandOutput,
} from "./commands/ListTargetsByRuleCommand";
import { PutEventsCommand, PutEventsCommandInput, PutEventsCommandOutput } from "./commands/PutEventsCommand";
import {
PutPartnerEventsCommand,
PutPartnerEventsCommandInput,
PutPartnerEventsCommandOutput,
} from "./commands/PutPartnerEventsCommand";
import {
PutPermissionCommand,
PutPermissionCommandInput,
PutPermissionCommandOutput,
} from "./commands/PutPermissionCommand";
import { PutRuleCommand, PutRuleCommandInput, PutRuleCommandOutput } from "./commands/PutRuleCommand";
import { PutTargetsCommand, PutTargetsCommandInput, PutTargetsCommandOutput } from "./commands/PutTargetsCommand";
import {
RemovePermissionCommand,
RemovePermissionCommandInput,
RemovePermissionCommandOutput,
} from "./commands/RemovePermissionCommand";
import {
RemoveTargetsCommand,
RemoveTargetsCommandInput,
RemoveTargetsCommandOutput,
} from "./commands/RemoveTargetsCommand";
import { StartReplayCommand, StartReplayCommandInput, StartReplayCommandOutput } from "./commands/StartReplayCommand";
import { TagResourceCommand, TagResourceCommandInput, TagResourceCommandOutput } from "./commands/TagResourceCommand";
import {
TestEventPatternCommand,
TestEventPatternCommandInput,
TestEventPatternCommandOutput,
} from "./commands/TestEventPatternCommand";
import {
UntagResourceCommand,
UntagResourceCommandInput,
UntagResourceCommandOutput,
} from "./commands/UntagResourceCommand";
import {
UpdateApiDestinationCommand,
UpdateApiDestinationCommandInput,
UpdateApiDestinationCommandOutput,
} from "./commands/UpdateApiDestinationCommand";
import {
UpdateArchiveCommand,
UpdateArchiveCommandInput,
UpdateArchiveCommandOutput,
} from "./commands/UpdateArchiveCommand";
import {
UpdateConnectionCommand,
UpdateConnectionCommandInput,
UpdateConnectionCommandOutput,
} from "./commands/UpdateConnectionCommand";
/**
* <p>Amazon EventBridge helps you to respond to state changes in your Amazon Web Services resources. When your
* resources change state, they automatically send events to an event stream. You can create
* rules that match selected events in the stream and route them to targets to take action. You
* can also use rules to take action on a predetermined schedule. For example, you can configure
* rules to:</p>
* <ul>
* <li>
* <p>Automatically invoke an Lambda function to update DNS entries when an event
* notifies you that Amazon EC2 instance enters the running state.</p>
* </li>
* <li>
* <p>Direct specific API records from CloudTrail to an Amazon Kinesis data stream for
* detailed analysis of potential security or availability risks.</p>
* </li>
* <li>
* <p>Periodically invoke a built-in target to create a snapshot of an Amazon EBS
* volume.</p>
* </li>
* </ul>
* <p>For more information about the features of Amazon EventBridge, see the <a href="https://docs.aws.amazon.com/eventbridge/latest/userguide">Amazon EventBridge User
* Guide</a>.</p>
*/
export class CloudWatchEvents extends CloudWatchEventsClient {
/**
* <p>Activates a partner event source that has been deactivated. Once activated, your matching
* event bus will start receiving events from the event source.</p>
*/
public activateEventSource(
args: ActivateEventSourceCommandInput,
options?: __HttpHandlerOptions
): Promise<ActivateEventSourceCommandOutput>;
public activateEventSource(
args: ActivateEventSourceCommandInput,
cb: (err: any, data?: ActivateEventSourceCommandOutput) => void
): void;
public activateEventSource(
args: ActivateEventSourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ActivateEventSourceCommandOutput) => void
): void;
public activateEventSource(
args: ActivateEventSourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ActivateEventSourceCommandOutput) => void),
cb?: (err: any, data?: ActivateEventSourceCommandOutput) => void
): Promise<ActivateEventSourceCommandOutput> | void {
const command = new ActivateEventSourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Cancels the specified replay.</p>
*/
public cancelReplay(
args: CancelReplayCommandInput,
options?: __HttpHandlerOptions
): Promise<CancelReplayCommandOutput>;
public cancelReplay(args: CancelReplayCommandInput, cb: (err: any, data?: CancelReplayCommandOutput) => void): void;
public cancelReplay(
args: CancelReplayCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CancelReplayCommandOutput) => void
): void;
public cancelReplay(
args: CancelReplayCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CancelReplayCommandOutput) => void),
cb?: (err: any, data?: CancelReplayCommandOutput) => void
): Promise<CancelReplayCommandOutput> | void {
const command = new CancelReplayCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Creates an API destination, which is an HTTP invocation endpoint configured as a target
* for events.</p>
*/
public createApiDestination(
args: CreateApiDestinationCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateApiDestinationCommandOutput>;
public createApiDestination(
args: CreateApiDestinationCommandInput,
cb: (err: any, data?: CreateApiDestinationCommandOutput) => void
): void;
public createApiDestination(
args: CreateApiDestinationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateApiDestinationCommandOutput) => void
): void;
public createApiDestination(
args: CreateApiDestinationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateApiDestinationCommandOutput) => void),
cb?: (err: any, data?: CreateApiDestinationCommandOutput) => void
): Promise<CreateApiDestinationCommandOutput> | void {
const command = new CreateApiDestinationCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Creates an archive of events with the specified settings. When you create an archive,
* incoming events might not immediately start being sent to the archive. Allow a short period of
* time for changes to take effect. If you do not specify a pattern to filter events sent to the
* archive, all events are sent to the archive except replayed events. Replayed events are not
* sent to an archive.</p>
*/
public createArchive(
args: CreateArchiveCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateArchiveCommandOutput>;
public createArchive(
args: CreateArchiveCommandInput,
cb: (err: any, data?: CreateArchiveCommandOutput) => void
): void;
public createArchive(
args: CreateArchiveCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateArchiveCommandOutput) => void
): void;
public createArchive(
args: CreateArchiveCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateArchiveCommandOutput) => void),
cb?: (err: any, data?: CreateArchiveCommandOutput) => void
): Promise<CreateArchiveCommandOutput> | void {
const command = new CreateArchiveCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Creates a connection. A connection defines the authorization type and credentials to use
* for authorization with an API destination HTTP endpoint.</p>
*/
public createConnection(
args: CreateConnectionCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateConnectionCommandOutput>;
public createConnection(
args: CreateConnectionCommandInput,
cb: (err: any, data?: CreateConnectionCommandOutput) => void
): void;
public createConnection(
args: CreateConnectionCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateConnectionCommandOutput) => void
): void;
public createConnection(
args: CreateConnectionCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateConnectionCommandOutput) => void),
cb?: (err: any, data?: CreateConnectionCommandOutput) => void
): Promise<CreateConnectionCommandOutput> | void {
const command = new CreateConnectionCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Creates a new event bus within your account. This can be a custom event bus which you can
* use to receive events from your custom applications and services, or it can be a partner event
* bus which can be matched to a partner event source.</p>
*/
public createEventBus(
args: CreateEventBusCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateEventBusCommandOutput>;
public createEventBus(
args: CreateEventBusCommandInput,
cb: (err: any, data?: CreateEventBusCommandOutput) => void
): void;
public createEventBus(
args: CreateEventBusCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateEventBusCommandOutput) => void
): void;
public createEventBus(
args: CreateEventBusCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateEventBusCommandOutput) => void),
cb?: (err: any, data?: CreateEventBusCommandOutput) => void
): Promise<CreateEventBusCommandOutput> | void {
const command = new CreateEventBusCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Called by an SaaS partner to create a partner event source. This operation is not used by
* Amazon Web Services customers.</p>
* <p>Each partner event source can be used by one Amazon Web Services account to create a matching partner
* event bus in that Amazon Web Services account. A SaaS partner must create one partner event source for each
* Amazon Web Services account that wants to receive those event types. </p>
* <p>A partner event source creates events based on resources within the SaaS partner's service
* or application.</p>
* <p>An Amazon Web Services account that creates a partner event bus that matches the partner event source can
* use that event bus to receive events from the partner, and then process them using Amazon Web Services Events
* rules and targets.</p>
* <p>Partner event source names follow this format:</p>
* <p>
* <code>
* <i>partner_name</i>/<i>event_namespace</i>/<i>event_name</i>
* </code>
* </p>
* <p>
* <i>partner_name</i> is determined during partner registration and identifies
* the partner to Amazon Web Services customers. <i>event_namespace</i> is determined by the
* partner and is a way for the partner to categorize their events.
* <i>event_name</i> is determined by the partner, and should uniquely identify
* an event-generating resource within the partner system. The combination of
* <i>event_namespace</i> and <i>event_name</i> should help Amazon Web Services
* customers decide whether to create an event bus to receive these events.</p>
*/
public createPartnerEventSource(
args: CreatePartnerEventSourceCommandInput,
options?: __HttpHandlerOptions
): Promise<CreatePartnerEventSourceCommandOutput>;
public createPartnerEventSource(
args: CreatePartnerEventSourceCommandInput,
cb: (err: any, data?: CreatePartnerEventSourceCommandOutput) => void
): void;
public createPartnerEventSource(
args: CreatePartnerEventSourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreatePartnerEventSourceCommandOutput) => void
): void;
public createPartnerEventSource(
args: CreatePartnerEventSourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreatePartnerEventSourceCommandOutput) => void),
cb?: (err: any, data?: CreatePartnerEventSourceCommandOutput) => void
): Promise<CreatePartnerEventSourceCommandOutput> | void {
const command = new CreatePartnerEventSourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>You can use this operation to temporarily stop receiving events from the specified partner
* event source. The matching event bus is not deleted. </p>
* <p>When you deactivate a partner event source, the source goes into PENDING state. If it
* remains in PENDING state for more than two weeks, it is deleted.</p>
* <p>To activate a deactivated partner event source, use <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_ActivateEventSource.html">ActivateEventSource</a>.</p>
*/
public deactivateEventSource(
args: DeactivateEventSourceCommandInput,
options?: __HttpHandlerOptions
): Promise<DeactivateEventSourceCommandOutput>;
public deactivateEventSource(
args: DeactivateEventSourceCommandInput,
cb: (err: any, data?: DeactivateEventSourceCommandOutput) => void
): void;
public deactivateEventSource(
args: DeactivateEventSourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeactivateEventSourceCommandOutput) => void
): void;
public deactivateEventSource(
args: DeactivateEventSourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeactivateEventSourceCommandOutput) => void),
cb?: (err: any, data?: DeactivateEventSourceCommandOutput) => void
): Promise<DeactivateEventSourceCommandOutput> | void {
const command = new DeactivateEventSourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Removes all authorization parameters from the connection. This lets you remove the secret
* from the connection so you can reuse it without having to create a new connection.</p>
*/
public deauthorizeConnection(
args: DeauthorizeConnectionCommandInput,
options?: __HttpHandlerOptions
): Promise<DeauthorizeConnectionCommandOutput>;
public deauthorizeConnection(
args: DeauthorizeConnectionCommandInput,
cb: (err: any, data?: DeauthorizeConnectionCommandOutput) => void
): void;
public deauthorizeConnection(
args: DeauthorizeConnectionCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeauthorizeConnectionCommandOutput) => void
): void;
public deauthorizeConnection(
args: DeauthorizeConnectionCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeauthorizeConnectionCommandOutput) => void),
cb?: (err: any, data?: DeauthorizeConnectionCommandOutput) => void
): Promise<DeauthorizeConnectionCommandOutput> | void {
const command = new DeauthorizeConnectionCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes the specified API destination.</p>
*/
public deleteApiDestination(
args: DeleteApiDestinationCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteApiDestinationCommandOutput>;
public deleteApiDestination(
args: DeleteApiDestinationCommandInput,
cb: (err: any, data?: DeleteApiDestinationCommandOutput) => void
): void;
public deleteApiDestination(
args: DeleteApiDestinationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteApiDestinationCommandOutput) => void
): void;
public deleteApiDestination(
args: DeleteApiDestinationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteApiDestinationCommandOutput) => void),
cb?: (err: any, data?: DeleteApiDestinationCommandOutput) => void
): Promise<DeleteApiDestinationCommandOutput> | void {
const command = new DeleteApiDestinationCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes the specified archive.</p>
*/
public deleteArchive(
args: DeleteArchiveCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteArchiveCommandOutput>;
public deleteArchive(
args: DeleteArchiveCommandInput,
cb: (err: any, data?: DeleteArchiveCommandOutput) => void
): void;
public deleteArchive(
args: DeleteArchiveCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteArchiveCommandOutput) => void
): void;
public deleteArchive(
args: DeleteArchiveCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteArchiveCommandOutput) => void),
cb?: (err: any, data?: DeleteArchiveCommandOutput) => void
): Promise<DeleteArchiveCommandOutput> | void {
const command = new DeleteArchiveCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes a connection.</p>
*/
public deleteConnection(
args: DeleteConnectionCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteConnectionCommandOutput>;
public deleteConnection(
args: DeleteConnectionCommandInput,
cb: (err: any, data?: DeleteConnectionCommandOutput) => void
): void;
public deleteConnection(
args: DeleteConnectionCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteConnectionCommandOutput) => void
): void;
public deleteConnection(
args: DeleteConnectionCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteConnectionCommandOutput) => void),
cb?: (err: any, data?: DeleteConnectionCommandOutput) => void
): Promise<DeleteConnectionCommandOutput> | void {
const command = new DeleteConnectionCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes the specified custom event bus or partner event bus. All rules associated with
* this event bus need to be deleted. You can't delete your account's default event bus.</p>
*/
public deleteEventBus(
args: DeleteEventBusCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteEventBusCommandOutput>;
public deleteEventBus(
args: DeleteEventBusCommandInput,
cb: (err: any, data?: DeleteEventBusCommandOutput) => void
): void;
public deleteEventBus(
args: DeleteEventBusCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteEventBusCommandOutput) => void
): void;
public deleteEventBus(
args: DeleteEventBusCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteEventBusCommandOutput) => void),
cb?: (err: any, data?: DeleteEventBusCommandOutput) => void
): Promise<DeleteEventBusCommandOutput> | void {
const command = new DeleteEventBusCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>This operation is used by SaaS partners to delete a partner event source. This operation
* is not used by Amazon Web Services customers.</p>
* <p>When you delete an event source, the status of the corresponding partner event bus in the
* Amazon Web Services customer account becomes DELETED.</p>
* <p></p>
*/
public deletePartnerEventSource(
args: DeletePartnerEventSourceCommandInput,
options?: __HttpHandlerOptions
): Promise<DeletePartnerEventSourceCommandOutput>;
public deletePartnerEventSource(
args: DeletePartnerEventSourceCommandInput,
cb: (err: any, data?: DeletePartnerEventSourceCommandOutput) => void
): void;
public deletePartnerEventSource(
args: DeletePartnerEventSourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeletePartnerEventSourceCommandOutput) => void
): void;
public deletePartnerEventSource(
args: DeletePartnerEventSourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeletePartnerEventSourceCommandOutput) => void),
cb?: (err: any, data?: DeletePartnerEventSourceCommandOutput) => void
): Promise<DeletePartnerEventSourceCommandOutput> | void {
const command = new DeletePartnerEventSourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes the specified rule.</p>
* <p>Before you can delete the rule, you must remove all targets, using <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_RemoveTargets.html">RemoveTargets</a>.</p>
*
* <p>When you delete a rule, incoming events might continue to match to the deleted rule. Allow
* a short period of time for changes to take effect.</p>
*
* <p>If you call delete rule multiple times for the same rule, all calls will succeed. When you
* call delete rule for a non-existent custom eventbus, <code>ResourceNotFoundException</code> is
* returned.</p>
*
* <p>Managed rules are rules created and managed by another Amazon Web Services service on your behalf. These
* rules are created by those other Amazon Web Services services to support functionality in those services. You
* can delete these rules using the <code>Force</code> option, but you should do so only if you
* are sure the other service is not still using that rule.</p>
*/
public deleteRule(args: DeleteRuleCommandInput, options?: __HttpHandlerOptions): Promise<DeleteRuleCommandOutput>;
public deleteRule(args: DeleteRuleCommandInput, cb: (err: any, data?: DeleteRuleCommandOutput) => void): void;
public deleteRule(
args: DeleteRuleCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteRuleCommandOutput) => void
): void;
public deleteRule(
args: DeleteRuleCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteRuleCommandOutput) => void),
cb?: (err: any, data?: DeleteRuleCommandOutput) => void
): Promise<DeleteRuleCommandOutput> | void {
const command = new DeleteRuleCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Retrieves details about an API destination.</p>
*/
public describeApiDestination(
args: DescribeApiDestinationCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeApiDestinationCommandOutput>;
public describeApiDestination(
args: DescribeApiDestinationCommandInput,
cb: (err: any, data?: DescribeApiDestinationCommandOutput) => void
): void;
public describeApiDestination(
args: DescribeApiDestinationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeApiDestinationCommandOutput) => void
): void;
public describeApiDestination(
args: DescribeApiDestinationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeApiDestinationCommandOutput) => void),
cb?: (err: any, data?: DescribeApiDestinationCommandOutput) => void
): Promise<DescribeApiDestinationCommandOutput> | void {
const command = new DescribeApiDestinationCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Retrieves details about an archive.</p>
*/
public describeArchive(
args: DescribeArchiveCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeArchiveCommandOutput>;
public describeArchive(
args: DescribeArchiveCommandInput,
cb: (err: any, data?: DescribeArchiveCommandOutput) => void
): void;
public describeArchive(
args: DescribeArchiveCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeArchiveCommandOutput) => void
): void;
public describeArchive(
args: DescribeArchiveCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeArchiveCommandOutput) => void),
cb?: (err: any, data?: DescribeArchiveCommandOutput) => void
): Promise<DescribeArchiveCommandOutput> | void {
const command = new DescribeArchiveCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Retrieves details about a connection.</p>
*/
public describeConnection(
args: DescribeConnectionCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeConnectionCommandOutput>;
public describeConnection(
args: DescribeConnectionCommandInput,
cb: (err: any, data?: DescribeConnectionCommandOutput) => void
): void;
public describeConnection(
args: DescribeConnectionCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeConnectionCommandOutput) => void
): void;
public describeConnection(
args: DescribeConnectionCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeConnectionCommandOutput) => void),
cb?: (err: any, data?: DescribeConnectionCommandOutput) => void
): Promise<DescribeConnectionCommandOutput> | void {
const command = new DescribeConnectionCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Displays details about an event bus in your account. This can include the external Amazon Web Services
* accounts that are permitted to write events to your default event bus, and the associated
* policy. For custom event buses and partner event buses, it displays the name, ARN, policy,
* state, and creation time.</p>
* <p> To enable your account to receive events from other accounts on its default event bus,
* use <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_PutPermission.html">PutPermission</a>.</p>
* <p>For more information about partner event buses, see <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_CreateEventBus.html">CreateEventBus</a>.</p>
*/
public describeEventBus(
args: DescribeEventBusCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeEventBusCommandOutput>;
public describeEventBus(
args: DescribeEventBusCommandInput,
cb: (err: any, data?: DescribeEventBusCommandOutput) => void
): void;
public describeEventBus(
args: DescribeEventBusCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeEventBusCommandOutput) => void
): void;
public describeEventBus(
args: DescribeEventBusCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeEventBusCommandOutput) => void),
cb?: (err: any, data?: DescribeEventBusCommandOutput) => void
): Promise<DescribeEventBusCommandOutput> | void {
const command = new DescribeEventBusCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>This operation lists details about a partner event source that is shared with your
* account.</p>
*/
public describeEventSource(
args: DescribeEventSourceCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeEventSourceCommandOutput>;
public describeEventSource(
args: DescribeEventSourceCommandInput,
cb: (err: any, data?: DescribeEventSourceCommandOutput) => void
): void;
public describeEventSource(
args: DescribeEventSourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeEventSourceCommandOutput) => void
): void;
public describeEventSource(
args: DescribeEventSourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeEventSourceCommandOutput) => void),
cb?: (err: any, data?: DescribeEventSourceCommandOutput) => void
): Promise<DescribeEventSourceCommandOutput> | void {
const command = new DescribeEventSourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>An SaaS partner can use this operation to list details about a partner event source that
* they have created. Amazon Web Services customers do not use this operation. Instead, Amazon Web Services customers can use <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_DescribeEventSource.html">DescribeEventSource</a>
* to see details about a partner event source that is
* shared with them.</p>
*/
public describePartnerEventSource(
args: DescribePartnerEventSourceCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribePartnerEventSourceCommandOutput>;
public describePartnerEventSource(
args: DescribePartnerEventSourceCommandInput,
cb: (err: any, data?: DescribePartnerEventSourceCommandOutput) => void
): void;
public describePartnerEventSource(
args: DescribePartnerEventSourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribePartnerEventSourceCommandOutput) => void
): void;
public describePartnerEventSource(
args: DescribePartnerEventSourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribePartnerEventSourceCommandOutput) => void),
cb?: (err: any, data?: DescribePartnerEventSourceCommandOutput) => void
): Promise<DescribePartnerEventSourceCommandOutput> | void {
const command = new DescribePartnerEventSourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Retrieves details about a replay. Use <code>DescribeReplay</code> to determine the
* progress of a running replay. A replay processes events to replay based on the time in the
* event, and replays them using 1 minute intervals. If you use <code>StartReplay</code> and
* specify an <code>EventStartTime</code> and an <code>EventEndTime</code> that covers a 20
* minute time range, the events are replayed from the first minute of that 20 minute range
* first. Then the events from the second minute are replayed. You can use
* <code>DescribeReplay</code> to determine the progress of a replay. The value returned for
* <code>EventLastReplayedTime</code> indicates the time within the specified time range
* associated with the last event replayed.</p>
*/
public describeReplay(
args: DescribeReplayCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeReplayCommandOutput>;
public describeReplay(
args: DescribeReplayCommandInput,
cb: (err: any, data?: DescribeReplayCommandOutput) => void
): void;
public describeReplay(
args: DescribeReplayCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeReplayCommandOutput) => void
): void;
public describeReplay(
args: DescribeReplayCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeReplayCommandOutput) => void),
cb?: (err: any, data?: DescribeReplayCommandOutput) => void
): Promise<DescribeReplayCommandOutput> | void {
const command = new DescribeReplayCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Describes the specified rule.</p>
* <p>DescribeRule does not list the targets of a rule. To see the targets associated with a
* rule, use <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_ListTargetsByRule.html">ListTargetsByRule</a>.</p>
*/
public describeRule(
args: DescribeRuleCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeRuleCommandOutput>;
public describeRule(args: DescribeRuleCommandInput, cb: (err: any, data?: DescribeRuleCommandOutput) => void): void;
public describeRule(
args: DescribeRuleCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeRuleCommandOutput) => void
): void;
public describeRule(
args: DescribeRuleCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeRuleCommandOutput) => void),
cb?: (err: any, data?: DescribeRuleCommandOutput) => void
): Promise<DescribeRuleCommandOutput> | void {
const command = new DescribeRuleCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Disables the specified rule. A disabled rule won't match any events, and won't
* self-trigger if it has a schedule expression.</p>
*
* <p>When you disable a rule, incoming events might continue to match to the disabled rule.
* Allow a short period of time for changes to take effect.</p>
*/
public disableRule(args: DisableRuleCommandInput, options?: __HttpHandlerOptions): Promise<DisableRuleCommandOutput>;
public disableRule(args: DisableRuleCommandInput, cb: (err: any, data?: DisableRuleCommandOutput) => void): void;
public disableRule(
args: DisableRuleCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DisableRuleCommandOutput) => void
): void;
public disableRule(
args: DisableRuleCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DisableRuleCommandOutput) => void),
cb?: (err: any, data?: DisableRuleCommandOutput) => void
): Promise<DisableRuleCommandOutput> | void {
const command = new DisableRuleCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Enables the specified rule. If the rule does not exist, the operation fails.</p>
*
* <p>When you enable a rule, incoming events might not immediately start matching to a newly
* enabled rule. Allow a short period of time for changes to take effect.</p>
*/
public enableRule(args: EnableRuleCommandInput, options?: __HttpHandlerOptions): Promise<EnableRuleCommandOutput>;
public enableRule(args: EnableRuleCommandInput, cb: (err: any, data?: EnableRuleCommandOutput) => void): void;
public enableRule(
args: EnableRuleCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: EnableRuleCommandOutput) => void
): void;
public enableRule(
args: EnableRuleCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: EnableRuleCommandOutput) => void),
cb?: (err: any, data?: EnableRuleCommandOutput) => void
): Promise<EnableRuleCommandOutput> | void {
const command = new EnableRuleCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Retrieves a list of API destination in the account in the current Region.</p>
*/
public listApiDestinations(
args: ListApiDestinationsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListApiDestinationsCommandOutput>;
public listApiDestinations(
args: ListApiDestinationsCommandInput,
cb: (err: any, data?: ListApiDestinationsCommandOutput) => void
): void;
public listApiDestinations(
args: ListApiDestinationsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListApiDestinationsCommandOutput) => void
): void;
public listApiDestinations(
args: ListApiDestinationsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListApiDestinationsCommandOutput) => void),
cb?: (err: any, data?: ListApiDestinationsCommandOutput) => void
): Promise<ListApiDestinationsCommandOutput> | void {
const command = new ListApiDestinationsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Lists your archives. You can either list all the archives or you can provide a prefix to
* match to the archive names. Filter parameters are exclusive.</p>
*/
public listArchives(
args: ListArchivesCommandInput,
options?: __HttpHandlerOptions
): Promise<ListArchivesCommandOutput>;
public listArchives(args: ListArchivesCommandInput, cb: (err: any, data?: ListArchivesCommandOutput) => void): void;
public listArchives(
args: ListArchivesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListArchivesCommandOutput) => void
): void;
public listArchives(
args: ListArchivesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListArchivesCommandOutput) => void),
cb?: (err: any, data?: ListArchivesCommandOutput) => void
): Promise<ListArchivesCommandOutput> | void {
const command = new ListArchivesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Retrieves a list of connections from the account.</p>
*/
public listConnections(
args: ListConnectionsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListConnectionsCommandOutput>;
public listConnections(
args: ListConnectionsCommandInput,
cb: (err: any, data?: ListConnectionsCommandOutput) => void
): void;
public listConnections(
args: ListConnectionsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListConnectionsCommandOutput) => void
): void;
public listConnections(
args: ListConnectionsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListConnectionsCommandOutput) => void),
cb?: (err: any, data?: ListConnectionsCommandOutput) => void
): Promise<ListConnectionsCommandOutput> | void {
const command = new ListConnectionsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Lists all the event buses in your account, including the default event bus, custom event
* buses, and partner event buses.</p>
*/
public listEventBuses(
args: ListEventBusesCommandInput,
options?: __HttpHandlerOptions
): Promise<ListEventBusesCommandOutput>;
public listEventBuses(
args: ListEventBusesCommandInput,
cb: (err: any, data?: ListEventBusesCommandOutput) => void
): void;
public listEventBuses(
args: ListEventBusesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListEventBusesCommandOutput) => void
): void;
public listEventBuses(
args: ListEventBusesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListEventBusesCommandOutput) => void),
cb?: (err: any, data?: ListEventBusesCommandOutput) => void
): Promise<ListEventBusesCommandOutput> | void {
const command = new ListEventBusesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>You can use this to see all the partner event sources that have been shared with your Amazon Web Services
* account. For more information about partner event sources, see <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_CreateEventBus.html">CreateEventBus</a>.</p>
*/
public listEventSources(
args: ListEventSourcesCommandInput,
options?: __HttpHandlerOptions
): Promise<ListEventSourcesCommandOutput>;
public listEventSources(
args: ListEventSourcesCommandInput,
cb: (err: any, data?: ListEventSourcesCommandOutput) => void
): void;
public listEventSources(
args: ListEventSourcesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListEventSourcesCommandOutput) => void
): void;
public listEventSources(
args: ListEventSourcesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListEventSourcesCommandOutput) => void),
cb?: (err: any, data?: ListEventSourcesCommandOutput) => void
): Promise<ListEventSourcesCommandOutput> | void {
const command = new ListEventSourcesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>An SaaS partner can use this operation to display the Amazon Web Services account ID that a particular
* partner event source name is associated with. This operation is not used by Amazon Web Services
* customers.</p>
*/
public listPartnerEventSourceAccounts(
args: ListPartnerEventSourceAccountsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListPartnerEventSourceAccountsCommandOutput>;
public listPartnerEventSourceAccounts(
args: ListPartnerEventSourceAccountsCommandInput,
cb: (err: any, data?: ListPartnerEventSourceAccountsCommandOutput) => void
): void;
public listPartnerEventSourceAccounts(
args: ListPartnerEventSourceAccountsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListPartnerEventSourceAccountsCommandOutput) => void
): void;
public listPartnerEventSourceAccounts(
args: ListPartnerEventSourceAccountsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListPartnerEventSourceAccountsCommandOutput) => void),
cb?: (err: any, data?: ListPartnerEventSourceAccountsCommandOutput) => void
): Promise<ListPartnerEventSourceAccountsCommandOutput> | void {
const command = new ListPartnerEventSourceAccountsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>An SaaS partner can use this operation to list all the partner event source names that
* they have created. This operation is not used by Amazon Web Services customers.</p>
*/
public listPartnerEventSources(
args: ListPartnerEventSourcesCommandInput,
options?: __HttpHandlerOptions
): Promise<ListPartnerEventSourcesCommandOutput>;
public listPartnerEventSources(
args: ListPartnerEventSourcesCommandInput,
cb: (err: any, data?: ListPartnerEventSourcesCommandOutput) => void
): void;
public listPartnerEventSources(
args: ListPartnerEventSourcesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListPartnerEventSourcesCommandOutput) => void
): void;
public listPartnerEventSources(
args: ListPartnerEventSourcesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListPartnerEventSourcesCommandOutput) => void),
cb?: (err: any, data?: ListPartnerEventSourcesCommandOutput) => void
): Promise<ListPartnerEventSourcesCommandOutput> | void {
const command = new ListPartnerEventSourcesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Lists your replays. You can either list all the replays or you can provide a prefix to
* match to the replay names. Filter parameters are exclusive.</p>
*/
public listReplays(args: ListReplaysCommandInput, options?: __HttpHandlerOptions): Promise<ListReplaysCommandOutput>;
public listReplays(args: ListReplaysCommandInput, cb: (err: any, data?: ListReplaysCommandOutput) => void): void;
public listReplays(
args: ListReplaysCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListReplaysCommandOutput) => void
): void;
public listReplays(
args: ListReplaysCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListReplaysCommandOutput) => void),
cb?: (err: any, data?: ListReplaysCommandOutput) => void
): Promise<ListReplaysCommandOutput> | void {
const command = new ListReplaysCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Lists the rules for the specified target. You can see which of the rules in Amazon
* EventBridge can invoke a specific target in your account.</p>
*/
public listRuleNamesByTarget(
args: ListRuleNamesByTargetCommandInput,
options?: __HttpHandlerOptions
): Promise<ListRuleNamesByTargetCommandOutput>;
public listRuleNamesByTarget(
args: ListRuleNamesByTargetCommandInput,
cb: (err: any, data?: ListRuleNamesByTargetCommandOutput) => void
): void;
public listRuleNamesByTarget(
args: ListRuleNamesByTargetCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListRuleNamesByTargetCommandOutput) => void
): void;
public listRuleNamesByTarget(
args: ListRuleNamesByTargetCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListRuleNamesByTargetCommandOutput) => void),
cb?: (err: any, data?: ListRuleNamesByTargetCommandOutput) => void
): Promise<ListRuleNamesByTargetCommandOutput> | void {
const command = new ListRuleNamesByTargetCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Lists your Amazon EventBridge rules. You can either list all the rules or you can provide
* a prefix to match to the rule names.</p>
*
* <p>ListRules does not list the targets of a rule. To see the targets associated with a rule,
* use <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_ListTargetsByRule.html">ListTargetsByRule</a>.</p>
*/
public listRules(args: ListRulesCommandInput, options?: __HttpHandlerOptions): Promise<ListRulesCommandOutput>;
public listRules(args: ListRulesCommandInput, cb: (err: any, data?: ListRulesCommandOutput) => void): void;
public listRules(
args: ListRulesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListRulesCommandOutput) => void
): void;
public listRules(
args: ListRulesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListRulesCommandOutput) => void),
cb?: (err: any, data?: ListRulesCommandOutput) => void
): Promise<ListRulesCommandOutput> | void {
const command = new ListRulesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Displays the tags associated with an EventBridge resource. In EventBridge, rules and event
* buses can be tagged.</p>
*/
public listTagsForResource(
args: ListTagsForResourceCommandInput,
options?: __HttpHandlerOptions
): Promise<ListTagsForResourceCommandOutput>;
public listTagsForResource(
args: ListTagsForResourceCommandInput,
cb: (err: any, data?: ListTagsForResourceCommandOutput) => void
): void;
public listTagsForResource(
args: ListTagsForResourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListTagsForResourceCommandOutput) => void
): void;
public listTagsForResource(
args: ListTagsForResourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTagsForResourceCommandOutput) => void),
cb?: (err: any, data?: ListTagsForResourceCommandOutput) => void
): Promise<ListTagsForResourceCommandOutput> | void {
const command = new ListTagsForResourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Lists the targets assigned to the specified rule.</p>
*/
public listTargetsByRule(
args: ListTargetsByRuleCommandInput,
options?: __HttpHandlerOptions
): Promise<ListTargetsByRuleCommandOutput>;
public listTargetsByRule(
args: ListTargetsByRuleCommandInput,
cb: (err: any, data?: ListTargetsByRuleCommandOutput) => void
): void;
public listTargetsByRule(
args: ListTargetsByRuleCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListTargetsByRuleCommandOutput) => void
): void;
public listTargetsByRule(
args: ListTargetsByRuleCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTargetsByRuleCommandOutput) => void),
cb?: (err: any, data?: ListTargetsByRuleCommandOutput) => void
): Promise<ListTargetsByRuleCommandOutput> | void {
const command = new ListTargetsByRuleCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Sends custom events to Amazon EventBridge so that they can be matched to rules.</p>
*/
public putEvents(args: PutEventsCommandInput, options?: __HttpHandlerOptions): Promise<PutEventsCommandOutput>;
public putEvents(args: PutEventsCommandInput, cb: (err: any, data?: PutEventsCommandOutput) => void): void;
public putEvents(
args: PutEventsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: PutEventsCommandOutput) => void
): void;
public putEvents(
args: PutEventsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutEventsCommandOutput) => void),
cb?: (err: any, data?: PutEventsCommandOutput) => void
): Promise<PutEventsCommandOutput> | void {
const command = new PutEventsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>This is used by SaaS partners to write events to a customer's partner event bus. Amazon Web Services
* customers do not use this operation.</p>
*/
public putPartnerEvents(
args: PutPartnerEventsCommandInput,
options?: __HttpHandlerOptions
): Promise<PutPartnerEventsCommandOutput>;
public putPartnerEvents(
args: PutPartnerEventsCommandInput,
cb: (err: any, data?: PutPartnerEventsCommandOutput) => void
): void;
public putPartnerEvents(
args: PutPartnerEventsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: PutPartnerEventsCommandOutput) => void
): void;
public putPartnerEvents(
args: PutPartnerEventsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutPartnerEventsCommandOutput) => void),
cb?: (err: any, data?: PutPartnerEventsCommandOutput) => void
): Promise<PutPartnerEventsCommandOutput> | void {
const command = new PutPartnerEventsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Running <code>PutPermission</code> permits the specified Amazon Web Services account or Amazon Web Services organization
* to put events to the specified <i>event bus</i>. Amazon EventBridge (CloudWatch
* Events) rules in your account are triggered by these events arriving to an event bus in your
* account. </p>
* <p>For another account to send events to your account, that external account must have an
* EventBridge rule with your account's event bus as a target.</p>
*
* <p>To enable multiple Amazon Web Services accounts to put events to your event bus, run
* <code>PutPermission</code> once for each of these accounts. Or, if all the accounts are
* members of the same Amazon Web Services organization, you can run <code>PutPermission</code> once specifying
* <code>Principal</code> as "*" and specifying the Amazon Web Services organization ID in
* <code>Condition</code>, to grant permissions to all accounts in that organization.</p>
*
* <p>If you grant permissions using an organization, then accounts in that organization must
* specify a <code>RoleArn</code> with proper permissions when they use <code>PutTarget</code> to
* add your account's event bus as a target. For more information, see <a href="https://docs.aws.amazon.com/eventbridge/latest/userguide/eventbridge-cross-account-event-delivery.html">Sending and
* Receiving Events Between Amazon Web Services Accounts</a> in the <i>Amazon EventBridge User
* Guide</i>.</p>
*
* <p>The permission policy on the event bus cannot exceed 10 KB in size.</p>
*/
public putPermission(
args: PutPermissionCommandInput,
options?: __HttpHandlerOptions
): Promise<PutPermissionCommandOutput>;
public putPermission(
args: PutPermissionCommandInput,
cb: (err: any, data?: PutPermissionCommandOutput) => void
): void;
public putPermission(
args: PutPermissionCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: PutPermissionCommandOutput) => void
): void;
public putPermission(
args: PutPermissionCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutPermissionCommandOutput) => void),
cb?: (err: any, data?: PutPermissionCommandOutput) => void
): Promise<PutPermissionCommandOutput> | void {
const command = new PutPermissionCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Creates or updates the specified rule. Rules are enabled by default, or based on value of
* the state. You can disable a rule using <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_DisableRule.html">DisableRule</a>.</p>
*
* <p>A single rule watches for events from a single event bus. Events generated by Amazon Web Services services
* go to your account's default event bus. Events generated by SaaS partner services or
* applications go to the matching partner event bus. If you have custom applications or
* services, you can specify whether their events go to your default event bus or a custom event
* bus that you have created. For more information, see <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_CreateEventBus.html">CreateEventBus</a>.</p>
*
* <p>If you are updating an existing rule, the rule is replaced with what you specify in this
* <code>PutRule</code> command. If you omit arguments in <code>PutRule</code>, the old values
* for those arguments are not kept. Instead, they are replaced with null values.</p>
*
* <p>When you create or update a rule, incoming events might not immediately start matching to
* new or updated rules. Allow a short period of time for changes to take effect.</p>
*
* <p>A rule must contain at least an EventPattern or ScheduleExpression. Rules with
* EventPatterns are triggered when a matching event is observed. Rules with ScheduleExpressions
* self-trigger based on the given schedule. A rule can have both an EventPattern and a
* ScheduleExpression, in which case the rule triggers on matching events as well as on a
* schedule.</p>
*
* <p>When you initially create a rule, you can optionally assign one or more tags to the rule.
* Tags can help you organize and categorize your resources. You can also use them to scope user
* permissions, by granting a user permission to access or change only rules with certain tag
* values. To use the <code>PutRule</code> operation and assign tags, you must have both the
* <code>events:PutRule</code> and <code>events:TagResource</code> permissions.</p>
* <p>If you are updating an existing rule, any tags you specify in the <code>PutRule</code>
* operation are ignored. To update the tags of an existing rule, use <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_TagResource.html">TagResource</a> and <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_UntagResource.html">UntagResource</a>.</p>
*
* <p>Most services in Amazon Web Services treat : or / as the same character in Amazon Resource Names (ARNs).
* However, EventBridge uses an exact match in event patterns and rules. Be sure to use the
* correct ARN characters when creating event patterns so that they match the ARN syntax in the
* event you want to match.</p>
*
* <p>In EventBridge, it is possible to create rules that lead to infinite loops, where a rule
* is fired repeatedly. For example, a rule might detect that ACLs have changed on an S3 bucket,
* and trigger software to change them to the desired state. If the rule is not written
* carefully, the subsequent change to the ACLs fires the rule again, creating an infinite
* loop.</p>
* <p>To prevent this, write the rules so that the triggered actions do not re-fire the same
* rule. For example, your rule could fire only if ACLs are found to be in a bad state, instead
* of after any change. </p>
* <p>An infinite loop can quickly cause higher than expected charges. We recommend that you use
* budgeting, which alerts you when charges exceed your specified limit. For more information,
* see <a href="https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/budgets-managing-costs.html">Managing Your Costs with
* Budgets</a>.</p>
*/
public putRule(args: PutRuleCommandInput, options?: __HttpHandlerOptions): Promise<PutRuleCommandOutput>;
public putRule(args: PutRuleCommandInput, cb: (err: any, data?: PutRuleCommandOutput) => void): void;
public putRule(
args: PutRuleCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: PutRuleCommandOutput) => void
): void;
public putRule(
args: PutRuleCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutRuleCommandOutput) => void),
cb?: (err: any, data?: PutRuleCommandOutput) => void
): Promise<PutRuleCommandOutput> | void {
const command = new PutRuleCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Adds the specified targets to the specified rule, or updates the targets if they are
* already associated with the rule.</p>
* <p>Targets are the resources that are invoked when a rule is triggered.</p>
* <p>You can configure the following as targets for Events:</p>
*
* <ul>
* <li>
* <p>
* <a href="https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-api-destinations.html">API
* destination</a>
* </p>
* </li>
* <li>
* <p>Amazon API Gateway REST API endpoints</p>
* </li>
* <li>
* <p>API Gateway</p>
* </li>
* <li>
* <p>Batch job queue</p>
* </li>
* <li>
* <p>CloudWatch Logs group</p>
* </li>
* <li>
* <p>CodeBuild project</p>
* </li>
* <li>
* <p>CodePipeline</p>
* </li>
* <li>
* <p>Amazon EC2 <code>CreateSnapshot</code> API call</p>
* </li>
* <li>
* <p>Amazon EC2 <code>RebootInstances</code> API call</p>
* </li>
* <li>
* <p>Amazon EC2 <code>StopInstances</code> API call</p>
* </li>
* <li>
* <p>Amazon EC2 <code>TerminateInstances</code> API call</p>
* </li>
* <li>
* <p>Amazon ECS tasks</p>
* </li>
* <li>
* <p>Event bus in a different Amazon Web Services account or Region.</p>
* <p>You can use an event bus in the US East (N. Virginia) us-east-1, US West (Oregon)
* us-west-2, or Europe (Ireland) eu-west-1 Regions as a target for a rule.</p>
* </li>
* <li>
* <p>Firehose delivery stream (Kinesis Data Firehose)</p>
* </li>
* <li>
* <p>Inspector assessment template (Amazon Inspector)</p>
* </li>
* <li>
* <p>Kinesis stream (Kinesis Data Stream)</p>
* </li>
* <li>
* <p>Lambda function</p>
* </li>
* <li>
* <p>Redshift clusters (Data API statement execution)</p>
* </li>
* <li>
* <p>Amazon SNS topic</p>
* </li>
* <li>
* <p>Amazon SQS queues (includes FIFO queues</p>
* </li>
* <li>
* <p>SSM Automation</p>
* </li>
* <li>
* <p>SSM OpsItem</p>
* </li>
* <li>
* <p>SSM Run Command</p>
* </li>
* <li>
* <p>Step Functions state machines</p>
* </li>
* </ul>
*
* <p>Creating rules with built-in targets is supported only in the Management Console. The
* built-in targets are <code>EC2 CreateSnapshot API call</code>, <code>EC2 RebootInstances API
* call</code>, <code>EC2 StopInstances API call</code>, and <code>EC2 TerminateInstances API
* call</code>. </p>
*
* <p>For some target types, <code>PutTargets</code> provides target-specific parameters. If the
* target is a Kinesis data stream, you can optionally specify which shard the event goes to by
* using the <code>KinesisParameters</code> argument. To invoke a command on multiple EC2
* instances with one rule, you can use the <code>RunCommandParameters</code> field.</p>
*
* <p>To be able to make API calls against the resources that you own, Amazon EventBridge
* needs the appropriate permissions. For Lambda and Amazon SNS
* resources, EventBridge relies on resource-based policies. For EC2 instances, Kinesis Data Streams,
* Step Functions state machines and API Gateway REST APIs, EventBridge relies on
* IAM roles that you specify in the <code>RoleARN</code> argument in <code>PutTargets</code>.
* For more information, see <a href="https://docs.aws.amazon.com/eventbridge/latest/userguide/auth-and-access-control-eventbridge.html">Authentication
* and Access Control</a> in the <i>Amazon EventBridge User Guide</i>.</p>
*
* <p>If another Amazon Web Services account is in the same region and has granted you permission (using
* <code>PutPermission</code>), you can send events to that account. Set that account's event
* bus as a target of the rules in your account. To send the matched events to the other account,
* specify that account's event bus as the <code>Arn</code> value when you run
* <code>PutTargets</code>. If your account sends events to another account, your account is
* charged for each sent event. Each event sent to another account is charged as a custom event.
* The account receiving the event is not charged. For more information, see <a href="http://aws.amazon.com/eventbridge/pricing/">Amazon EventBridge
* Pricing</a>.</p>
*
* <note>
* <p>
* <code>Input</code>, <code>InputPath</code>, and <code>InputTransformer</code> are not
* available with <code>PutTarget</code> if the target is an event bus of a different Amazon Web Services
* account.</p>
* </note>
*
* <p>If you are setting the event bus of another account as the target, and that account
* granted permission to your account through an organization instead of directly by the account
* ID, then you must specify a <code>RoleArn</code> with proper permissions in the
* <code>Target</code> structure. For more information, see <a href="https://docs.aws.amazon.com/eventbridge/latest/userguide/eventbridge-cross-account-event-delivery.html">Sending and
* Receiving Events Between Amazon Web Services Accounts</a> in the <i>Amazon EventBridge User
* Guide</i>.</p>
*
* <p>For more information about enabling cross-account events, see <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_PutPermission.html">PutPermission</a>.</p>
*
* <p>
* <b>Input</b>, <b>InputPath</b>, and
* <b>InputTransformer</b> are mutually exclusive and optional
* parameters of a target. When a rule is triggered due to a matched event:</p>
*
* <ul>
* <li>
* <p>If none of the following arguments are specified for a target, then the entire event
* is passed to the target in JSON format (unless the target is Amazon EC2 Run Command or
* Amazon ECS task, in which case nothing from the event is passed to the target).</p>
* </li>
* <li>
* <p>If <b>Input</b> is specified in the form of valid JSON, then
* the matched event is overridden with this constant.</p>
* </li>
* <li>
* <p>If <b>InputPath</b> is specified in the form of JSONPath
* (for example, <code>$.detail</code>), then only the part of the event specified in the
* path is passed to the target (for example, only the detail part of the event is
* passed).</p>
* </li>
* <li>
* <p>If <b>InputTransformer</b> is specified, then one or more
* specified JSONPaths are extracted from the event and used as values in a template that you
* specify as the input to the target.</p>
* </li>
* </ul>
*
* <p>When you specify <code>InputPath</code> or <code>InputTransformer</code>, you must use
* JSON dot notation, not bracket notation.</p>
*
* <p>When you add targets to a rule and the associated rule triggers soon after, new or updated
* targets might not be immediately invoked. Allow a short period of time for changes to take
* effect.</p>
*
* <p>This action can partially fail if too many requests are made at the same time. If that
* happens, <code>FailedEntryCount</code> is non-zero in the response and each entry in
* <code>FailedEntries</code> provides the ID of the failed target and the error code.</p>
*/
public putTargets(args: PutTargetsCommandInput, options?: __HttpHandlerOptions): Promise<PutTargetsCommandOutput>;
public putTargets(args: PutTargetsCommandInput, cb: (err: any, data?: PutTargetsCommandOutput) => void): void;
public putTargets(
args: PutTargetsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: PutTargetsCommandOutput) => void
): void;
public putTargets(
args: PutTargetsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutTargetsCommandOutput) => void),
cb?: (err: any, data?: PutTargetsCommandOutput) => void
): Promise<PutTargetsCommandOutput> | void {
const command = new PutTargetsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Revokes the permission of another Amazon Web Services account to be able to put events to the specified
* event bus. Specify the account to revoke by the <code>StatementId</code> value that you
* associated with the account when you granted it permission with <code>PutPermission</code>.
* You can find the <code>StatementId</code> by using <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_DescribeEventBus.html">DescribeEventBus</a>.</p>
*/
public removePermission(
args: RemovePermissionCommandInput,
options?: __HttpHandlerOptions
): Promise<RemovePermissionCommandOutput>;
public removePermission(
args: RemovePermissionCommandInput,
cb: (err: any, data?: RemovePermissionCommandOutput) => void
): void;
public removePermission(
args: RemovePermissionCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: RemovePermissionCommandOutput) => void
): void;
public removePermission(
args: RemovePermissionCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RemovePermissionCommandOutput) => void),
cb?: (err: any, data?: RemovePermissionCommandOutput) => void
): Promise<RemovePermissionCommandOutput> | void {
const command = new RemovePermissionCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Removes the specified targets from the specified rule. When the rule is triggered, those
* targets are no longer be invoked.</p>
*
* <p>When you remove a target, when the associated rule triggers, removed targets might
* continue to be invoked. Allow a short period of time for changes to take effect.</p>
*
* <p>This action can partially fail if too many requests are made at the same time. If that
* happens, <code>FailedEntryCount</code> is non-zero in the response and each entry in
* <code>FailedEntries</code> provides the ID of the failed target and the error code.</p>
*/
public removeTargets(
args: RemoveTargetsCommandInput,
options?: __HttpHandlerOptions
): Promise<RemoveTargetsCommandOutput>;
public removeTargets(
args: RemoveTargetsCommandInput,
cb: (err: any, data?: RemoveTargetsCommandOutput) => void
): void;
public removeTargets(
args: RemoveTargetsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: RemoveTargetsCommandOutput) => void
): void;
public removeTargets(
args: RemoveTargetsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RemoveTargetsCommandOutput) => void),
cb?: (err: any, data?: RemoveTargetsCommandOutput) => void
): Promise<RemoveTargetsCommandOutput> | void {
const command = new RemoveTargetsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Starts the specified replay. Events are not necessarily replayed in the exact same order
* that they were added to the archive. A replay processes events to replay based on the time in
* the event, and replays them using 1 minute intervals. If you specify an
* <code>EventStartTime</code> and an <code>EventEndTime</code> that covers a 20 minute time
* range, the events are replayed from the first minute of that 20 minute range first. Then the
* events from the second minute are replayed. You can use <code>DescribeReplay</code> to
* determine the progress of a replay. The value returned for <code>EventLastReplayedTime</code>
* indicates the time within the specified time range associated with the last event
* replayed.</p>
*/
public startReplay(args: StartReplayCommandInput, options?: __HttpHandlerOptions): Promise<StartReplayCommandOutput>;
public startReplay(args: StartReplayCommandInput, cb: (err: any, data?: StartReplayCommandOutput) => void): void;
public startReplay(
args: StartReplayCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: StartReplayCommandOutput) => void
): void;
public startReplay(
args: StartReplayCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: StartReplayCommandOutput) => void),
cb?: (err: any, data?: StartReplayCommandOutput) => void
): Promise<StartReplayCommandOutput> | void {
const command = new StartReplayCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Assigns one or more tags (key-value pairs) to the specified EventBridge resource. Tags can
* help you organize and categorize your resources. You can also use them to scope user
* permissions by granting a user permission to access or change only resources with certain tag
* values. In EventBridge, rules and event buses can be tagged.</p>
* <p>Tags don't have any semantic meaning to Amazon Web Services and are interpreted strictly as strings of
* characters.</p>
* <p>You can use the <code>TagResource</code> action with a resource that already has tags. If
* you specify a new tag key, this tag is appended to the list of tags associated with the
* resource. If you specify a tag key that is already associated with the resource, the new tag
* value that you specify replaces the previous value for that tag.</p>
* <p>You can associate as many as 50 tags with a resource.</p>
*/
public tagResource(args: TagResourceCommandInput, options?: __HttpHandlerOptions): Promise<TagResourceCommandOutput>;
public tagResource(args: TagResourceCommandInput, cb: (err: any, data?: TagResourceCommandOutput) => void): void;
public tagResource(
args: TagResourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: TagResourceCommandOutput) => void
): void;
public tagResource(
args: TagResourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: TagResourceCommandOutput) => void),
cb?: (err: any, data?: TagResourceCommandOutput) => void
): Promise<TagResourceCommandOutput> | void {
const command = new TagResourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Tests whether the specified event pattern matches the provided event.</p>
* <p>Most services in Amazon Web Services treat : or / as the same character in Amazon Resource Names (ARNs).
* However, EventBridge uses an exact match in event patterns and rules. Be sure to use the
* correct ARN characters when creating event patterns so that they match the ARN syntax in the
* event you want to match.</p>
*/
public testEventPattern(
args: TestEventPatternCommandInput,
options?: __HttpHandlerOptions
): Promise<TestEventPatternCommandOutput>;
public testEventPattern(
args: TestEventPatternCommandInput,
cb: (err: any, data?: TestEventPatternCommandOutput) => void
): void;
public testEventPattern(
args: TestEventPatternCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: TestEventPatternCommandOutput) => void
): void;
public testEventPattern(
args: TestEventPatternCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: TestEventPatternCommandOutput) => void),
cb?: (err: any, data?: TestEventPatternCommandOutput) => void
): Promise<TestEventPatternCommandOutput> | void {
const command = new TestEventPatternCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Removes one or more tags from the specified EventBridge resource. In Amazon EventBridge
* (CloudWatch Events), rules and event buses can be tagged.</p>
*/
public untagResource(
args: UntagResourceCommandInput,
options?: __HttpHandlerOptions
): Promise<UntagResourceCommandOutput>;
public untagResource(
args: UntagResourceCommandInput,
cb: (err: any, data?: UntagResourceCommandOutput) => void
): void;
public untagResource(
args: UntagResourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UntagResourceCommandOutput) => void
): void;
public untagResource(
args: UntagResourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UntagResourceCommandOutput) => void),
cb?: (err: any, data?: UntagResourceCommandOutput) => void
): Promise<UntagResourceCommandOutput> | void {
const command = new UntagResourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Updates an API destination.</p>
*/
public updateApiDestination(
args: UpdateApiDestinationCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateApiDestinationCommandOutput>;
public updateApiDestination(
args: UpdateApiDestinationCommandInput,
cb: (err: any, data?: UpdateApiDestinationCommandOutput) => void
): void;
public updateApiDestination(
args: UpdateApiDestinationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateApiDestinationCommandOutput) => void
): void;
public updateApiDestination(
args: UpdateApiDestinationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateApiDestinationCommandOutput) => void),
cb?: (err: any, data?: UpdateApiDestinationCommandOutput) => void
): Promise<UpdateApiDestinationCommandOutput> | void {
const command = new UpdateApiDestinationCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Updates the specified archive.</p>
*/
public updateArchive(
args: UpdateArchiveCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateArchiveCommandOutput>;
public updateArchive(
args: UpdateArchiveCommandInput,
cb: (err: any, data?: UpdateArchiveCommandOutput) => void
): void;
public updateArchive(
args: UpdateArchiveCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateArchiveCommandOutput) => void
): void;
public updateArchive(
args: UpdateArchiveCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateArchiveCommandOutput) => void),
cb?: (err: any, data?: UpdateArchiveCommandOutput) => void
): Promise<UpdateArchiveCommandOutput> | void {
const command = new UpdateArchiveCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Updates settings for a connection.</p>
*/
public updateConnection(
args: UpdateConnectionCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateConnectionCommandOutput>;
public updateConnection(
args: UpdateConnectionCommandInput,
cb: (err: any, data?: UpdateConnectionCommandOutput) => void
): void;
public updateConnection(
args: UpdateConnectionCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateConnectionCommandOutput) => void
): void;
public updateConnection(
args: UpdateConnectionCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateConnectionCommandOutput) => void),
cb?: (err: any, data?: UpdateConnectionCommandOutput) => void
): Promise<UpdateConnectionCommandOutput> | void {
const command = new UpdateConnectionCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.